feat(emr-containers): run a job run's Spark job in a container (#9203)

An EMR on EKS job run ran nothing: it was COMPLETED at once, or RUNNING
on a timer and then COMPLETED, whatever its Spark job would have done.

- With floci.services.emrcontainers.runner-mode set to docker, a run
  runs its Spark job in a container of its release's EMR on EKS base
  image on Amazon ECR Public, or of its custom image: a
  sparkSubmitJobDriver's spark-submit, or a sparkSqlJobDriver's
  spark-sql with its entry point as the file it runs, with the
  spark-defaults of its configurationOverrides and its execution role's
  credentials, on Floci's S3.
- The release label names the image's repository and tag, as the
  development guide's release notes give each release's "Container
  image tag": emr-7.2.0-20240610 runs emr-7.2.0:20240610. The base
  image's spark-defaults.conf runs a driver in Kubernetes' cluster
  mode, so the driver runs in client mode, its executors with it.
- A run is SUBMITTED while its container starts, RUNNING once its
  driver runs, and COMPLETED or FAILED as the driver exits, a failed
  driver with AWS's USER_ERROR and "Jobrun failed. Main Spark container
  terminated with errors. ...". A container that cannot start, a job
  driver without an entry point, and a run a restart left running fail
  with the development guide's INTERNAL_ERROR and VALIDATION_ERROR
  answers.
- CancelJobRun makes a running run CANCEL_PENDING until its driver is
  stopped, then CANCELLED.
- A run holds its virtual cluster's running slot from its submission
  until its driver ends, counting as concurrent, not queued, and the
  slot then goes to the queue. A run that cannot be handed to a thread
  fails and frees its slot, and a leftover driver of a run found failed
  is removed.
- The immediate runner mode, the default, is unchanged.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 09:33:41 -04:00
1 parent 4d96d3e662
commit 84cbee7d6f
13 files changed
+1300 -62

No files matched your search

+3
View File
@@ -139,6 +139,9 @@ starts EmrServerlessSparkConnectNightlyIntegrationTest EmrServerlessDashboardNig
# The nightly EmrSessionServerNightlyIntegrationTest runs an EMR session's Spark Connect server on an emr-spark-8.1.0
# cluster, Spark 4, sessions needing the AWS runtime for Apache Spark, and its client in that image.
starts EmrSessionServerNightlyIntegrationTest && ecr public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.0:latest
# The nightly EmrContainersSparkNightlyIntegrationTest runs EMR on EKS job runs in the emr-7.5.0 release's EMR on EKS
# base image, about 5 GB.
starts EmrContainersSparkNightlyIntegrationTest && ecr public.ecr.aws/emr-on-eks/spark/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)
+7 -5
View File
@@ -31,9 +31,11 @@ jobs:
# Each group runs its checks one after another, within their own @Timeout bounds, plus about twenty minutes for
# compilation, the image and the prefetch; together they would exceed the 360 minutes a hosted runner gives one
# job. standard holds every check but the EMR Docker runner's, 339 minutes. docker-runner holds
# EmrDockerRunnerNightlyIntegrationTest's eleven two-minute tests and two-minute setup, and
# EmrClusterShrinkNightlyIntegrationTest's sixteen-minute method and two-minute setup, 42 minutes. A check added,
# or a bound raised, raises its group's timeout with it, so a slow check fails with its own message.
# EmrDockerRunnerNightlyIntegrationTest's eleven two-minute tests and two-minute setup,
# EmrClusterShrinkNightlyIntegrationTest's sixteen-minute method and two-minute setup, and
# EmrContainersSparkNightlyIntegrationTest's three six-minute methods, eleven-minute method, two-minute setup before
# each and 21-minute image pull, 100 minutes. A check added, or a bound raised, raises its group's timeout with it,
# so a slow check fails with its own message.
strategy:
fail-fast: false
matrix:
@@ -41,7 +43,7 @@ jobs:
- group: standard
timeout: 359
- group: docker-runner
timeout: 62
timeout: 120
timeout-minutes: ${{ matrix.timeout }}
# A fork's schedule would spend its owner's minutes on checks it never asked for; a draft waits until it is
# ready for review, as the CI shards do.
@@ -73,7 +75,7 @@ jobs:
mv selected.txt all-nightly.txt
fi
fi
runner='/(EmrDockerRunner|EmrClusterShrink)NightlyIntegrationTest$'
runner='/(EmrDockerRunner|EmrClusterShrink|EmrContainersSpark)NightlyIntegrationTest$'
if [ "$GROUP" = "docker-runner" ]; then
grep -E "$runner" all-nightly.txt > nightly.txt || true
else
+59 -8
View File
@@ -7,14 +7,19 @@
Floci implements the Amazon EMR on EKS (`emr-containers`) API: virtual clusters, job runs, job
templates, managed endpoints, security configurations and tags. It is the API Airflow's
`EmrContainerOperator`, the `aws emr-containers` CLI and the SDKs call. Floci keeps the records and
moves job runs through their states; it does not run Spark on Kubernetes.
moves job runs through their states, and in the `docker` runner mode runs each job run's Spark job in a
container (see [Running job runs](#running-job-runs)).
## Configuration
| Key | Description | Default |
|-----|-------------|---------|
| `floci.services.emrcontainers.enabled` | Whether the EMR on EKS API is enabled | `true` |
| `floci.services.emrcontainers.job-run-duration-seconds` | How long a job run stays `RUNNING` before it is `COMPLETED`; `0` completes it as soon as it is submitted | `0` |
| `floci.services.emrcontainers.job-run-duration-seconds` | In the `immediate` runner mode, how long a job run stays `RUNNING` before it is `COMPLETED`; `0` completes it as soon as it is submitted | `0` |
| `floci.services.emrcontainers.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each job run's Spark job in a container (see [Running job runs](#running-job-runs)) | `immediate` |
| `floci.services.emrcontainers.docker-network` | Docker network for job run containers | the global default |
| `floci.services.emrcontainers.image-template` | Image for a `docker` job run that names no custom image, `%s` standing for its release's container image tag, `emr-7.2.0:20240610` for `emr-7.2.0-20240610` | `public.ecr.aws/emr-on-eks/spark/%s` |
| `floci.services.emrcontainers.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` |
| `floci.storage.services.emrcontainers.mode` | Storage mode for EMR on EKS resources | the global storage mode |
| `floci.storage.services.emrcontainers.flush-interval-ms` | Flush interval for persistent storage | `5000` |
@@ -71,10 +76,11 @@ not.
AWS's "Common errors when running jobs" page gives them. When Floci's EKS has no cluster of the virtual
cluster's container provider id in the request's account and Region, the run is `FAILED` with
`stateDetails` "Cluster *id* does not exist." and `failureReason` `CLUSTER_UNAVAILABLE`, as that page
gives it. Otherwise the run is `COMPLETED` at once, or `RUNNING` for
`job-run-duration-seconds` and then `COMPLETED`. `CancelJobRun` moves a run that has not finished to
`CANCELLED`. A run with a `retryPolicyConfiguration` reports `retryPolicyExecution` with one attempt.
The release label is not checked against EMR on EKS's releases.
gives it. Otherwise, in the `immediate` runner mode, the run is `COMPLETED` at once, or `RUNNING` for
`job-run-duration-seconds` and then `COMPLETED`, and `CancelJobRun` moves a run that has not finished to
`CANCELLED`; in the `docker` one it runs (see [Running job runs](#running-job-runs)). A run with a
`retryPolicyConfiguration` reports `retryPolicyExecution` with one attempt. The release label is not
checked against EMR on EKS's releases.
**Concurrent job limits.** `StartJobRun` applies the virtual cluster's limits, as the development guide's
"Concurrent job limits for virtual clusters" describes them. At most `maxConcurrentJobRuns` runs are
@@ -83,8 +89,11 @@ running slot frees up, the run first in the queue starts. Once `maxInQueueJobRun
refuses another with `ValidationException`. A run still queued 30 minutes after it was submitted is `FAILED`,
as the guide's "buffered jobs fail after 30 minutes if no slot frees up" has it. A higher limit, a cleared
one, or a cancelled run starts queued runs at once. The guide gives neither message, so the refusal's and
the timed-out run's `stateDetails` are Floci's wording. A run takes its slot only while it is `RUNNING`, so
with the default `job-run-duration-seconds` of `0` no run waits.
the timed-out run's `stateDetails` are Floci's wording. In the `immediate` runner mode a run takes its slot
only while it is `RUNNING`, so with the default `job-run-duration-seconds` of `0` no run waits. In the
`docker` one a run takes its slot as it is submitted, while its container starts, and keeps it until its
driver ends: a `SUBMITTED` or `CANCEL_PENDING` run whose container runs counts in `currentConcurrentJobRuns`, not
in `currentInQueueJobRuns`, and only the runs that wait for a slot count toward `maxInQueueJobRuns`.
**Job templates.** `StartJobRun` with a `jobTemplateId` takes `executionRoleArn`, `releaseLabel`,
`jobDriver` and `configurationOverrides` from the template where the request leaves them out, and the
@@ -121,3 +130,45 @@ are Floci's own.
Resources are scoped to the request's account and Region, and IDs follow AWS's lengths: 25 characters for
a virtual cluster, 13 for a managed endpoint and 19 for the others.
## Running job runs
With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMRCONTAINERS_RUNNER_MODE=docker`), a job run executes.
Floci starts one container per run from its custom image, if it names one, or else from its release's base
image, the one AWS publishes for customizing EMR on EKS images on Amazon ECR Public ("For Amazon EMR 6.9.0
and higher, you can get the base images from the Amazon ECR Public Gallery"): the release label names the
image's repository and tag, so `emr-7.2.0-20240610` runs `public.ecr.aws/emr-on-eks/spark/emr-7.2.0:20240610`,
`emr-7.2.0-latest` its `latest`, and `emr-7.2.0-java11-latest` `emr-7.2.0-java11:latest`. The driver runs
in that container in Spark's client mode, its executors with it in Spark's local mode, where EMR on EKS runs
each in a pod of its own on the cluster. The first run of a release pulls its image, about 5 GB. The mode needs a
Docker daemon: explicitly mount `/var/run/docker.sock` when running Floci in a container or a Testcontainers
wrapper with `FLOCI_SERVICES_EMRCONTAINERS_RUNNER_MODE=docker` (see [Docker](../configuration/docker.md)).
* **What runs**: a `sparkSubmitJobDriver` runs `spark-submit` with its `sparkSubmitParameters`, its
`entryPoint` and its `entryPointArguments`; a `sparkSqlJobDriver` runs `spark-sql` with its
`sparkSqlParameters` and its `entryPoint` as the file it runs (`-f`). Both get the `spark-defaults`
properties of the run's `configurationOverrides.applicationConfiguration` before their own options, which
win; the run's other classifications are not applied. `s3://` and `s3a://` paths reach Floci's S3 through
S3A, so the entry point and its files can be read from there, and the Glue Data Catalog client is pointed at
Floci's Glue. The driver gets its execution role's credentials.
* **Image**: `spark.kubernetes.driver.container.image`, or else `spark.kubernetes.container.image`, from the
`spark-defaults` or a `--conf` in the parameters, names the run's custom image, as the development guide's
"Customizing Docker images" has it. An image in Floci's ECR is pulled from Floci's registry.
* **Driver environment and archives**: a `spark.kubernetes.driverEnv.<KEY>` property is an environment
variable of the container, and the run's `spark.archives`, or its `--archives`, are unpacked in its working
directory, a PySpark virtual environment among them.
* **States**: a run is `SUBMITTED` while its image is pulled and its container starts, and `RUNNING` once its
Spark driver runs. It is `COMPLETED` when the driver exits with code 0, and `FAILED` otherwise, with
`failureReason` `USER_ERROR` and `stateDetails` "Jobrun failed. Main Spark container terminated with errors.
Please refer logs uploaded to S3/CloudWatch based on your monitoring configuration.", as AWS answers it. A run
whose container cannot start is `FAILED` with `failureReason` `INTERNAL_ERROR` and `stateDetails` "JobRun
submission failed due to an internal error.", the reason after it Floci's. `CancelJobRun` makes a run whose
container runs `CANCEL_PENDING` until its driver is stopped, then `CANCELLED`; a run still queued is
`CANCELLED` at once. A run Floci was running when it stopped is `FAILED` once it is read again, with
`failureReason` `INTERNAL_ERROR` and `stateDetails` "Trouble monitoring your JobRun due to an internal
error". Floci's shutdown and a state reset stop every driver, and a driver a hard stop left running is
removed when Floci starts again, unless `reconcile-containers-on-startup` is off.
* **Not emulated yet**: the driver's output goes to Floci's log only, not to the run's
`monitoringConfiguration` destinations in S3 or CloudWatch Logs; a `retryPolicyConfiguration` does not
start the driver again; and a run waits for its container however long it takes, with no
`job-start-timeout`.
@@ -1205,13 +1205,49 @@ public interface EmulatorConfig {
boolean enabled();
/**
* How long a job run stays RUNNING before it completes; 0, the default, completes a job run as
* soon as it is submitted. Floci follows the job run states without running Spark on Kubernetes.
* How long a job run stays RUNNING before it completes in the {@code immediate} runner mode; 0, the default,
* completes a job run as soon as it is submitted.
*
* Env var: FLOCI_SERVICES_EMRCONTAINERS_JOB_RUN_DURATION_SECONDS
*/
@WithDefault("0")
int jobRunDurationSeconds();
/**
* {@code immediate} follows the job run states without running anything; {@code docker} runs each job run's
* Spark job, its {@code spark-submit} or {@code spark-sql}, in a container of its release's EMR on EKS image.
*
* Env var: FLOCI_SERVICES_EMRCONTAINERS_RUNNER_MODE
*/
@WithDefault("immediate")
String runnerMode();
/**
* The Docker network a {@code docker} job run's container joins; the global default when omitted.
*
* Env var: FLOCI_SERVICES_EMRCONTAINERS_DOCKER_NETWORK
*/
Optional<String> dockerNetwork();
/**
* The image a {@code docker} job run uses when it names no custom image, with {@code %s} standing for its
* release's container image tag, {@code emr-7.2.0:20240610} for {@code emr-7.2.0-20240610}, for example
* "registry.internal/emr-on-eks/spark/%s". If omitted, Floci uses the release's base image on Amazon ECR
* Public.
*
* Env var: FLOCI_SERVICES_EMRCONTAINERS_IMAGE_TEMPLATE
*/
Optional<String> imageTemplate();
/**
* When true, Floci removes, in the {@code docker} runner mode, every EMR on EKS driver a previous run of
* <em>this same</em> Floci left on the daemon before its first job run starts. Turn it off when two Floci
* instances share a daemon with the same port and no resource namespace.
*
* Env var: FLOCI_SERVICES_EMRCONTAINERS_RECONCILE_CONTAINERS_ON_STARTUP
*/
@WithDefault("true")
boolean reconcileContainersOnStartup();
}
interface EmrServerlessServiceConfig {
@@ -14,6 +14,7 @@ import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.StoredResourceArns;
@@ -22,9 +23,13 @@ import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.eks.model.AccessConfig;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.math.BigDecimal;
import java.time.Clock;
@@ -40,23 +45,29 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* EMR on EKS ({@code emr-containers}): virtual clusters, job runs, job templates, managed endpoints
* and security configurations, as control-plane records. A job run follows the job run states
* without running Spark on Kubernetes: it completes as soon as it is submitted, or after
* {@code floci.services.emrcontainers.job-run-duration-seconds}, and fails as AWS documents when
* and security configurations, as control-plane records. In the {@code immediate} runner mode a job run
* follows the job run states without running anything: it completes as soon as it is submitted, or after
* {@code floci.services.emrcontainers.job-run-duration-seconds}. In the {@code docker} one it runs its Spark
* job in a container ({@link EmrContainersSparkJobs}): SUBMITTED while the container starts, RUNNING once its
* driver runs, and COMPLETED or FAILED as its driver exits. Either way it fails as AWS documents when
* Floci's EKS has no cluster of the virtual cluster's name. A virtual cluster's concurrent job
* limits hold a run beyond its running limit in a queue, and refuse one beyond its queue depth.
*
@@ -67,6 +78,7 @@ import java.util.regex.Pattern;
public class EmrContainersService implements Resettable, StoredResourceArns {
static final String SERVICE = "emr-containers";
private static final Logger LOG = Logger.getLogger(EmrContainersService.class);
static final String VIRTUAL_CLUSTERS = "/virtualclusters/";
static final String JOB_RUNS = "/jobruns/";
static final String ENDPOINTS = "/endpoints/";
@@ -85,13 +97,30 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
private static final Set<String> ACCESS_ENTRY_MODES = Set.of("API", "API_AND_CONFIG_MAP");
private static final String RUNNING = "RUNNING";
private static final String PENDING = "PENDING";
private static final String SUBMITTED = "SUBMITTED";
private static final String CANCEL_PENDING = "CANCEL_PENDING";
private static final String TERMINATED = "TERMINATED";
private static final String COMPLETED = "COMPLETED";
private static final String CANCELLED = "CANCELLED";
private static final String FAILED = "FAILED";
private static final String ACTIVE = "ACTIVE";
private static final Set<String> FINISHED_JOB_RUN_STATES = Set.of(COMPLETED, CANCELLED, FAILED);
private static final Set<String> QUEUED_JOB_RUN_STATES = Set.of(PENDING, "SUBMITTED");
private static final Set<String> QUEUED_JOB_RUN_STATES = Set.of(PENDING, SUBMITTED);
// The states of a run whose container runs, or is about to, in the docker runner mode: each holds a running slot.
private static final Set<String> LAUNCHED_JOB_RUN_STATES = Set.of(SUBMITTED, RUNNING, CANCEL_PENDING);
private static final String RUNNER_DOCKER = "docker";
// AWS's answer for a run whose Spark driver exits with an error, as DescribeJobRun gave it (apache/iceberg#4804).
private static final String DRIVER_FAILED = "Jobrun failed. Main Spark container terminated with errors. Please "
+ "refer logs uploaded to S3/CloudWatch based on your monitoring configuration.";
// AWS's "Common errors when running jobs": a submission that failed for an internal error, and a run whose
// monitoring an internal error ended, as a Floci restart ends a running driver's.
private static final String SUBMISSION_FAILED = "JobRun submission failed due to an internal error.";
private static final String MONITORING_FAILED = "Trouble monitoring your JobRun due to an internal error";
// The same page's answer for a run whose StartJobRun parameters are not valid.
private static final String INVALID_SUBMISSION = "JobRun submission failed.";
private static final String USER_ERROR = "USER_ERROR";
private static final String INTERNAL_ERROR = "INTERNAL_ERROR";
private static final String VALIDATION_ERROR = "VALIDATION_ERROR";
// The development guide's concurrent job limits: "By default, the per-virtual-cluster concurrency limit is set
// to 1000 concurrent job runs", and "buffered jobs fail after 30 minutes if no slot frees up".
private static final int DEFAULT_MAX_CONCURRENT_JOB_RUNS = 1000;
@@ -121,18 +150,37 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
private final RequestContext requestContext;
private final Clock clock;
private final int jobRunDurationSeconds;
// The runner of the docker runner mode, or null in the immediate one.
private final SparkJobRunner sparkRunner;
private final Executor runExecutor;
// image-template and docker-network, each null when not set.
private final String imageTemplate;
private final String dockerNetwork;
// The ARNs of the runs whose containers a thread of this process runs; a launched run not here was left by a
// restart.
private final Set<String> executing = new HashSet<>();
// Raised by each reset, so a run's thread from before it writes nothing back after the wipe.
private long generation;
@Inject
public EmrContainersService(StorageFactory storageFactory, ObjectMapper mapper, RegionResolver regionResolver,
EksService eksService, IamService iamService, RequestContext requestContext,
Clock clock, EmulatorConfig config) {
Clock clock, EmulatorConfig config, EmrServerlessSparkRunner sparkRunner) {
this(storage(storageFactory, "emr-containers-virtual-clusters.json"),
storage(storageFactory, "emr-containers-job-runs.json"),
storage(storageFactory, "emr-containers-endpoints.json"),
storage(storageFactory, "emr-containers-job-templates.json"),
storage(storageFactory, "emr-containers-security-configurations.json"),
mapper, regionResolver, eksService, iamService, requestContext, clock,
config.services().emrcontainers().jobRunDurationSeconds());
config.services().emrcontainers().jobRunDurationSeconds(),
RUNNER_DOCKER.equalsIgnoreCase(config.services().emrcontainers().runnerMode()) ? sparkRunner : null,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-containers-run-", 0).factory()),
config.services().emrcontainers().imageTemplate().orElse(null),
config.services().emrcontainers().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().emrcontainers().reconcileContainersOnStartup()) {
sparkRunner.removeLeftoverDrivers(SERVICE);
}
}
EmrContainersService(AccountAwareStorageBackend<ObjectNode> virtualClusters,
@@ -143,6 +191,19 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
ObjectMapper mapper, RegionResolver regionResolver, EksService eksService,
IamService iamService, RequestContext requestContext, Clock clock,
int jobRunDurationSeconds) {
this(virtualClusters, jobRuns, endpoints, jobTemplates, securityConfigurations, mapper, regionResolver,
eksService, iamService, requestContext, clock, jobRunDurationSeconds, null, Runnable::run, null, null);
}
EmrContainersService(AccountAwareStorageBackend<ObjectNode> virtualClusters,
AccountAwareStorageBackend<ObjectNode> jobRuns,
AccountAwareStorageBackend<ObjectNode> endpoints,
AccountAwareStorageBackend<ObjectNode> jobTemplates,
AccountAwareStorageBackend<ObjectNode> securityConfigurations,
ObjectMapper mapper, RegionResolver regionResolver, EksService eksService,
IamService iamService, RequestContext requestContext, Clock clock,
int jobRunDurationSeconds, SparkJobRunner sparkRunner, Executor runExecutor,
String imageTemplate, String dockerNetwork) {
this.virtualClusters = virtualClusters;
this.jobRuns = jobRuns;
this.endpoints = endpoints;
@@ -155,6 +216,17 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
this.requestContext = requestContext;
this.clock = clock;
this.jobRunDurationSeconds = jobRunDurationSeconds;
this.sparkRunner = sparkRunner;
this.runExecutor = runExecutor;
this.imageTemplate = imageTemplate;
this.dockerNetwork = dockerNetwork;
}
@PreDestroy
void shutdown() {
if (runExecutor instanceof ExecutorService executor) {
executor.shutdownNow();
}
}
private static AccountAwareStorageBackend<ObjectNode> storage(StorageFactory storageFactory, String file) {
@@ -336,8 +408,9 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
// Concurrent job limits are "enforced at StartJobRun, before any pods are created": a run beyond the
// running limit waits in the queue, and "once the queue is full, StartJobRun rejects further submissions".
List<ObjectNode> runs = settledRuns(cluster);
boolean slotFree = count(runs, RUNNING::equals) < maxConcurrentJobRuns(cluster);
long queued = count(runs, QUEUED_JOB_RUN_STATES::contains);
boolean slotFree = runs.stream().filter(EmrContainersService::holdsSlot).count()
< maxConcurrentJobRuns(cluster);
long queued = runs.stream().filter(EmrContainersService::waitsForSlot).count();
JsonNode maxInQueue = cluster.path("schedulerConfiguration").path("maxInQueueJobRuns");
if (!slotFree && maxInQueue.isIntegralNumber() && queued >= maxInQueue.longValue()) {
// The guide gives ValidationException, not its message; the wording is Floci's.
@@ -360,6 +433,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
start(run, now);
}
jobRuns.put(arn, run);
launch(List.of(run));
return pick(run, "id", "name", "arn", "virtualClusterId");
}
@@ -388,6 +462,16 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
throw invalid("Job run " + id + " is " + state + " and can't be cancelled.");
}
ObjectNode cancelled = run.deepCopy();
if (CANCEL_PENDING.equals(state)) {
return object("id", id).put("virtualClusterId", virtualClusterId);
} else if (launched(run)) {
// "CANCEL_PENDING - A job run has been requested for cancellation. Amazon EMR on EKS is trying to cancel
// the job on the virtual cluster", until its driver is stopped.
cancelled.put("state", CANCEL_PENDING);
jobRuns.put(cancelled.get("arn").textValue(), cancelled);
runExecutor.execute(() -> sparkRunner.stop(id));
return object("id", id).put("virtualClusterId", virtualClusterId);
}
finish(cancelled, CANCELLED, now());
jobRuns.put(cancelled.get("arn").textValue(), cancelled);
// A running slot it frees goes to the queue's first run now.
@@ -675,8 +759,20 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
return resource.startsWith(SECURITY_CONFIGURATIONS) ? securityConfigurations : null;
}
/**
* 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 stops their drivers.
*/
@Override
public synchronized void beforeReset() {
generation++;
executing.clear();
}
@Override
public synchronized void clear() {
generation++;
executing.clear();
virtualClusters.clear();
jobRuns.clear();
endpoints.clear();
@@ -890,13 +986,28 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
* happened: a RUNNING run completes once its duration has passed, and the running slot it frees goes at that
* moment to the run first in the queue, "As running slots free up, queued job runs start automatically"; a run
* still queued 30 minutes after it was submitted fails. A slot free now, once the limit is raised or a run is
* cancelled, goes to the queue now.
* cancelled, goes to the queue now. A run whose container runs holds its slot until its driver ends, and one
* whose container no thread of this process runs, as after a restart, has failed.
*/
private List<ObjectNode> settledRuns(ObjectNode cluster) {
String prefix = cluster.get("arn").textValue() + JOB_RUNS;
List<ObjectNode> runs = jobRuns.scan(key -> key.startsWith(prefix)).stream()
.map(ObjectNode::deepCopy)
.toList();
Instant now = now();
// By identity: a node's equality is its content, which changes here.
Set<ObjectNode> changed = Collections.newSetFromMap(new IdentityHashMap<>());
List<String> leftovers = new ArrayList<>();
for (ObjectNode run : runs) {
if (launched(run) && !executing.contains(run.get("arn").textValue())) {
finish(run, FAILED, now);
run.put("stateDetails", MONITORING_FAILED);
run.put("failureReason", INTERNAL_ERROR);
changed.add(run);
leftovers.add(run.get("id").textValue());
}
}
int held = (int) runs.stream().filter(EmrContainersService::launched).count();
// The running runs by when they complete, and the queue in order: a run's DUE_AT never changes in there.
PriorityQueue<ObjectNode> running = new PriorityQueue<>(Comparator.comparing(EmrContainersService::dueAt));
runs.stream()
@@ -907,9 +1018,6 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
.sorted(Comparator.comparingLong(run -> run.get(QUEUE_POSITION).longValue()))
.toList());
int limit = maxConcurrentJobRuns(cluster);
Instant now = now();
// By identity: a node's equality is its content, which changes here.
Set<ObjectNode> changed = Collections.newSetFromMap(new IdentityHashMap<>());
while (true) {
ObjectNode ending = running.peek();
Instant endsAt = ending != null && !dueAt(ending).isAfter(now) ? dueAt(ending) : null;
@@ -927,38 +1035,63 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
running.poll();
finish(ending, COMPLETED, endsAt);
changed.add(ending);
startQueued(running, queue, limit, endsAt, changed);
held += startQueued(running, queue, limit - held, endsAt, changed);
} else {
break;
}
}
startQueued(running, queue, limit, now, changed);
startQueued(running, queue, limit - held, now, changed);
// In one write: a persistent store rewrites its file on each.
if (!changed.isEmpty()) {
Map<String, ObjectNode> writes = new LinkedHashMap<>();
changed.forEach(run -> writes.put(run.get("arn").textValue(), run));
jobRuns.putAll(writes);
}
// A driver of theirs the startup's cleanup left goes, off the request's thread.
if (sparkRunner != null) {
leftovers.forEach(id -> runExecutor.execute(() -> sparkRunner.removeLeftoverDriver(SERVICE, id)));
}
// Once stored: a run's thread reads it.
launch(changed);
return runs;
}
// Starts the queue's first runs at the moment {@code at} while the running limit leaves a slot.
private void startQueued(PriorityQueue<ObjectNode> running, Deque<ObjectNode> queue, int limit, Instant at,
Set<ObjectNode> changed) {
while (running.size() < limit && !queue.isEmpty()) {
/**
* Starts the queue's first runs at the moment {@code at} while the running limit, less the slots launched runs
* hold, leaves a slot. Answers how many of them were launched, each holding a slot until its driver ends.
*/
private int startQueued(PriorityQueue<ObjectNode> running, Deque<ObjectNode> queue, int limit, Instant at,
Set<ObjectNode> changed) {
int launched = 0;
while (running.size() + launched < limit && !queue.isEmpty()) {
ObjectNode run = queue.pollFirst();
start(run, at);
changed.add(run);
if (run.has(DUE_AT)) {
running.add(run);
} else if (launched(run)) {
launched++;
}
}
return launched;
}
// A run starts: RUNNING for the configured duration, or completed at once without one.
/**
* A run starts. In the docker runner mode it is SUBMITTED, "successfully submitted to the virtual cluster", until
* its driver runs, or FAILED where its job driver names no entry point to run; in the immediate one it is RUNNING
* for the configured duration, or completed at once without one.
*/
private void start(ObjectNode run, Instant at) {
run.remove(QUEUE_POSITION);
if (jobRunDurationSeconds <= 0) {
if (sparkRunner != null && EmrContainersSparkJobs.entryPoint(run) == null) {
// Kept, not refused: AWS's "Common errors when running jobs" gives a run whose StartJobRun parameters "are
// not valid" as one DescribeJobRun answers FAILED, "JobRun submission failed." with VALIDATION_ERROR.
finish(run, FAILED, at);
run.put("stateDetails", INVALID_SUBMISSION);
run.put("failureReason", VALIDATION_ERROR);
} else if (sparkRunner != null) {
run.put("state", SUBMITTED);
} else if (jobRunDurationSeconds <= 0) {
finish(run, COMPLETED, at);
} else {
run.put("state", RUNNING);
@@ -966,6 +1099,130 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
}
}
// Whether a run's container runs, or is about to: it has no set end, unlike a RUNNING run of the immediate mode.
private static boolean launched(ObjectNode run) {
return LAUNCHED_JOB_RUN_STATES.contains(run.path("state").textValue()) && !run.has(DUE_AT);
}
// Whether a run holds one of its virtual cluster's running slots: it runs, or its container is about to.
private static boolean holdsSlot(ObjectNode run) {
return RUNNING.equals(run.path("state").textValue()) || launched(run);
}
// Whether a run waits in its virtual cluster's queue: queued, and holding no running slot.
private static boolean waitsForSlot(ObjectNode run) {
return QUEUED_JOB_RUN_STATES.contains(run.path("state").textValue()) && !holdsSlot(run);
}
/**
* Hands each of {@code runs} that was just submitted in the docker runner mode to a thread of its own, which runs
* its Spark job to its end. Each is counted as running before any starts: a thread that runs at once reads the
* others. One that cannot be handed off, its thread refused as Floci shuts down, fails, and its slot goes to the
* queue.
*/
private void launch(Collection<ObjectNode> runs) {
if (sparkRunner == null) {
return;
}
List<ObjectNode> submitted = runs.stream()
.filter(run -> SUBMITTED.equals(run.path("state").textValue()))
.filter(run -> !executing.contains(run.get("arn").textValue()))
.toList();
submitted.forEach(run -> executing.add(run.get("arn").textValue()));
long launchedIn = generation;
Set<String> freed = new LinkedHashSet<>();
for (ObjectNode run : submitted) {
String arn = run.get("arn").textValue();
try {
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, imageTemplate, dockerNetwork);
runExecutor.execute(() -> execute(arn, job, launchedIn));
} catch (RuntimeException e) {
LOG.warnv(e, "EMR on EKS job run {0} could not be handed to a thread", run.get("id").textValue());
executing.remove(arn);
ObjectNode failed = run.deepCopy();
finish(failed, FAILED, now());
failed.put("stateDetails", submissionFailed(e.getMessage()));
failed.put("failureReason", INTERNAL_ERROR);
jobRuns.put(arn, failed);
freed.add(run.get("virtualClusterId").textValue());
}
}
freed.forEach(this::settledRuns);
}
// AWS's sentence, then what kept Floci from starting the run's driver, which is Floci's own.
private static String submissionFailed(String reason) {
return SUBMISSION_FAILED + " Floci could not start its driver: " + reason;
}
private void execute(String arn, SparkJobRunner.Job job, long launchedIn) {
SparkJobRunner.Outcome outcome;
try {
outcome = sparkRunner.run(job, new RunProgress(arn, job, launchedIn));
} catch (RuntimeException e) {
LOG.warnv(e, "EMR on EKS job run {0} could not run", job.runId());
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
}
SparkJobRunner.Outcome ended = outcome;
RequestScopes.runAs(job.accountId(), job.region(), () -> ended(arn, ended, launchedIn));
}
// A run's driver runs: "In Spark applications, this means that the Spark driver process is in the running state."
private synchronized void driverStarted(String arn, long launchedIn) {
if (launchedIn != generation) {
return;
}
jobRuns.get(arn).filter(run -> SUBMITTED.equals(run.path("state").textValue())).ifPresent(run -> {
ObjectNode running = run.deepCopy();
running.put("state", RUNNING);
jobRuns.put(arn, running);
});
}
// Whether a run's driver may still start, or go on: a cancelled run is past it, and so is one a reset removed.
private synchronized boolean stillGoing(String arn, long launchedIn) {
return launchedIn == generation && jobRuns.get(arn)
.map(run -> SUBMITTED.equals(run.path("state").textValue())
|| RUNNING.equals(run.path("state").textValue()))
.orElse(false);
}
/**
* Ends a run as its driver did: COMPLETED when it "succeeds (exits with code 0)", FAILED when it "fails (exits
* with a non-zero code)", or could not start, and CANCELLED when it was cancelled. A driver stopped otherwise was
* stopped by Floci's shutdown. The running slot it frees goes to the queue's first run.
*/
private synchronized void ended(String arn, SparkJobRunner.Outcome outcome, long launchedIn) {
if (launchedIn != generation) {
return;
}
executing.remove(arn);
ObjectNode stored = jobRuns.get(arn).orElse(null);
if (stored == null || FINISHED_JOB_RUN_STATES.contains(stored.path("state").textValue())) {
return;
}
ObjectNode run = stored.deepCopy();
Instant now = now();
if (CANCEL_PENDING.equals(run.path("state").textValue())) {
finish(run, CANCELLED, now);
} else if (outcome.exitCode() != null && outcome.exitCode() == 0) {
finish(run, COMPLETED, now);
} else {
finish(run, FAILED, now);
if (outcome.exitCode() != null) {
run.put("stateDetails", DRIVER_FAILED);
run.put("failureReason", USER_ERROR);
} else {
run.put("stateDetails", outcome.failure() != null ? submissionFailed(outcome.failure())
: MONITORING_FAILED);
run.put("failureReason", INTERNAL_ERROR);
}
}
jobRuns.put(arn, run);
LOG.infov("EMR on EKS job run {0} ended {1}", run.get("id").textValue(), run.get("state").textValue());
settledRuns(run.get("virtualClusterId").textValue());
}
private static Instant dueAt(ObjectNode run) {
return Instant.ofEpochMilli(run.get(DUE_AT).longValue());
}
@@ -1002,17 +1259,13 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
}
List<ObjectNode> runs = settledRuns(cluster);
ObjectNode status = mapper.createObjectNode();
status.put("currentInQueueJobRuns", count(runs, QUEUED_JOB_RUN_STATES::contains));
status.put("currentConcurrentJobRuns", count(runs, RUNNING::equals));
status.put("currentInQueueJobRuns", runs.stream().filter(EmrContainersService::waitsForSlot).count());
status.put("currentConcurrentJobRuns", runs.stream().filter(EmrContainersService::holdsSlot).count());
ObjectNode withStatus = cluster.deepCopy();
withStatus.set("schedulerStatus", status);
return withStatus;
}
private static long count(Collection<ObjectNode> runs, Predicate<String> state) {
return runs.stream().filter(run -> state.test(run.path("state").textValue())).count();
}
// ── JSON helpers ─────────────────────────────────────────────────────────────
private ObjectNode wrap(String member, ObjectNode resource) {
@@ -1153,4 +1406,33 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
private static AwsException invalid(String message) {
return new AwsException("ValidationException", message, 400);
}
/** What a run's thread tells the service, and asks it, while its Spark job runs. */
private final class RunProgress implements SparkJobRunner.Progress {
private final String arn;
private final SparkJobRunner.Job job;
private final long launchedIn;
RunProgress(String arn, SparkJobRunner.Job job, long launchedIn) {
this.arn = arn;
this.job = job;
this.launchedIn = launchedIn;
}
@Override
public void started() {
RequestScopes.runAs(job.accountId(), job.region(), () -> driverStarted(arn, launchedIn));
}
// A run of EMR on EKS has no timeout of its own.
@Override
public void timedOut() {
}
@Override
public boolean cancelled() {
return !RequestScopes.callAs(job.accountId(), job.region(), () -> stillGoing(arn, launchedIn));
}
}
}
@@ -0,0 +1,133 @@
package io.floci.aws.services.emrcontainers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Spark job an EMR on EKS job run runs in the {@code docker} runner mode: its {@code sparkSubmitJobDriver}'s
* {@code spark-submit}, or its {@code sparkSqlJobDriver}'s {@code spark-sql}, in a container of its release's EMR on
* EKS base image, with the {@code spark-defaults} of its {@code configurationOverrides} and its execution role's
* credentials. Its driver runs in that container, its executors with it in Spark's local mode, where EMR on EKS runs
* each in a pod of its own.
*/
final class EmrContainersSparkJobs {
/**
* The release's base image: "For Amazon EMR 6.9.0 and higher, you can get the base images from the Amazon ECR
* Public Gallery", {@code public.ecr.aws/emr-on-eks/spark/emr-7.13.0:latest} for example, with {@code %s} its
* container image tag (EMR on EKS Development Guide, "Customizing Docker images").
*/
static final String DEFAULT_IMAGE_TEMPLATE =
"public.ecr.aws/emr-on-eks/spark/%s"; // partition-literal: ECR Public, where AWS publishes the base images
private static final ObjectMapper JSON = new ObjectMapper();
private static final String SPARK_DEFAULTS = "spark-defaults";
// "You can use spark.kubernetes.driver.container.image and spark.kubernetes.executor.container.image to specify a
// different image for driver and executor pods."
private static final String CONTAINER_IMAGE = "spark.kubernetes.container.image";
private static final String DRIVER_CONTAINER_IMAGE = "spark.kubernetes.driver.container.image";
private static final String DRIVER_ENV_PREFIX = "spark.kubernetes.driverEnv.";
// The base image's spark-defaults.conf runs a driver in Kubernetes' cluster mode, which local mode refuses.
private static final String DEPLOY_MODE = "spark.submit.deployMode";
private static final String CLIENT = "client";
private static final String SPARK_SQL = "spark-sql";
// A release label is its image's repository and tag joined by a hyphen: emr-7.2.0-20240610 runs the image tagged
// emr-7.2.0:20240610, and emr-7.2.0-java11-latest the one tagged emr-7.2.0-java11:latest.
private static final Pattern RELEASE_LABEL = Pattern.compile("(.+)-(latest|\\d{8})");
private EmrContainersSparkJobs() {
}
/**
* A release's container image tag, "Container image tag: emr-7.2.0:20240610" for {@code emr-7.2.0-20240610} in
* the development guide's release notes, its repository's {@code latest} for a label of no other form.
*/
static String containerImageTag(String releaseLabel) {
Matcher label = RELEASE_LABEL.matcher(releaseLabel);
return label.matches() ? label.group(1) + ":" + label.group(2) : releaseLabel + ":latest";
}
/** The image a release's job runs use: {@code imageTemplate}, or else the release's base image. */
static String image(String imageTemplate, String releaseLabel) {
String template = imageTemplate != null ? imageTemplate : DEFAULT_IMAGE_TEMPLATE;
return template.replace("%s", containerImageTag(releaseLabel));
}
/**
* The {@code spark-defaults} properties of a run's {@code configurationOverrides}: those of each
* {@code spark-defaults} classification of its {@code applicationConfiguration}, a later one's winning.
*/
static Map<String, String> sparkDefaults(JsonNode configurationOverrides) {
JsonNode configurations = configurationOverrides != null
? configurationOverrides.path("applicationConfiguration") : null;
if (configurations == null || !configurations.isArray()) {
return new LinkedHashMap<>();
}
List<?> list = JSON.convertValue(configurations, List.class);
return EmrServerlessJobRunService.classificationProperties(list, SPARK_DEFAULTS);
}
/**
* The entry point a job run's job driver runs, its {@code sparkSqlJobDriver}'s or else its
* {@code sparkSubmitJobDriver}'s, or null where it names none, which the model allows of a Spark SQL driver.
*/
static String entryPoint(ObjectNode run) {
JsonNode jobDriver = run.path("jobDriver");
JsonNode driver = jobDriver.path("sparkSqlJobDriver").isObject() ? jobDriver.path("sparkSqlJobDriver")
: jobDriver.path("sparkSubmitJobDriver");
return driver.path("entryPoint").textValue();
}
/**
* What runs a job run's Spark job, one whose job driver names an entry point ({@link #entryPoint}): its
* {@code sparkSubmitJobDriver}'s {@code sparkSubmitParameters}, entry point and its arguments after Floci's
* settings on {@code spark-submit}'s command line, or its {@code sparkSqlJobDriver}'s {@code spark-sql} with its
* {@code sparkSqlParameters} and its entry point as the file it runs ({@code -f}). Its custom image is the one
* {@code spark.kubernetes.driver.container.image}, or else {@code spark.kubernetes.container.image}, names; its
* driver's environment its {@code spark.kubernetes.driverEnv.<KEY>} properties; its {@code spark.archives} are
* unpacked in its working directory, as they are in a pod's.
*/
static SparkJobRunner.Job job(ObjectNode run, String imageTemplate, String dockerNetwork) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(run.get("arn").textValue());
String releaseLabel = run.get("releaseLabel").textValue();
JsonNode sparkSql = run.path("jobDriver").path("sparkSqlJobDriver");
JsonNode sparkSubmit = run.path("jobDriver").path("sparkSubmitJobDriver");
String parameters = sparkSql.isObject() ? sparkSql.path("sparkSqlParameters").textValue()
: sparkSubmit.path("sparkSubmitParameters").textValue();
Map<String, String> sparkDefaults = sparkDefaults(run.get("configurationOverrides"));
sparkDefaults.put(DEPLOY_MODE, CLIENT);
Map<String, String> properties = EmrServerlessJobRunService.sparkProperties(sparkDefaults, parameters);
String customImage = properties.getOrDefault(DRIVER_CONTAINER_IMAGE, properties.get(CONTAINER_IMAGE));
List<String> application = new ArrayList<>();
List<String> command = null;
if (sparkSql.isObject()) {
command = new ArrayList<>(List.of(SPARK_SQL));
command.addAll(EmrServerlessSparkRunner.splitParameters(parameters));
command.addAll(List.of("-f", entryPoint(run)));
} else {
application.addAll(EmrServerlessSparkRunner.splitParameters(parameters));
application.add(entryPoint(run));
sparkSubmit.path("entryPointArguments").forEach(argument -> application.add(argument.asText()));
}
return new SparkJobRunner.Job(EmrContainersService.SERVICE, run.get("id").textValue(), arn.accountId(),
arn.region(), releaseLabel, SparkJobRunner.Engine.SPARK, image(imageTemplate, releaseLabel),
customImage, dockerNetwork, run.get("executionRoleArn").textValue(), sparkDefaults, application,
command, Duration.ZERO, null, null,
EmrServerlessJobRunService.environment(properties, DRIVER_ENV_PREFIX),
EmrServerlessJobRunService.archives(properties), null, Map.of(), Map.of(), Map.of(), Map.of(),
Map.of(), null);
}
}
@@ -1129,8 +1129,17 @@ public class EmrServerlessJobRunService implements Resettable {
* {@code spark-submit} has it.
*/
static Map<String, String> sparkProperties(Map<String, String> sparkDefaults, JobDriver.SparkSubmit sparkSubmit) {
return sparkProperties(sparkDefaults, sparkSubmit.getSparkSubmitParameters());
}
/**
* A Spark driver's properties: {@code sparkDefaults}, then the {@code --conf} settings and the last
* {@code --archives} option of {@code sparkSubmitParameters}, a {@code spark-submit} command line's options, as
* {@link #sparkProperties(Map, JobDriver.SparkSubmit)} reads a run's.
*/
public static Map<String, String> sparkProperties(Map<String, String> sparkDefaults, String sparkSubmitParameters) {
Map<String, String> properties = new LinkedHashMap<>(sparkDefaults);
List<String> parameters = EmrServerlessSparkRunner.splitParameters(sparkSubmit.getSparkSubmitParameters());
List<String> parameters = EmrServerlessSparkRunner.splitParameters(sparkSubmitParameters);
String archivesOption = null;
for (int i = 0; i < parameters.size(); i++) {
String parameter = parameters.get(i);
@@ -1158,10 +1167,15 @@ public class EmrServerlessJobRunService implements Resettable {
/** 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) {
return environment(sparkProperties, DRIVER_ENV_PREFIX);
}
/** The environment variables {@code sparkProperties} set by their {@code <prefix><KEY>} properties. */
public static Map<String, String> environment(Map<String, String> sparkProperties, String prefix) {
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);
if (key.startsWith(prefix) && key.length() > prefix.length()) {
environment.put(key.substring(prefix.length()), value);
}
});
return environment;
@@ -1171,7 +1185,7 @@ public class EmrServerlessJobRunService implements Resettable {
* 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) {
public static List<String> archives(Map<String, String> sparkProperties) {
String archives = sparkProperties.get(SPARK_ARCHIVES);
if (archives == null) {
return List.of();
@@ -1468,16 +1482,25 @@ public class EmrServerlessJobRunService implements Resettable {
}
}
if (overrides instanceof List<?> configurations) {
boolean replaces = !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, releaseLabel, 8, 1);
for (Object configuration : configurations) {
if (configuration instanceof Map<?, ?> members
&& classification.equals(members.get("classification"))) {
if (replaces) {
properties.clear();
replaces = false;
}
addProperties(properties, members, classification);
}
boolean named = configurations.stream().anyMatch(configuration -> configuration instanceof Map<?, ?> members
&& classification.equals(members.get("classification")));
if (named && !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, releaseLabel, 8, 1)) {
properties.clear();
}
properties.putAll(classificationProperties(configurations, classification));
}
return properties;
}
/**
* The properties of each {@code classification} configuration of {@code configurations}, a workload's own
* configuration list as the API's JSON gives it, a later configuration's winning where a property is the same.
*/
public static Map<String, String> classificationProperties(List<?> configurations, String classification) {
Map<String, String> properties = new LinkedHashMap<>();
for (Object configuration : configurations) {
if (configuration instanceof Map<?, ?> members) {
addProperties(properties, members, classification);
}
}
return properties;
+6
View File
@@ -1150,6 +1150,12 @@ floci:
emrcontainers:
enabled: true
job-run-duration-seconds: 0 # 0 = a job run completes as soon as it is submitted
runner-mode: immediate # docker = run each job run's Spark job in a container
# docker-network: floci-network
# image-template: "registry.internal/emr-on-eks/spark/%s" # %s = the container image tag, emr-7.2.0:20240610
# 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
ssoadmin:
enabled: true
ssooidc:
@@ -11,6 +11,7 @@ import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.eks.model.AccessConfig;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.emrcontainers.EmrContainersService.ListQuery;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
@@ -18,12 +19,17 @@ import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -680,4 +686,352 @@ class EmrContainersServiceTest {
assertThrows(AwsException.class, () -> service.describeVirtualCluster(clusterId));
}
// A docker runner mode service whose run threads the test runs, by runAll(), over these stores.
private EmrContainersService dockerService(FakeRunner runner, QueuedExecutor executor,
List<AccountAwareStorageBackend<ObjectNode>> stores) {
IamService iam = mock(IamService.class);
when(iam.resolveCallerArn(eq(null))).thenReturn(Optional.empty());
return new EmrContainersService(stores.get(0), stores.get(1), stores.get(2), stores.get(3), stores.get(4),
mapper, new RegionResolver(REGION, ACCOUNT_ID), eks, iam, null, clock, 0, runner, executor,
"registry.internal/emr-on-eks/spark/%s", "floci-net");
}
private EmrContainersService dockerService(FakeRunner runner, QueuedExecutor executor) {
return dockerService(runner, executor, stores());
}
private static List<AccountAwareStorageBackend<ObjectNode>> stores() {
return List.of(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
AccountAwareStorageBackend.inMemory(ACCOUNT_ID), AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
}
private static String state(JsonNode run) {
return run.get("state").textValue();
}
@Test
void dockerRunIsSubmittedThenRunningWhileItsDriverRunsThenCompleted() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = startJobRun(service, clusterId).get("id").textValue();
assertEquals("SUBMITTED", state(jobRun(service, clusterId, id)), "submitted while its container starts");
List<String> whileRunning = new ArrayList<>();
runner.whileRunning = () -> whileRunning.add(state(jobRun(service, clusterId, id)));
clock.advance(Duration.ofSeconds(42));
executor.runAll();
assertEquals(List.of("RUNNING"), whileRunning);
JsonNode run = jobRun(service, clusterId, id);
assertEquals("COMPLETED", state(run));
assertEquals("2026-01-01T00:00:42Z", run.get("finishedAt").textValue());
assertFalse(run.has("failureReason"));
SparkJobRunner.Job job = runner.jobs.getFirst();
assertEquals(id, job.runId());
assertEquals("registry.internal/emr-on-eks/spark/emr-7.5.0:latest", job.imageTemplate());
assertEquals("floci-net", job.dockerNetwork());
assertEquals(ROLE, job.executionRole());
assertEquals(List.of("s3://bucket/pi.py"), job.application());
}
@Test
void dockerRunWhoseDriverExitsWithAnErrorFailsAsAUserError() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = startJobRun(service, clusterId).get("id").textValue();
executor.runAll();
JsonNode run = jobRun(service, clusterId, id);
assertEquals("FAILED", state(run));
assertEquals("USER_ERROR", run.get("failureReason").textValue());
assertEquals("Jobrun failed. Main Spark container terminated with errors. Please refer logs uploaded to "
+ "S3/CloudWatch based on your monitoring configuration.", run.get("stateDetails").textValue());
}
@Test
void dockerRunWhoseDriverCannotStartFailsAsAnInternalError() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.couldNotStart("Could not pull image");
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = startJobRun(service, clusterId).get("id").textValue();
executor.runAll();
JsonNode run = jobRun(service, clusterId, id);
assertEquals("FAILED", state(run));
assertEquals("INTERNAL_ERROR", run.get("failureReason").textValue());
assertEquals("JobRun submission failed due to an internal error. Floci could not start its driver: "
+ "Could not pull image", run.get("stateDetails").textValue());
}
@Test
void cancellingARunningDockerRunStopsItsDriverThenCancelsIt() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = startJobRun(service, clusterId).get("id").textValue();
List<String> afterCancel = new ArrayList<>();
runner.whileRunning = () -> {
service.cancelJobRun(clusterId, id);
afterCancel.add(state(jobRun(service, clusterId, id)));
// The stop the cancel handed off, and the cancel again, which changes nothing.
executor.runAll();
service.cancelJobRun(clusterId, id);
afterCancel.add(state(jobRun(service, clusterId, id)));
};
executor.runAll();
assertEquals(List.of("CANCEL_PENDING", "CANCEL_PENDING"), afterCancel);
assertEquals(Set.of(id), runner.stopped);
assertEquals("CANCELLED", state(jobRun(service, clusterId, id)));
AwsException again = assertThrows(AwsException.class, () -> service.cancelJobRun(clusterId, id));
assertEquals("ValidationException", again.getErrorCode());
}
@Test
void dockerRunCancelledBeforeItsDriverStartsNeverStartsIt() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = startJobRun(service, clusterId).get("id").textValue();
service.cancelJobRun(clusterId, id);
executor.runAll();
assertTrue(runner.driversStarted.isEmpty());
assertEquals("CANCELLED", state(jobRun(service, clusterId, id)));
}
@Test
void dockerRunHoldsItsRunningSlotFromSubmissionUntilItsDriverEnds() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}");
String first = startJobRun(service, clusterId).get("id").textValue();
String second = startJobRun(service, clusterId).get("id").textValue();
assertEquals("SUBMITTED", state(jobRun(service, clusterId, first)));
assertEquals("PENDING", state(jobRun(service, clusterId, second)), "the submitted run holds the only slot");
assertEquals(1, executor.queued(), "only the first run's container starts");
executor.runNext();
assertEquals("COMPLETED", state(jobRun(service, clusterId, first)));
assertEquals("SUBMITTED", state(jobRun(service, clusterId, second)), "the freed slot goes to the queue");
executor.runAll();
assertEquals("COMPLETED", state(jobRun(service, clusterId, second)));
assertEquals(List.of(first, second), runner.driversStarted);
}
@Test
void cancellingAQueuedDockerRunCancelsItAtOnce() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}");
startJobRun(service, clusterId);
String queued = startJobRun(service, clusterId).get("id").textValue();
service.cancelJobRun(clusterId, queued);
assertEquals("CANCELLED", state(jobRun(service, clusterId, queued)));
assertTrue(runner.stopped.isEmpty());
}
@Test
void dockerRunAnEarlierProcessLeftRunningHasFailed() {
List<AccountAwareStorageBackend<ObjectNode>> stores = stores();
EmrContainersService earlier = dockerService(new FakeRunner(), new QueuedExecutor(), stores);
String clusterId = virtualCluster(earlier, EKS_CLUSTER);
String id = startJobRun(earlier, clusterId).get("id").textValue();
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService restarted = dockerService(runner, executor, stores);
JsonNode run = jobRun(restarted, clusterId, id);
assertEquals("FAILED", state(run));
assertEquals("INTERNAL_ERROR", run.get("failureReason").textValue());
assertEquals("Trouble monitoring your JobRun due to an internal error", run.get("stateDetails").textValue());
assertTrue(runner.leftoversRemoved.isEmpty(), "removed off the request's thread");
executor.runAll();
assertEquals(List.of(id), runner.leftoversRemoved, "a driver the startup's cleanup left goes");
}
@Test
void dockerRunsThreadFromBeforeAResetWritesNothingBack() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
startJobRun(service, clusterId);
service.beforeReset();
service.clear();
String after = virtualCluster(service, EKS_CLUSTER);
executor.runAll();
assertEquals(1, runner.jobs.size(), "its thread still ran");
assertTrue(service.listJobRuns(after, ListQuery.of(null, null, null, null, null), null)
.get("jobRuns").isEmpty());
assertThrows(AwsException.class, () -> service.describeVirtualCluster(clusterId));
}
@Test
void dockerRunWhoseJobDriverNamesNoEntryPointFailsItsSubmission() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = service.startJobRun(clusterId, json("""
{"clientToken": "sql", "executionRoleArn": "%s", "releaseLabel": "%s",
"jobDriver": {"sparkSqlJobDriver": {"sparkSqlParameters": "--conf a=b"}}}
""".formatted(ROLE, RELEASE))).get("id").textValue();
JsonNode run = jobRun(service, clusterId, id);
assertEquals("FAILED", state(run));
assertEquals("VALIDATION_ERROR", run.get("failureReason").textValue());
assertEquals("JobRun submission failed.", run.get("stateDetails").textValue(),
"kept FAILED, as AWS's common errors page gives a run whose parameters are not valid, not refused");
assertEquals(0, executor.queued(), "no container starts");
}
@Test
void dockerRunWhoseContainerStartsCountsAsConcurrentNotQueued() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
// The model's least queue depth.
String clusterId = limitedVirtualCluster(service,
"{\"maxConcurrentJobRuns\": 1, \"maxInQueueJobRuns\": 100}");
String first = startJobRun(service, clusterId).get("id").textValue();
assertEquals(1, schedulerStatus(service, clusterId).get("currentConcurrentJobRuns").intValue());
assertEquals(0, schedulerStatus(service, clusterId).get("currentInQueueJobRuns").intValue());
String last = null;
for (int i = 0; i < 100; i++) {
last = startJobRun(service, clusterId).get("id").textValue();
}
assertEquals("PENDING", state(jobRun(service, clusterId, last)), "the queue's hundredth place is free");
assertEquals(100, schedulerStatus(service, clusterId).get("currentInQueueJobRuns").intValue());
AwsException full = assertThrows(AwsException.class, () -> startJobRun(service, clusterId));
assertEquals("ValidationException", full.getErrorCode());
service.cancelJobRun(clusterId, first);
assertEquals("CANCEL_PENDING", state(jobRun(service, clusterId, first)));
assertEquals(1, schedulerStatus(service, clusterId).get("currentConcurrentJobRuns").intValue(),
"its container still runs");
}
@Test
void dockerRunThatCannotBeHandedToAThreadFailsAndFreesItsSlot() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}");
String first = startJobRun(service, clusterId).get("id").textValue();
String second = startJobRun(service, clusterId).get("id").textValue();
String third = startJobRun(service, clusterId).get("id").textValue();
executor.rejecting = true;
executor.runNext();
assertEquals("COMPLETED", state(jobRun(service, clusterId, first)));
for (String refused : List.of(second, third)) {
JsonNode run = jobRun(service, clusterId, refused);
assertEquals("FAILED", state(run), "its slot then went to the next");
assertEquals("INTERNAL_ERROR", run.get("failureReason").textValue());
assertEquals("JobRun submission failed due to an internal error. Floci could not start its driver: "
+ "shutting down", run.get("stateDetails").textValue());
}
}
@Test
void immediateModeNeverStartsAContainer() {
EmrContainersService service = service(0);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = startJobRun(service, clusterId).get("id").textValue();
assertEquals("COMPLETED", state(jobRun(service, clusterId, id)));
}
/** Runs what the service hands its run threads only when the test says so, on the test's thread. */
private static final class QueuedExecutor implements Executor {
private final Deque<Runnable> tasks = new ArrayDeque<>();
// Refuses every task from then on, as an executor that is shut down does.
boolean rejecting;
@Override
public void execute(Runnable task) {
if (rejecting) {
throw new RejectedExecutionException("shutting down");
}
tasks.add(task);
}
int queued() {
return tasks.size();
}
void runNext() {
tasks.removeFirst().run();
}
void runAll() {
while (!tasks.isEmpty()) {
runNext();
}
}
}
/** A runner that starts the driver at once, runs {@code whileRunning}, and ends as {@code outcome} says. */
private static final class FakeRunner implements SparkJobRunner {
final List<Job> jobs = new ArrayList<>();
final List<String> driversStarted = new ArrayList<>();
final Set<String> stopped = new HashSet<>();
final List<String> leftoversRemoved = new ArrayList<>();
Outcome outcome = Outcome.exitedWith(0);
Runnable whileRunning = () -> { };
@Override
public Outcome run(Job job, Progress progress) {
jobs.add(job);
if (progress.cancelled()) {
return Outcome.halted();
}
driversStarted.add(job.runId());
progress.started();
whileRunning.run();
return stopped.contains(job.runId()) ? Outcome.halted() : outcome;
}
@Override
public void stop(String runId) {
stopped.add(runId);
}
@Override
public void removeLeftoverDrivers(String service) {
}
@Override
public void removeLeftoverDriver(String service, String runId) {
leftoversRemoved.add(runId);
}
}
}
@@ -0,0 +1,126 @@
package io.floci.aws.services.emrcontainers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EmrContainersSparkJobsTest {
private static final String ARN =
"arn:aws:emr-containers:eu-west-1:123456789012:/virtualclusters/vc1/jobruns/run1";
private static final String ROLE = "arn:aws:iam::123456789012:role/emr-job";
private final ObjectMapper mapper = new ObjectMapper();
private ObjectNode run(String jobDriver, String configurationOverrides) throws Exception {
ObjectNode run = (ObjectNode) mapper.readTree("""
{"id": "run1", "arn": "%s", "releaseLabel": "emr-7.2.0-20240610", "executionRoleArn": "%s",
"jobDriver": %s}
""".formatted(ARN, ROLE, jobDriver));
if (configurationOverrides != null) {
run.set("configurationOverrides", mapper.readTree(configurationOverrides));
}
return run;
}
@Test
void releaseLabelNamesItsImagesRepositoryAndTag() {
assertEquals("emr-7.2.0:20240610", EmrContainersSparkJobs.containerImageTag("emr-7.2.0-20240610"));
assertEquals("emr-7.2.0:latest", EmrContainersSparkJobs.containerImageTag("emr-7.2.0-latest"));
assertEquals("emr-7.2.0-java11:latest", EmrContainersSparkJobs.containerImageTag("emr-7.2.0-java11-latest"));
assertEquals("emr-7.2.0-spark-rapids:20240610",
EmrContainersSparkJobs.containerImageTag("emr-7.2.0-spark-rapids-20240610"));
assertEquals("emr-spark-8.0.0:20260421", EmrContainersSparkJobs.containerImageTag("emr-spark-8.0.0-20260421"));
assertEquals("emr-7.2.0:latest", EmrContainersSparkJobs.containerImageTag("emr-7.2.0"));
}
@Test
void imageIsTheReleasesBaseImageOnEcrPublicUnlessATemplateNamesAnother() {
assertEquals("public.ecr.aws/emr-on-eks/spark/emr-7.13.0:latest",
EmrContainersSparkJobs.image(null, "emr-7.13.0-latest"));
assertEquals("registry.internal/emr-on-eks/spark/emr-7.2.0:20240610",
EmrContainersSparkJobs.image("registry.internal/emr-on-eks/spark/%s", "emr-7.2.0-20240610"));
}
@Test
void sparkSubmitRunsItsParametersEntryPointAndArgumentsInClientMode() throws Exception {
ObjectNode run = run("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py", "entryPointArguments": ["10", "a b"],
"sparkSubmitParameters": "--conf spark.executor.instances=2 --archives s3://bucket/env.tar.gz#env"}}
""", """
{"applicationConfiguration": [
{"classification": "spark-defaults", "properties": {"spark.driver.memory": "2G"}},
{"classification": "spark-log4j", "properties": {"rootLogger.level": "WARN"}},
{"classification": "spark-defaults", "properties": {"spark.sql.shuffle.partitions": "4"}}]}
""");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, "floci-net");
assertEquals("emr-containers", job.service());
assertEquals("run1", job.runId());
assertEquals("123456789012", job.accountId());
assertEquals("eu-west-1", job.region());
assertEquals("emr-7.2.0-20240610", job.releaseLabel());
assertEquals(SparkJobRunner.Engine.SPARK, job.engine());
assertEquals("public.ecr.aws/emr-on-eks/spark/emr-7.2.0:20240610", job.imageTemplate());
assertNull(job.customImage());
assertEquals("floci-net", job.dockerNetwork());
assertEquals(ROLE, job.executionRole());
assertEquals(Map.of("spark.driver.memory", "2G", "spark.sql.shuffle.partitions", "4",
"spark.submit.deployMode", "client"), job.sparkDefaults());
assertEquals(List.of("--conf", "spark.executor.instances=2", "--archives", "s3://bucket/env.tar.gz#env",
"s3://bucket/pi.py", "10", "a b"), job.application());
assertNull(job.command());
assertEquals(Duration.ZERO, job.timeout(), "a run of EMR on EKS has no timeout");
assertEquals(List.of("s3://bucket/env.tar.gz#env"), job.archives());
assertTrue(job.environment().isEmpty());
assertNull(job.executors());
}
@Test
void sparkSqlRunsItsFileWithItsParameters() throws Exception {
ObjectNode run = run("""
{"sparkSqlJobDriver": {"entryPoint": "s3://bucket/query.sql",
"sparkSqlParameters": "--conf spark.executor.instances=2 -hivevar table=reviews"}}
""", null);
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null);
assertEquals(List.of("spark-sql", "--conf", "spark.executor.instances=2", "-hivevar", "table=reviews", "-f",
"s3://bucket/query.sql"), job.command());
assertTrue(job.application().isEmpty());
assertEquals(Map.of("spark.submit.deployMode", "client"), job.sparkDefaults());
}
@Test
void driversImageAndEnvironmentComeFromItsKubernetesProperties() throws Exception {
String parameters = "--conf spark.kubernetes.driver.container.image=custom/driver:1"
+ " --conf spark.kubernetes.driverEnv.PYSPARK_PYTHON=./env/bin/python";
ObjectNode run = run("""
{"sparkSubmitJobDriver": {"entryPoint": "local:///app/job.py", "sparkSubmitParameters": "%s"}}
""".formatted(parameters), """
{"applicationConfiguration": [{"classification": "spark-defaults",
"properties": {"spark.kubernetes.container.image": "custom/all:1"}}]}
""");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null);
assertEquals("custom/driver:1", job.customImage(), "the driver's own image wins over the job's");
assertEquals(Map.of("PYSPARK_PYTHON", "./env/bin/python"), job.environment());
ObjectNode onlyJobImage = run("""
{"sparkSubmitJobDriver": {"entryPoint": "local:///app/job.py",
"sparkSubmitParameters": "--conf spark.kubernetes.container.image=custom/all:2"}}
""", null);
assertEquals("custom/all:2", EmrContainersSparkJobs.job(onlyJobImage, null, null).customImage());
}
}
@@ -0,0 +1,217 @@
package io.floci.aws.services.emrcontainers;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.PullImageResultCallback;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CloudFormationSettingsProfile;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EksRequests;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import java.time.Duration;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* EMR on EKS job runs, run for real in the {@code docker} runner mode: each runs its Spark job in a container of its
* release's base image from Amazon ECR Public, on Floci's S3, and ends as its driver does.
*
* <p>A nightly check: the release's base image is about 5 GB.
*/
@QuarkusTest
@TestProfile(CloudFormationSettingsProfile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// One instance, so that the image is pulled once for the class.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
// Bounded waits: a job run of up to five minutes in each method, past the default two, and the cancelled run's five
// minutes to start besides. With the image's pull of up to 21 and each method's setup of up to the default two, 58
// minutes, which the Nightly checks' docker-runner group counts.
@Timeout(value = 6, unit = TimeUnit.MINUTES)
class EmrContainersSparkNightlyIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-job";
private static final String RELEASE = "emr-7.5.0-latest";
// The release's base image, which the runner's default template names.
private static final String BASE_IMAGE = "public.ecr.aws/emr-on-eks/spark/emr-7.5.0:latest";
private static final Set<String> FINISHED = Set.of("COMPLETED", "FAILED", "CANCELLED");
private static final Duration JOB_RUN_TIMEOUT = Duration.ofMinutes(5);
private static final Duration POLL_INTERVAL = Duration.ofMillis(500);
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
DockerClient docker;
private S3Client s3;
private String bucket;
private String virtualClusterId;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
// The base image's pull alone may take its twenty minutes.
@BeforeAll
@Timeout(value = 21, unit = TimeUnit.MINUTES)
void pullImage() throws InterruptedException {
// Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing.
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
docker.pullImageCmd(BASE_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(20, TimeUnit.MINUTES);
}
@BeforeEach
void setUp() {
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
bucket = "emr-eks-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
put("write.py", """
import sys
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
spark.createDataFrame([(sys.argv[2],)], ["value"]).coalesce(1).write.text(sys.argv[1])
""");
put("fail.py", """
import sys
sys.exit(3)
""");
put("sleep.py", """
import time
time.sleep(600)
""");
put("query.sql", """
INSERT OVERWRITE DIRECTORY 's3://%s/sql-out/' USING text SELECT 'from-sql' AS value;
""".formatted(bucket));
String eksCluster = "emr-" + UUID.randomUUID().toString().substring(0, 8);
EksRequests.eks(ACCOUNT, REGION)
.body("""
{"name": "%s", "roleArn": "arn:aws:iam::000000000000:role/eks-role", "version": "1.29"}
""".formatted(eksCluster))
.post("/clusters")
.then().statusCode(200);
cleanup.register(() -> EksRequests.eks(ACCOUNT, REGION).delete("/clusters/" + eksCluster)
.then().statusCode(200));
virtualClusterId = emr().body("""
{"name": "nightly", "clientToken": "%s",
"containerProvider": {"type": "EKS", "id": "%s", "info": {"eksInfo": {"namespace": "spark"}}}}
""".formatted(UUID.randomUUID(), eksCluster))
.post("/virtualclusters")
.then().statusCode(200)
.extract().path("id");
String created = virtualClusterId;
cleanup.register(() -> emr().delete("/virtualclusters/" + created).then().statusCode(200));
}
@Test
void sparkSubmitJobRunWritesToS3AndCompletes() {
String id = startJobRun("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://%s/write.py",
"entryPointArguments": ["s3://%s/out/", "from-submit"],
"sparkSubmitParameters": "--conf spark.sql.shuffle.partitions=1"}}
""".formatted(bucket, bucket));
Response run = awaitFinished(id);
assertEquals("COMPLETED", run.jsonPath().getString("jobRun.state"), run.asString());
assertEquals("from-submit\n", S3TestClients.partFiles(s3, bucket, "out/"));
}
@Test
void sparkSqlJobRunRunsItsFileAndCompletes() {
String id = startJobRun("""
{"sparkSqlJobDriver": {"entryPoint": "s3://%s/query.sql",
"sparkSqlParameters": "--conf spark.sql.shuffle.partitions=1"}}
""".formatted(bucket));
Response run = awaitFinished(id);
assertEquals("COMPLETED", run.jsonPath().getString("jobRun.state"), run.asString());
assertEquals("from-sql\n", S3TestClients.partFiles(s3, bucket, "sql-out/"));
}
@Test
void jobRunWhoseDriverExitsWithAnErrorFails() {
String id = startJobRun("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://%s/fail.py"}}
""".formatted(bucket));
Response run = awaitFinished(id);
assertEquals("FAILED", run.jsonPath().getString("jobRun.state"), run.asString());
assertEquals("USER_ERROR", run.jsonPath().getString("jobRun.failureReason"));
}
@Test
@Timeout(value = 11, unit = TimeUnit.MINUTES)
void cancelledJobRunStopsItsDriverAndIsCancelled() {
String id = startJobRun("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://%s/sleep.py"}}
""".formatted(bucket));
await("job run " + id + " to run").atMost(JOB_RUN_TIMEOUT).pollInterval(POLL_INTERVAL)
.until(() -> describe(id).jsonPath().getString("jobRun.state"), "RUNNING"::equals);
emr().delete("/virtualclusters/" + virtualClusterId + "/jobruns/" + id).then().statusCode(200);
Response run = awaitFinished(id);
assertEquals("CANCELLED", run.jsonPath().getString("jobRun.state"), run.asString());
}
private void put(String key, String body) {
s3.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(body));
}
private static RequestSpecification emr() {
return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, REGION, "emr-containers"))
.contentType("application/json")
.urlEncodingEnabled(false);
}
private String startJobRun(String jobDriver) {
return emr().body("""
{"name": "nightly", "clientToken": "%s", "executionRoleArn": "%s", "releaseLabel": "%s",
"jobDriver": %s}
""".formatted(UUID.randomUUID(), ROLE, RELEASE, jobDriver))
.post("/virtualclusters/" + virtualClusterId + "/jobruns")
.then().statusCode(200)
.extract().path("id");
}
private Response describe(String id) {
return emr().get("/virtualclusters/" + virtualClusterId + "/jobruns/" + id)
.then().statusCode(200).extract().response();
}
private Response awaitFinished(String id) {
return await("job run " + id + " to end").atMost(JOB_RUN_TIMEOUT).pollInterval(POLL_INTERVAL)
.until(() -> describe(id), run -> FINISHED.contains(run.jsonPath().getString("jobRun.state")));
}
}
@@ -31,12 +31,15 @@ import java.util.Map;
* <li>{@code floci.services.eks.imds=true} and {@code floci.services.eks.imds-pod-network=true}
* program the link-local IMDS endpoint into a cluster's container, for the node and for its pods.
* {@code EksImdsDockerIntegrationTest} relies on them.</li>
* <li>{@code floci.services.emr.runner-mode=docker} and
* {@code floci.services.emrserverless.runner-mode=docker} run a cluster's steps and an EMR
* Serverless application's job runs in containers of the release's image, and
* <li>{@code floci.services.emr.runner-mode=docker},
* {@code floci.services.emrserverless.runner-mode=docker} and
* {@code floci.services.emrcontainers.runner-mode=docker} run a cluster's steps, an EMR
* Serverless application's job runs and an EMR on EKS virtual cluster's job runs in containers of the
* release's image, and
* {@code floci.services.emrserverless.executor-containers=2} a Spark job run's executors each in a
* container of its own. {@code EmrDockerRunnerNightlyIntegrationTest},
* {@code EmrServerlessHiveDockerIntegrationTest} and the EMR nightly checks rely on them.</li>
* {@code EmrServerlessHiveDockerIntegrationTest}, {@code EmrContainersSparkNightlyIntegrationTest} and the
* EMR nightly checks rely on them.</li>
* <li>{@code floci.services.cloudfront.enabled=false} turns CloudFront off.
* {@code CloudFrontDisabledServingTest} relies on it.</li>
* <li>{@code floci.storage.services.dynamodb.mode=persistent}, with its items in the
@@ -61,8 +64,8 @@ import java.util.Map;
* </ul>
*
* <p>Each override is inert for the other classes: each is read by a single service, CloudFormation,
* the Timestream for InfluxDB data plane, an EKS cluster's container start, the EMR and EMR
* Serverless runners, CloudFront, DynamoDB, SageMaker training, ECS, Kinesis and RDS, and no other
* the Timestream for InfluxDB data plane, an EKS cluster's container start, the EMR, EMR
* Serverless and EMR on EKS runners, CloudFront, DynamoDB, SageMaker training, ECS, Kinesis and RDS, and no other
* class here calls that service. Boot-time reconciliation only acts on containers a previous run
* left, which this application never adopts. The persistent path is the one setting every class sees: it moves where this
* application writes what services keep on disk whatever their storage mode, Timestream backups and
@@ -98,6 +101,7 @@ public class CloudFormationSettingsProfile implements QuarkusTestProfile {
Map.entry("floci.services.emr.runner-mode", "docker"),
Map.entry("floci.services.emrserverless.runner-mode", "docker"),
Map.entry("floci.services.emrserverless.executor-containers", "2"),
Map.entry("floci.services.emrcontainers.runner-mode", "docker"),
Map.entry("floci.services.cloudfront.enabled", "false"),
Map.entry("floci.storage.services.dynamodb.mode", "persistent"),
Map.entry("floci.storage.services.dynamodb.item-layout", "per-table"),
+1
View File
@@ -551,6 +551,7 @@ floci:
emrcontainers:
enabled: true
job-run-duration-seconds: 0 # 0 = a job run completes as soon as it is submitted
runner-mode: immediate
ssoadmin:
enabled: true
ssooidc: