diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 9655c29bd2..0e669f170d 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -13,7 +13,8 @@ EMR Serverless is an AWS service that provides serverless data analytics environ | `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` | +| `floci.services.emrserverless.executor-containers` | How many executors a `docker` Spark job run may have at once, each in a container of its own (see **Executors** under [Running Spark job runs](#running-spark-job-runs)); `0`, the default, runs a run's executors in its driver's container, in Spark's local mode | `0` | +| `floci.services.emrserverless.reconcile-containers-on-startup` | Remove the drivers and executors 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 @@ -119,7 +120,31 @@ run executes. Floci starts one container per run from the application's custom i (see **Image** below), or else from the release's image, the base image AWS publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/spark/`, and `spark4/` for the AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs -`spark-submit` in local mode in it: the container holds the driver and its executors. +`spark-submit` in it, in Spark's local mode by default: the container holds the driver and its executors. +With `executor-containers` above `0`, each executor runs in a container of its own instead, as each has a +worker of its own on EMR Serverless (see **Executors** below). + +* **Executors**: with `executor-containers` above `0`, Floci starts an executor's container as the driver asks + for one, of the same image as the driver's or the application's for its executors (see **Image**), on the + same network, with the same credentials and trust store. Its worker offers the run's `spark.executor.cores` and `spark.executor.memory`, + which Floci reads from the running driver, so they come from the image's `spark-defaults`, the run's + configuration or its `sparkSubmitParameters` alike: 4 cores and 14 GB unless the run says otherwise. How many + run follows Spark's dynamic allocation, on by default, which starts with `spark.dynamicAllocation.initialExecutors` + (3) and releases an idle executor after `spark.dynamicAllocation.executorIdleTimeout`, when its shuffle data + allows: Floci removes the container of an executor Spark released. With dynamic allocation off, + `spark.executor.instances` start. A run has at most `executor-containers` executors at once, + and none that would take the workers of its application's runs, their drivers' among them, past the application's + `maximumCapacity`, which "is cumulative across all workers at any given point in time" and of which "no new + resources will be created once any one of the defined limits is hit": a worker counts its cores, its memory with + Spark's overhead rounded up to a whole GB, and its disk, `spark.emr-serverless.executor.disk` or + `spark.emr-serverless.driver.disk`, 20 GB by default. The overhead is the run's `spark.executor.memoryOverhead` + (or the driver's), else that share of the memory its `spark.executor.memoryOverheadFactor` gives, else + `spark.emr-serverless.memoryOverheadFactor`'s, else 10%, and at least 384 MB. The master's address, the run's + secret and the UI's kill links (see below) come after the run's own options, so none of them replaces these. + Every executor's container goes with its driver, however the run ends, as does one that ended before it, and a + hard stop's leftovers go as its driver's do. With `executor-containers` at `0`, + the default, or on the host's network or another container's network namespace, where two runs' ports would meet, the + executors run in the driver's container instead, in Spark's local mode. * **States**: a run is `SCHEDULED` while its image is pulled and its container starts (the first run of a release pulls its image, 3.5 to 4.3 GB unpacked; a pull still downloading after @@ -161,8 +186,9 @@ AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs Floci reads each archive as the run's account. One it cannot read fails the run before its driver starts, with "Job run could not start" naming it, and one that does not unpack fails the run as a driver's failure does. Spark also unpacks every archive itself, into its own files folder, where - `SparkFiles.get` finds it. A `spark.executorEnv.` needs nothing more from Floci: local mode's - executors run in the driver's JVM, and Spark gives these variables to the Python workers it starts. + `SparkFiles.get` finds it, and, with executors in containers of their own, into each executor's working + directory. A `spark.executorEnv.` needs nothing more from Floci: Spark gives these variables to its + executors, in the driver's JVM in local mode, and the Python workers they start. * **Credentials**: the container gets a session for the run's execution role when IAM knows the role, otherwise the account's placeholder credentials, and `AWS_ENDPOINT_URL` pointing at Floci, so the job's own SDK clients reach Floci too. @@ -190,9 +216,8 @@ AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs any; both are created as needed, in the run's account and Region. A `logTypes` sends only the driver's types it names, and none of the driver's output when it names only `SPARK_EXECUTOR`. * **Image**: an application's custom image runs in place of the release's: the `Driver` worker type's - `imageConfiguration` in `workerTypeSpecifications`, or else the application's `imageConfiguration`, - which applies to every worker type (local mode runs the executors in the driver's container, so an - `Executor` image is not used). An `.dkr.ecr..amazonaws.com/:` URI + `imageConfiguration` in `workerTypeSpecifications` for the driver and the `Executor` worker type's for the + executors in containers of their own (local mode runs them in the driver's container), or else the application's `imageConfiguration`, which applies to every worker type. An `.dkr.ecr..amazonaws.com/:` URI leads to Floci's [ECR](ecr.md), as a Lambda function's or an ECS task's image does, so the image is pushed to a repository there; the `repositoryUri` Floci's ECR hands out works too. The image is pulled again for every run, so a tag pushed again is what the next run gets; when the pull fails the image the @@ -238,7 +263,8 @@ application's `imageConfiguration`; a `TezTask` image is not used, as Tez's task ## 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, 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). +* **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 Spark's local mode in one container unless `executor-containers` is above `0` (see **Executors** below), and a Hive run with Tez in local mode in one container: in local mode, 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 (no executor logs, which local mode does not have and executors' containers take with them, no `HIVE_LOG`, `TEZ_AM` or `TEZ_TASK` logs of a Hive run, whose own log stays in its container, and `encryptionKeyArn` is ignored). +* **Executors**: with `executor-containers` above `0`, a Spark run's executors run in containers of their own, but at most `executor-containers` of them, rather than as many as dynamic allocation asks for, and a container's memory and cores are not limited to its worker's size, which only Spark's settings follow. `initialCapacity` is not applied: no worker is waiting, so each starts as the run asks for it. Spark's master is Spark's own standalone master, in the driver's container, where EMR Serverless has its own (`spark.master` reads `spark://...`), and the driver's UI, which the release's image turns off, is on, with its kill links off, as Floci follows the driver through it: a run that turns it off again (`spark.ui.enabled=false`) gets a single executor container 30 seconds after its driver starts, whose worker offers 32 cores and 256 GB, as Floci cannot read the run's own sizes, and which, like its driver's, counts for nothing against the application's `maximumCapacity`. * **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. diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index b5ed8ceed2..d5593a38e2 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1180,6 +1180,16 @@ public interface EmulatorConfig { */ Optional hiveImageTemplate(); + /** + * How many executors a {@code docker} Spark job run may have at once, each in a container of its own, as each + * has a worker of its own on EMR Serverless; 0, the default, runs a job's executors in its driver's container, in + * Spark's local mode. The application's maximum capacity limits them too. + * + * Env var: FLOCI_SERVICES_EMRSERVERLESS_EXECUTOR_CONTAINERS + */ + @WithDefault("0") + int executorContainers(); + /** * When true, Floci removes, in the {@code docker} runner mode, every EMR Serverless driver a * previous run of this same Floci left on the daemon (matched by the diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index ce2262a75d..5e5afedb52 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -1539,7 +1539,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear executionRole(cluster, step, accountId), Map.of(), hive.arguments(), hive.runner(), Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null, EmrSparkSteps.hiveEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(), - storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of()); + storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } else if (application == null && command == null) { job = null; } else { @@ -1554,7 +1554,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER)); + EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), null); } StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation, teardowns.get()); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java index 2c74b16a48..058035ec6a 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -23,6 +23,7 @@ import io.floci.aws.services.emrserverless.model.JobRun; import io.floci.aws.services.emrserverless.model.JobRunAttemptSummary; import io.floci.aws.services.emrserverless.model.JobRunRecord; import io.floci.aws.services.emrserverless.model.JobRunSummary; +import io.floci.aws.services.emrserverless.model.MaximumCapacity; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification; @@ -100,6 +101,7 @@ public class EmrServerlessJobRunService implements Resettable { // 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"; + private static final String EXECUTOR_WORKER_TYPE = "Executor"; // 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"; @@ -161,6 +163,8 @@ public class EmrServerlessJobRunService implements Resettable { private final String imageTemplate; private final String hiveImageTemplate; private final String dockerNetwork; + // How many executor containers a Spark run may have at once: executor-containers, 0 for Spark's local mode. + private final int executorContainers; // Container runs a thread is running; one not here that has not ended was left by a restart. private final Set executing = new HashSet<>(); // Raised by each reset, so a run's thread from before it writes nothing back after the wipe. @@ -178,7 +182,8 @@ public class EmrServerlessJobRunService implements Resettable { 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)); + config.services().emrserverless().dockerNetwork().orElse(null), + config.services().emrserverless().executorContainers()); // 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()) { sparkRunner.removeLeftoverDrivers(SERVICE); @@ -205,6 +210,16 @@ public class EmrServerlessJobRunService implements Resettable { ObjectMapper objectMapper, int runDurationSeconds, Clock clock, SparkJobRunner sparkRunner, Executor runExecutor, String imageTemplate, String hiveImageTemplate, String dockerNetwork) { + this(store, applications, iamService, regionResolver, requestContext, objectMapper, runDurationSeconds, clock, + sparkRunner, runExecutor, imageTemplate, hiveImageTemplate, dockerNetwork, 0); + } + + EmrServerlessJobRunService(AccountAwareStorageBackend 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, + int executorContainers) { if (runDurationSeconds < 0) { throw new IllegalArgumentException( "floci.services.emrserverless.job-run-duration-seconds must not be negative: " + runDurationSeconds); @@ -222,6 +237,7 @@ public class EmrServerlessJobRunService implements Resettable { this.imageTemplate = imageTemplate; this.hiveImageTemplate = hiveImageTemplate; this.dockerNetwork = dockerNetwork; + this.executorContainers = executorContainers; } @PreDestroy @@ -529,7 +545,7 @@ public class EmrServerlessJobRunService implements Resettable { 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()); + Map.of(), Map.of(), Map.of(), Map.of(), null); } else { JobDriver.SparkSubmit sparkSubmit = run.getJobDriver().getSparkSubmit(); Map sparkDefaults = sparkDefaults(app, run); @@ -538,7 +554,8 @@ public class EmrServerlessJobRunService implements Resettable { 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()); + archives(sparkProperties), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), + executors(app, executorContainers)); } executing.add(run.getJobRunId()); long launchedIn = generation; @@ -560,20 +577,56 @@ public class EmrServerlessJobRunService implements Resettable { /** * 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. + * "EMR Serverless applies ... to all worker types". Tez runs a Hive run's tasks in the driver's container, so a + * {@code TezTask} image is not used; a Spark run's executors have their own, {@link #executors}. */ static String customImage(Application app) { - String workerType = HIVE_TYPE.equalsIgnoreCase(app.getType()) ? HIVE_DRIVER_WORKER_TYPE : DRIVER_WORKER_TYPE; - WorkerTypeSpecification driver = app.getWorkerTypeSpecifications() != null + return workerImage(app, HIVE_TYPE.equalsIgnoreCase(app.getType()) ? HIVE_DRIVER_WORKER_TYPE : DRIVER_WORKER_TYPE); + } + + // A worker type's custom image, else the application's, else null for the release's. + private static String workerImage(Application app, String workerType) { + WorkerTypeSpecification worker = app.getWorkerTypeSpecifications() != null ? app.getWorkerTypeSpecifications().get(workerType) : null; - if (driver != null && driver.getImageConfiguration() != null - && driver.getImageConfiguration().getImageUri() != null) { - return driver.getImageConfiguration().getImageUri(); + if (worker != null && worker.getImageConfiguration() != null + && worker.getImageConfiguration().getImageUri() != null) { + return worker.getImageConfiguration().getImageUri(); } return app.getImageConfiguration() != null ? app.getImageConfiguration().getImageUri() : null; } + /** + * Where a Spark run's executors run: in containers of their own, at most {@code containers} at once, in the + * {@code Executor} worker type's custom image, else the application's, and within the application's maximum + * capacity, which its runs share; or, with {@code containers} 0, in the driver's container, which Spark's local + * mode runs them in. + */ + static SparkJobRunner.Executors executors(Application app, int containers) { + if (containers <= 0) { + return null; + } + MaximumCapacity capacity = app.getMaximumCapacity(); + return new SparkJobRunner.Executors(containers, workerImage(app, EXECUTOR_WORKER_TYPE), + capacity != null ? capacityAmount(capacity.getCpu()) : 0, + capacity != null ? capacityAmount(capacity.getMemory()) : 0, + capacity != null ? capacityAmount(capacity.getDisk()) : 0, app.getArn()); + } + + // A maximum capacity's amount, as "400 vCPU" or "1024GB" give it, or 0 for none. + static long capacityAmount(String value) { + if (value == null) { + return 0; + } + int digits = 0; + while (digits < value.length() && Character.isDigit(value.charAt(digits))) { + digits++; + } + if (digits == 0) { + return 0; + } + return digits > 18 ? Long.MAX_VALUE : Long.parseLong(value.substring(0, digits)); + } + /** * What follows Floci's own settings on a run's {@code spark-submit} command line: its * {@code sparkSubmitParameters}, split as a shell would split them, then its entry point and the diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index 85b984f47d..30ecb37a25 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -13,8 +13,10 @@ import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.S3Uri; import io.floci.aws.core.common.XmlBuilder; import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLaunches; import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerLiveness; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; @@ -36,17 +38,20 @@ import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.security.SecureRandom; 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.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import java.util.regex.Pattern; @@ -57,7 +62,9 @@ import java.util.zip.GZIPOutputStream; * Runs a Spark application's {@code spark-submit} in a container of an EMR Serverless image, for an EMR * Serverless job run or an EMR step. The image's own entrypoint hands over to a script EMR Serverless * supplies at run time, which the public image lacks, so the runner starts {@code spark-submit} itself, - * in local mode: the container holds the driver and its executors. The container reaches Floci as the + * in local mode, the container holding the driver and its executors, unless the job's executors run in containers of + * their own, as an EMR Serverless run's do ({@link SparkExecutors}), or on its cluster's YARN, as a step's do. The + * container reaches Floci as the * other containers Floci launches do, with the run's execution role as its credentials, and S3A, which * takes {@code s3://} on every release, is pointed at Floci's S3. With TLS on, every JVM in the container * trusts Floci's CA, through the Java trust store copied in before it starts, and the run's archives in S3 @@ -76,6 +83,8 @@ import java.util.zip.GZIPOutputStream; public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown { private static final Logger LOG = Logger.getLogger(EmrServerlessSparkRunner.class); + // Where a run's secret, which its master, workers and driver share, comes from. + private static final SecureRandom SECRETS = new SecureRandom(); 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. @@ -353,6 +362,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo // The runs inside run(); a stop for a run not here comes after its driver has gone, and is dropped. private final ContainerLaunches launches = new ContainerLaunches(); + // What the workers of each application's runs with executors of their own hold, by application, while any runs. + private final Map capacities = new ConcurrentHashMap<>(); private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -392,10 +403,14 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo } @Override - public Outcome run(Job job, Progress progress) { + public Outcome run(Job given, Progress progress) { + String network = containerBuilder.resolveDockerNetwork(Optional.ofNullable(given.dockerNetwork())).orElse(null); + Job job = executorsApart(given, network) ? given : given.withExecutors(null); ContainerLaunches.Launch launch = launches.begin(job.runId()); Optional credentials = Optional.empty(); Closeable logHandle = null; + SparkExecutors executors = null; + SparkExecutors.Capacity capacity = null; try { // A cancel before the run was in launches had nothing to stop, so it is read here. if (progress.cancelled()) { @@ -414,11 +429,14 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo ? awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), endpoint, credentials, job.accountId()) : List.of(); List archives = archives(job); + List awsEnvironment = awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, + job.accountId()); + // Pulled, when it is not the driver's, before the driver starts rather than while it waits for executors. + String executorImage = job.executors() != null ? executorImage(job) : null; + String secret = job.executors() != null ? newSecret() : null; ContainerBuilder.Builder container = containerBuilder.newContainer(launchImage(job)) .withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId())) - .withEnv(environment( - awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()), - job.environment())); + .withEnv(environment(awsEnvironment, job.environment())); // bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@". if (job.engine() == Engine.HIVE) { List hive = hiveArguments(job, endpoint, executorEnvironment); @@ -433,10 +451,21 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo container.withEnv(HIVE_SCRATCH_VARIABLE, scratch); } } else if (job.command() == null) { - List sparkSubmit = job.sparkLog4j2().isEmpty() && job.storage() == null - ? List.of(SPARK_SUBMIT) : List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci", SPARK_SUBMIT); + List sparkSubmit = new ArrayList<>(); + if (!job.sparkLog4j2().isEmpty() || job.storage() != null) { + sparkSubmit.addAll(List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci")); + } + List arguments = sparkSubmitArguments(job, endpoint, executorEnvironment); + if (job.executors() != null) { + sparkSubmit.addAll(List.of("/bin/bash", "-c", SparkExecutors.DRIVER_WRAPPER, "floci")); + container.withEnv(SparkExecutors.SECRET_VARIABLE, secret); + } + sparkSubmit.add(SPARK_SUBMIT); + if (job.executors() != null) { + sparkSubmit.add(String.valueOf(SparkExecutors.optionCount(arguments))); + } container.withEntrypoint(unpackingFirst(archives, sparkSubmit)) - .withCmd(sparkSubmitArguments(job, endpoint, executorEnvironment)); + .withCmd(arguments); } else { container.withEntrypoint(unpackingFirst(archives, List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci"))) .withCmd(job.command()) @@ -501,7 +530,15 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo lifecycleManager.startCreated(containerId, spec); logHandle = attachLog(containerId, job); progress.started(); - Outcome outcome = awaitEnd(containerId, job, launch, progress); + if (job.executors() != null) { + capacity = joinCapacity(job.executors().application()); + executors = new SparkExecutors(job.executors(), driver(containerId), + executorContainers(job, executorImage, network, + lifecycleManager.resolveContainerNetworkIp(containerId, network), secret, + awsEnvironment, labels), + capacity, System::nanoTime); + } + Outcome outcome = awaitEnd(containerId, job, launch, progress, executors); writeLogs(job, launch); return outcome; } catch (InterruptedException e) { @@ -516,6 +553,12 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo LOG.warnv(e, "Spark run {0} of {1} could not run", job.runId(), job.service()); return Outcome.couldNotStart(e.getMessage()); } finally { + // The executors go with their driver, however the run ended, and their workers' share of the + // application's capacity with them. + if (executors != null) { + executors.removeAll(); + leaveCapacity(job.executors().application(), capacity); + } String unclaimed = launches.end(job.runId(), launch); if (unclaimed != null) { lifecycleManager.stopAndRemove(unclaimed, logHandle, STOP_TIMEOUT_SECONDS); @@ -574,8 +617,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (aliases.consistent(container.getId(), labels) && aliases.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner)) { lifecycleManager.removeIfExists(container.getId()); - LOG.infov("Removed {0} Spark driver {1}, left running by an earlier Floci process", service, - container.getId()); + LOG.infov("Removed {0} Spark {1} {2}, left running by an earlier Floci process", service, + SparkExecutors.COMPONENT.equals(component) ? "executor" : "driver", container.getId()); } } } catch (RuntimeException e) { @@ -711,6 +754,124 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo return unpacking; } + /** + * Whether a job's executors run in containers of their own: an EMR Serverless Spark run's that says so, on a + * network of containers; on the host's, or in another container's namespace, the executors' and the master's + * ports would meet another run's, so they run in the driver's container. + */ + static boolean executorsApart(Job job, String network) { + return job.executors() != null && job.engine() == Engine.SPARK && job.command() == null + && job.storage() == null && !"host".equals(network) + && (network == null || !network.startsWith("container:")); + } + + private static String newSecret() { + byte[] secret = new byte[32]; + SECRETS.nextBytes(secret); + return HexFormat.of().formatHex(secret); + } + + // The capacity an application's runs share, which a run joins when its driver starts; a run of no application + // shares it with none. + SparkExecutors.Capacity joinCapacity(String application) { + if (application == null) { + return new SparkExecutors.Capacity().joined(); + } + return capacities.compute(application, + (key, shared) -> (shared != null ? shared : new SparkExecutors.Capacity()).joined()); + } + + // A run leaves the capacity it shared, which goes once no run shares it. + void leaveCapacity(String application, SparkExecutors.Capacity capacity) { + if (application == null) { + return; + } + capacities.computeIfPresent(application, (key, shared) -> shared == capacity && shared.left() ? null : shared); + } + + // The driver's container, answering through curl in it, which every EMR Serverless image has, or nothing, as + // when the container has just ended. + SparkExecutors.Driver driver(String containerId) { + return (port, path) -> { + try { + ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, + new String[]{"curl", "-sf", "-m", "2", "http://127.0.0.1:" + port + path}, 5); + return result.exitCode() == 0 ? result.stdout() : null; + } catch (RuntimeException e) { + LOG.debugv("Could not ask the driver in container {0}: {1}", containerId, e.getMessage()); + return null; + } + }; + } + + // The image a job's executors run in: the application's for its executors, pulled for every run as the driver's + // custom image is, else the release's, pulled when missing, as a driver with a custom image does not pull it. + private String executorImage(Job job) { + if (job.executors().image() == null) { + return lifecycleManager.resolveImageForLaunch(image(job.imageTemplate(), job.releaseLabel(), Engine.SPARK), + ImagePullBehavior.PREFER_CACHED, null).imageId(); + } + String image = containerBuilder.resolveImage(ecrRegistryManager.rewriteImageUri(job.executors().image())); + return lifecycleManager.resolveImageForLaunch(image, ImagePullBehavior.DEFAULT, null).imageId(); + } + + /** + * A job's executors' containers: each a standalone worker, named after the run and its number, on the driver's + * network, which finds the master at the driver's address, with the run's secret, the AWS environment the driver + * has but for its own variables, Floci's trust store, and the driver's labels, so a reset and the leftover sweep + * find it as they find the driver. + */ + SparkExecutors.Containers executorContainers(Job job, String image, String network, String driverAddress, + String secret, List awsEnvironment, + Map driverLabels) { + Map labels = new LinkedHashMap<>(driverLabels); + labels.put(ContainerStorageHelper.COMPONENT_LABEL, SparkExecutors.COMPONENT); + return new SparkExecutors.Containers() { + @Override + public SparkExecutors.Worker start(int index, SparkExecutors.Size size) { + ContainerSpec spec = containerBuilder.newContainer(image) + .withName(ContainerStorageHelper.dockerName(config, + job.service() + "-" + job.runId() + "-executor-" + index)) + .withEnv(awsEnvironment) + .withEnv(SparkExecutors.SECRET_VARIABLE, secret) + .withEnv(SparkExecutors.MASTER_VARIABLE, driverAddress) + .withEnv(SparkExecutors.CORES_VARIABLE, String.valueOf(size.cores())) + .withEnv(SparkExecutors.MEMORY_VARIABLE, String.valueOf(size.memoryMib())) + .withEntrypoint(List.of("/bin/bash", "-c", SparkExecutors.WORKER_SCRIPT)) + .withDockerNetwork(Optional.ofNullable(job.dockerNetwork())) + .withHostDockerInternalOnLinux() + .withEmbeddedDns() + .withLogRotation() + .withLabels(labels) + .withJavaTrustStore() + .build(); + String containerId = lifecycleManager.createAndStart(spec).containerId(); + try { + return new SparkExecutors.Worker(containerId, + lifecycleManager.resolveContainerNetworkIp(containerId, network)); + } catch (RuntimeException e) { + // Not yet the run's to remove, so removed here. + try { + lifecycleManager.stopAndRemove(containerId, null, STOP_TIMEOUT_SECONDS); + } catch (RuntimeException removal) { + e.addSuppressed(removal); + } + throw e; + } + } + + @Override + public boolean running(String containerId) { + return lifecycleManager.probeContainer(containerId) != ContainerLiveness.NOT_RUNNING; + } + + @Override + public void remove(String containerId) { + lifecycleManager.stopAndRemove(containerId, null, STOP_TIMEOUT_SECONDS); + } + }; + } + /** * The image a run's driver starts from: the release's, or the template's, or the application's custom * image. A custom image's ECR URI leads to Floci's own registry, as a Lambda function's or an ECS task's @@ -794,6 +955,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo /** * {@code spark-submit}'s arguments: local mode, or YARN for a step on its cluster's (see {@link #yarnSettings}), + * or, for a run whose executors run in containers of their own, no master, which the driver's container gives + * after the run's own options with what no run may change ({@link SparkExecutors#DRIVER_WRAPPER}), and the + * driver's UI on, which Floci follows the driver through, * S3A on Floci's S3 for {@code s3://} and {@code s3a://} * paths, the cluster's HDFS for {@code hdfs://} paths and those without a scheme on a step, then the run's * {@code spark-defaults} and its own options, which win over what comes before them, then its @@ -803,7 +967,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo * none and a write is silently lost. */ static List sparkSubmitArguments(Job job, String flociEndpoint, List executorEnvironment) { - List arguments = new ArrayList<>(List.of("--master", master(job))); + List arguments = new ArrayList<>(); + if (job.executors() == null) { + arguments.addAll(List.of("--master", master(job))); + } for (SparkSetting setting : sparkSettings(job, flociEndpoint, executorEnvironment)) { conf(arguments, setting.key(), setting.value()); } @@ -1212,6 +1379,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (onYarn(job)) { settings.addAll(yarnSettings(job, executorEnvironment)); } + // The driver's UI, which Floci follows the driver through; its kill links, which any container on the network + // reaches, are turned off after the run's own settings (SparkExecutors.DRIVER_WRAPPER). + if (job.executors() != null) { + settings.add(new SparkSetting("spark.ui.enabled", "true")); + } job.sparkDefaults().forEach((key, value) -> settings.add(new SparkSetting(key, value))); return settings; } @@ -1334,10 +1506,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo * while a reset's teardown was passing is stopped once the reset has removed its run. Each look at the * container is one short control-plane call, so a run holds no Docker connection while its driver runs. */ - private Outcome awaitEnd(String containerId, Job job, ContainerLaunches.Launch launch, Progress progress) - throws InterruptedException { + private Outcome awaitEnd(String containerId, Job job, ContainerLaunches.Launch launch, Progress progress, + SparkExecutors executors) throws InterruptedException { Instant deadline = job.timeout().isZero() ? null : clock.instant().plus(job.timeout()); while (!launch.stopRequested() && !progress.cancelled()) { + if (executors != null) { + executors.follow(); + } InspectContainerResponse.ContainerState state = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getState(); if (!Boolean.TRUE.equals(state.getRunning())) { diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java b/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java new file mode 100644 index 0000000000..197e42c66f --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java @@ -0,0 +1,481 @@ +package io.floci.aws.services.emrserverless; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.emrserverless.SparkJobRunner.Executors; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.LongSupplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * An EMR Serverless Spark run's executors, each in a container of its own, as each has a worker of its own on EMR + * Serverless, rather than in its driver's container in Spark's local mode. The driver's container runs Spark's + * standalone master beside the driver, which {@link #DRIVER_WRAPPER} starts at the container's own address before it + * hands over to {@code spark-submit}, whose master that is; an executor's container runs a standalone worker offering + * one executor's cores and memory, {@link #WORKER_SCRIPT}, which the master gives the driver's next executor. The three + * share a secret, as the image's {@code spark-defaults} turn on Spark's authentication, which the master and the + * worker read too. Floci follows the driver, through its UI: an executor's size from its settings, once, and how many + * executors Spark's dynamic allocation wants from its metrics, at each look, and starts containers, or removes idle + * ones, to match, up to the run's limit and so that the workers of its application's runs, their drivers' among them, + * stay within that application's maximum capacity ({@link Capacity}), as "no new resources will be created once any one + * of the defined limits is hit". + */ +final class SparkExecutors { + + private static final Logger LOG = Logger.getLogger(SparkExecutors.class); + private static final ObjectMapper JSON = new ObjectMapper(); + + /** The variable the run's secret is in, in the driver's container and each executor's. */ + static final String SECRET_VARIABLE = "FLOCI_SPARK_SECRET"; + /** The driver container's address, where an executor's worker finds the master, in its container. */ + static final String MASTER_VARIABLE = "FLOCI_SPARK_MASTER"; + /** The cores and memory, in MiB, an executor's worker offers, in its container. */ + static final String CORES_VARIABLE = "FLOCI_EXECUTOR_CORES"; + static final String MEMORY_VARIABLE = "FLOCI_EXECUTOR_MEMORY_MB"; + /** The component label of an executor's container. */ + static final String COMPONENT = "emr-serverless-executor"; + /** The ports the driver's UI and the master's answer on, in the driver's container. */ + static final int DRIVER_UI_PORT = 4040; + static final int MASTER_UI_PORT = 8080; + private static final int MASTER_PORT = 7077; + private static final String SPARK_CLASS = "/usr/lib/spark/bin/spark-class"; + // The image's spark-defaults turn authentication on, which the master and the worker read too, so each gets the + // run's secret; Spark 4's master refuses it while its REST submission server is on, which nothing here uses; and + // its UI, which Floci only reads, kills nothing, as any container on the network reaches it. + private static final String MASTER_OPTIONS = "-Dspark.authenticate.secret=$" + SECRET_VARIABLE + + " -Dspark.master.rest.enabled=false -Dspark.ui.killEnabled=false"; + + /** + * Runs before {@code spark-submit}, given as its first argument, then how many of the rest are its options + * ({@link #optionCount}), the rest being its own: starts the master at the container's address, its log in /tmp, + * waits for its port, then runs {@code spark-submit} with that master, the driver reached at that address, the + * run's secret and its UI's kill links off, after the run's own options, so that none of theirs replaces them, and + * before its primary resource. A master that exits first ends the run, its log on standard error. + */ + static final String DRIVER_WRAPPER = String.join("\n", + "address=$(hostname -i | awk '{print $1}')", + "SPARK_MASTER_OPTS=\"" + MASTER_OPTIONS + "\" " + SPARK_CLASS + " org.apache.spark.deploy.master.Master" + + " --host \"$address\" --port " + MASTER_PORT + " --webui-port " + MASTER_UI_PORT + + " > /tmp/floci-spark-master.log 2>&1 &", + "master=$!", + "until (exec 3<>\"/dev/tcp/$address/" + MASTER_PORT + "\") 2>/dev/null; do", + " kill -0 $master 2>/dev/null || { cat /tmp/floci-spark-master.log >&2; exit 1; }", + " sleep 0.2", + "done", + "submit=$1; options=$2; shift 2", + "exec \"$submit\" \"${@:1:$options}\" --master \"spark://$address:" + MASTER_PORT + "\"" + + " --conf \"spark.driver.host=$address\" --conf \"spark.authenticate.secret=$" + SECRET_VARIABLE + + "\" --conf spark.ui.killEnabled=false \"${@:$((options + 1))}\""); + + // spark-submit's options that take a value, as its option parser (SparkSubmitOptionParser) names them; its other + // options are switches, and its first argument that is no option is its primary resource. + private static final Set VALUE_OPTIONS = Set.of("--archives", "--class", "--conf", "-c", "--deploy-mode", + "--driver-class-path", "--driver-cores", "--driver-java-options", "--driver-library-path", "--driver-memory", + "--exclude-packages", "--executor-cores", "--executor-memory", "--files", "--jars", "--keytab", "--kill", + "--master", "--name", "--num-executors", "--packages", "--principal", "--properties-file", "--proxy-user", + "--py-files", "--queue", "--remote", "--repositories", "--status", "--total-executor-cores"); + + /** + * An executor's container: a standalone worker at the container's address, offering the cores and memory its + * variables give, its executors' folders in /tmp, the image's own not being its user's. + */ + static final String WORKER_SCRIPT = String.join("\n", + "address=$(hostname -i | awk '{print $1}')", + "SPARK_WORKER_OPTS=\"-Dspark.authenticate.secret=$" + SECRET_VARIABLE + "\" exec " + SPARK_CLASS + + " org.apache.spark.deploy.worker.Worker --cores \"$" + CORES_VARIABLE + "\"" + + " --memory \"${" + MEMORY_VARIABLE + "}m\" --work-dir /tmp/floci-spark-work" + + " --host \"$address\" \"spark://$" + MASTER_VARIABLE + ":" + MASTER_PORT + "\""); + + // How often the driver is looked at, and how long its UI may stay silent once the master has its application + // before executors start without its settings, both in real time rather than the clock Floci keeps. + static final Duration LOOK_INTERVAL = Duration.ofSeconds(2); + static final Duration UI_SILENCE = Duration.ofSeconds(30); + // What a worker offers when the driver's UI never answers: enough for any one executor's settings. With the run's + // settings unknown, it and the driver's worker count for nothing against the application's maximum capacity. + static final Size BLIND_SIZE = new Size(32, 256 * 1024, Amount.NONE, Amount.NONE); + // EMR Serverless's own defaults for a worker's disk, and Spark's for an executor's memory overhead. + private static final long DEFAULT_DISK_GB = 20; + private static final long MINIMUM_OVERHEAD_MIB = 384; + private static final double DEFAULT_OVERHEAD_FACTOR = 0.10; + // EMR Serverless's overhead factor for the driver's and the executors' workers alike. + private static final String EMR_OVERHEAD_FACTOR = "spark.emr-serverless.memoryOverheadFactor"; + private static final Pattern SIZE = Pattern.compile("(\\d+)\\s*([kmgtp]?)b?", Pattern.CASE_INSENSITIVE); + + /** The driver's container, which answers a GET of a path on one of its ports, or null when nothing does. */ + interface Driver { + String get(int port, String path); + } + + /** The executors' containers. */ + interface Containers { + + /** Starts the {@code index}th executor's container, its worker offering {@code size}'s cores and memory. */ + Worker start(int index, Size size); + + /** Whether the container still runs. */ + boolean running(String containerId); + + /** Stops and removes it. */ + void remove(String containerId); + } + + /** An executor's container and its address, which its worker registers with the master at. */ + record Worker(String containerId, String address) { + } + + /** + * What one executor's worker offers and holds, and what the driver's holds: the executor's cores and memory in MiB, + * which the worker offers Spark, and what its worker and the driver's count toward the application's maximum + * capacity. + */ + record Size(int cores, long memoryMib, Amount executor, Amount driver) { + } + + /** What a worker counts toward its application's maximum capacity: its vCPUs, and its memory and disk in GB. */ + record Amount(long vcpus, long memoryGb, long diskGb) { + static final Amount NONE = new Amount(0, 0, 0); + } + + /** + * What the workers of an application's runs hold at once, which its runs share, so that together they stay within + * its maximum capacity, as it "is cumulative across all workers at any given point in time"; a run's driver is held + * once its size is known, whatever room is left, as it already runs. + */ + static final class Capacity { + private long vcpus; + private long memoryGb; + private long diskGb; + private int runs; + + /** Takes {@code amount} when {@code limits} have room for it beside what is held, each limit 0 for none. */ + synchronized boolean take(Amount amount, Executors limits) { + if (over(vcpus + amount.vcpus(), limits.vcpus()) || over(memoryGb + amount.memoryGb(), limits.memoryGb()) + || over(diskGb + amount.diskGb(), limits.diskGb())) { + return false; + } + hold(amount); + return true; + } + + /** Takes {@code amount} whatever room is left. */ + synchronized void hold(Amount amount) { + vcpus += amount.vcpus(); + memoryGb += amount.memoryGb(); + diskGb += amount.diskGb(); + } + + /** Gives {@code amount} back. */ + synchronized void release(Amount amount) { + vcpus -= amount.vcpus(); + memoryGb -= amount.memoryGb(); + diskGb -= amount.diskGb(); + } + + /** What is held, as vCPUs, memory and disk. */ + synchronized Amount held() { + return new Amount(vcpus, memoryGb, diskGb); + } + + /** One more run shares this capacity. */ + synchronized Capacity joined() { + runs++; + return this; + } + + /** One run no longer shares it; true once none does. */ + synchronized boolean left() { + return --runs <= 0; + } + + private static boolean over(long held, long limit) { + return limit > 0 && held > limit; + } + } + + private final Executors executors; + private final Driver driver; + private final Containers containers; + private final Capacity capacity; + private final LongSupplier nanoTime; + private final List workers = new ArrayList<>(); + // Containers that ended or were removed while Docker would not remove them, to try again at the run's end. + private final List leftovers = new ArrayList<>(); + private int nextIndex = 1; + private boolean looked; + private long nextLook; + private Long applicationSeen; + private Size size; + // Read with the size: whether Spark's dynamic allocation is on, and, when it is not, how many executors it wants. + private boolean dynamic = true; + private int instances; + + SparkExecutors(Executors executors, Driver driver, Containers containers, Capacity capacity, + LongSupplier nanoTime) { + this.executors = executors; + this.driver = driver; + this.containers = containers; + this.capacity = capacity; + this.nanoTime = nanoTime; + } + + /** The executors' containers that run now. */ + List workers() { + return List.copyOf(workers); + } + + /** + * Looks at the driver, at most once a {@link #LOOK_INTERVAL}, and starts or removes executors' containers to match + * what it wants, removing those that ended. A look that fails changes nothing more, and the next one tries again. + */ + void follow() { + long now = nanoTime.getAsLong(); + if (looked && now - nextLook < 0) { + return; + } + looked = true; + nextLook = now + LOOK_INTERVAL.toNanos(); + try { + for (Iterator each = workers.iterator(); each.hasNext(); ) { + Worker worker = each.next(); + if (!containers.running(worker.containerId())) { + each.remove(); + capacity.release(size.executor()); + remove(worker.containerId()); + } + } + if (size == null) { + size = readSize(now); + if (size == null) { + return; + } + capacity.hold(size.driver()); + } + Integer target = target(); + if (target == null) { + return; + } + int wanted = Math.min(target, executors.containers()); + while (workers.size() < wanted && capacity.take(size.executor(), executors)) { + Worker worker; + try { + worker = containers.start(nextIndex++, size); + } catch (RuntimeException e) { + capacity.release(size.executor()); + throw e; + } + workers.add(worker); + } + if (workers.size() > wanted) { + removeIdle(workers.size() - wanted); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not follow the executors of a Spark run"); + } + } + + /** Removes every executor's container, and gives back what its workers held, as the run has ended. */ + void removeAll() { + for (Worker worker : workers) { + capacity.release(size.executor()); + remove(worker.containerId()); + } + workers.clear(); + for (String containerId : List.copyOf(leftovers)) { + leftovers.remove(containerId); + remove(containerId); + } + if (size != null) { + capacity.release(size.driver()); + size = null; + } + } + + /** How many of spark-submit's {@code arguments} are its options, before its primary resource and its arguments. */ + static int optionCount(List arguments) { + int count = 0; + while (count < arguments.size() && arguments.get(count).startsWith("-")) { + // "--conf=key=value" is one argument, "--conf key=value" two. + count += VALUE_OPTIONS.contains(arguments.get(count)) ? 2 : 1; + } + return Math.min(count, arguments.size()); + } + + // Removes an executor's container; one Docker will not remove yet is tried again at the run's end. + private void remove(String containerId) { + try { + containers.remove(containerId); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove executor container {0}", containerId); + if (!leftovers.contains(containerId)) { + leftovers.add(containerId); + } + } + } + + // An executor's size, from the driver's settings once its UI answers; or, once the master has had the driver's + // application for UI_SILENCE without its UI answering, as a job that turned it off would have it, BLIND_SIZE. + private Size readSize(long now) { + String applications = driver.get(DRIVER_UI_PORT, "/api/v1/applications"); + if (applications == null) { + if (applicationSeen == null && masterHasApplication()) { + applicationSeen = now; + } + if (applicationSeen != null && now - applicationSeen >= UI_SILENCE.toNanos()) { + LOG.warnv("The driver's UI of a Spark run does not answer, so its executors start without its" + + " settings; spark.ui.enabled=false keeps Floci from sizing them"); + dynamic = false; + instances = 1; + return BLIND_SIZE; + } + return null; + } + JsonNode list = parse(applications); + if (list == null || !list.isArray() || list.isEmpty()) { + return null; + } + String environment = driver.get(DRIVER_UI_PORT, + "/api/v1/applications/" + list.get(0).path("id").asText() + "/environment"); + JsonNode properties = environment != null ? parse(environment) : null; + if (properties == null) { + return null; + } + Map settings = new HashMap<>(); + for (JsonNode pair : properties.path("sparkProperties")) { + settings.put(pair.path(0).asText(), pair.path(1).asText()); + } + dynamic = Boolean.parseBoolean(settings.getOrDefault("spark.dynamicAllocation.enabled", "false")); + instances = (int) Math.max(0, number(settings.get("spark.executor.instances"), 2)); + return sizeOf(settings); + } + + /** What one executor's worker offers and holds, and the driver's, from a run's Spark settings. */ + static Size sizeOf(Map settings) { + int cores = (int) Math.max(1, number(settings.get("spark.executor.cores"), 1)); + long memory = mebibytes(settings.get("spark.executor.memory"), 1024); + long driverMemory = mebibytes(settings.get("spark.driver.memory"), 1024); + return new Size(cores, memory, + new Amount(cores, workerGb(memory, settings, "spark.executor"), + gigabytes(settings.get("spark.emr-serverless.executor.disk"))), + new Amount(Math.max(1, number(settings.get("spark.driver.cores"), 1)), + workerGb(driverMemory, settings, "spark.driver"), + gigabytes(settings.get("spark.emr-serverless.driver.disk")))); + } + + // A worker's memory in whole GB: the JVM's heap and its overhead, rounded up, as worker memory comes in steps of + // 1 GB. The overhead is the role's memoryOverhead when set, else its share of the heap, by the role's + // memoryOverheadFactor, else EMR Serverless's, else 10%, and at least 384 MB, as "The overhead has a default + // value of 10% of container memory, with a minimum of 384 MB". + private static long workerGb(long heapMib, Map settings, String role) { + String overhead = settings.get(role + ".memoryOverhead"); + String factor = settings.getOrDefault(role + ".memoryOverheadFactor", settings.get(EMR_OVERHEAD_FACTOR)); + long overheadMib = overhead != null ? mebibytes(overhead, MINIMUM_OVERHEAD_MIB) + : Math.max(MINIMUM_OVERHEAD_MIB, (long) (heapMib * fraction(factor))); + return (heapMib + overheadMib + 1023) / 1024; + } + + private static double fraction(String value) { + try { + return value != null ? Double.parseDouble(value.trim()) : DEFAULT_OVERHEAD_FACTOR; + } catch (NumberFormatException e) { + return DEFAULT_OVERHEAD_FACTOR; + } + } + + // How many executors Spark wants: dynamic allocation's target, from the driver's metrics, or, without it, its + // executor instances. + private Integer target() { + if (!dynamic) { + return instances; + } + String metrics = driver.get(DRIVER_UI_PORT, "/metrics/json/"); + JsonNode gauges = metrics != null ? parse(metrics) : null; + if (gauges == null) { + return null; + } + for (Map.Entry gauge : gauges.path("gauges").properties()) { + if (gauge.getKey().endsWith("ExecutorAllocationManager.executors.numberTargetExecutors")) { + return gauge.getValue().path("value").asInt(); + } + } + return null; + } + + private boolean masterHasApplication() { + String state = driver.get(MASTER_UI_PORT, "/json/"); + JsonNode master = state != null ? parse(state) : null; + return master != null && !master.path("activeapps").isEmpty(); + } + + // Removes up to count executors' containers whose worker runs no executor, newest first, as the master tells. + private void removeIdle(int count) { + String state = driver.get(MASTER_UI_PORT, "/json/"); + JsonNode master = state != null ? parse(state) : null; + if (master == null) { + return; + } + Map coresUsed = new HashMap<>(); + for (JsonNode worker : master.path("workers")) { + coresUsed.put(worker.path("host").asText(), worker.path("coresused").asInt()); + } + for (int i = workers.size() - 1; i >= 0 && count > 0; i--) { + Worker worker = workers.get(i); + if (Integer.valueOf(0).equals(coresUsed.get(worker.address()))) { + containers.remove(worker.containerId()); + workers.remove(i); + capacity.release(size.executor()); + count--; + } + } + } + + private static JsonNode parse(String json) { + try { + return JSON.readTree(json); + } catch (IOException e) { + return null; + } + } + + private static long number(String value, long otherwise) { + if (value == null) { + return otherwise; + } + try { + return Long.parseLong(value.trim()); + } catch (NumberFormatException e) { + return otherwise; + } + } + + // A size as Spark takes it, "14G" or "1024m", in MiB, a bare number being MiB, as spark.executor.memory has it. + static long mebibytes(String value, long otherwise) { + Matcher size = value != null ? SIZE.matcher(value.trim()) : null; + if (size == null || !size.matches()) { + return otherwise; + } + long amount = Long.parseLong(size.group(1)); + return switch (size.group(2).toLowerCase(Locale.ROOT)) { + case "k" -> Math.max(1, amount / 1024); + case "g" -> amount * 1024; + case "t" -> amount * 1024 * 1024; + case "p" -> amount * 1024 * 1024 * 1024; + default -> amount; + }; + } + + // A disk size in GB, as "20G" gives it, EMR Serverless's 20 GB when not set. + static long gigabytes(String value) { + return value != null ? Math.max(1, (mebibytes(value, DEFAULT_DISK_GB * 1024) + 1023) / 1024) : DEFAULT_DISK_GB; + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index 90b4fe262e..68bf648179 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -78,9 +78,10 @@ public interface SparkJobRunner { * {@code core-site.xml} properties its {@code hadoop} command gets, on a cluster, after those of the * cluster's storage, which they replace where a name is the same (empty for none); the * {@code log4j2.properties} lines its Spark gets after those of its configuration, which they replace where - * a key is the same (empty for none); and, on a cluster, the {@code mapred-site.xml} properties its + * a key is the same (empty for none); on a cluster, the {@code mapred-site.xml} properties its * MapReduce gets, the {@code log4j.properties} lines and the {@code hadoop-env.sh} exports its {@code hadoop} - * command gets (each empty for none). + * command gets (each empty for none); and, for an EMR Serverless Spark run, where its executors run, in + * containers of their own (null for Spark's local mode, in the driver's container). */ record Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine, String imageTemplate, String customImage, String dockerNetwork, String executionRole, @@ -88,22 +89,42 @@ public interface SparkJobRunner { String logFolder, CloudWatchLogs cloudWatchLogs, Map environment, List archives, Storage storage, Map coreSite, Map sparkLog4j2, Map mapredSite, Map hadoopLog4j, - Map hadoopEnvironment) { + Map hadoopEnvironment, Executors executors) { /** This job, on {@code storage}. */ public Job onStorage(Storage storage) { return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, - hadoopEnvironment); + hadoopEnvironment, executors); } /** This job, run in {@code image}. */ public Job inImage(String image) { return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment, - archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment); + archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment, executors); } + + /** This job, its executors where {@code executors} has them. */ + public Job withExecutors(Executors executors) { + return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, + dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, + cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, + hadoopEnvironment, executors); + } + } + + /** + * An EMR Serverless Spark run's executors, each in a container of its own, as each has a worker of its own on EMR + * Serverless: at most {@code containers} at once; in {@code image}, the application's custom image for its + * executors, or the release's EMR Serverless image when null; and none that would take the workers of + * {@code application}'s runs, its drivers' among them, past its maximum capacity: {@code vcpus}, {@code memoryGb} + * and {@code diskGb} in all, each 0 for no limit, as that capacity "is cumulative across all workers at any given + * point in time". {@code application} names the application its runs share that capacity in, or is null for a + * run that shares it with none. + */ + record Executors(int containers, String image, long vcpus, long memoryGb, long diskGb, String application) { } /** diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 81d6680e01..995f3f78a7 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -156,6 +156,7 @@ quarkus: - --initialize-at-run-time=io.floci.aws.services.bedrockagentcore.BedrockAgentCoreEventService - --initialize-at-run-time=io.floci.aws.services.cloudfront.CloudFrontService - --initialize-at-run-time=io.floci.aws.services.emr.EmrService + - --initialize-at-run-time=io.floci.aws.services.emrserverless.EmrServerlessSparkRunner - --initialize-at-run-time=io.floci.aws.services.elasticbeanstalk.ElasticBeanstalkService - --initialize-at-run-time=io.floci.aws.services.elb.ElbClassicService - --initialize-at-run-time=io.floci.aws.services.datasync.DataSyncService @@ -1048,8 +1049,9 @@ floci: # 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. + executor-containers: 0 # a docker Spark run's executors at once, each in a container; 0 = local mode + # Remove the drivers and executors 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 diff --git a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java index a90c6f8311..679359b9dd 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java @@ -57,7 +57,7 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * EMR steps and EMR Serverless job runs through Floci's Docker runner for real: a cluster in the {@code docker} * runner mode runs each step, and an application each job run, in a container of the release's EMR Serverless image, - * which reaches Floci's S3 and Glue from there. The cached {@code emr-7.5.0} image keeps a local run from pulling; + * which reaches Floci's S3 and Glue from there, a job run's executors each in a container of their own, as the profile sets. The cached {@code emr-7.5.0} image keeps a local run from pulling; * CI pulls it (3.5 GB) the first time. */ @QuarkusTest @@ -392,6 +392,38 @@ class EmrDockerRunnerDockerIntegrationTest { assertEquals("from the archive environment\n", partFiles("venv-out/")); } + @Test + void anEmrServerlessRunsExecutorsRunInContainersOfTheirOwnThatGoWithIt() { + put("side/hosts.py", """ + import socket, sys, time + from pyspark.sql import SparkSession + spark = SparkSession.builder.getOrCreate() + hosts = spark.sparkContext.parallelize(range(24), 24) \\ + .map(lambda i: (time.sleep(0.5), socket.gethostname())[1]).distinct().collect() + where = "with the driver" if socket.gethostname() in hosts else "apart from the driver" + spark.createDataFrame([("%d executors, %s" % (len(hosts), where),)], ["value"]) \\ + .coalesce(1).write.text(sys.argv[1]) + """); + String applicationId = createSparkApplication(REGION, "emr-7.5.0"); + cleanup.register(() -> deleteApplication(REGION, applicationId)); + ObjectNode run = JSON.createObjectNode().put("clientToken", UUID.randomUUID().toString()) + .put("executionRoleArn", "arn:aws:iam::000000000000:role/emr-serverless-job"); + ObjectNode sparkSubmit = run.putObject("jobDriver").putObject("sparkSubmit") + .put("entryPoint", s3Uri("side/hosts.py")) + .put("sparkSubmitParameters", "--conf spark.executor.cores=2 --conf spark.executor.memory=1g"); + sparkSubmit.putArray("entryPointArguments").add(s3Uri("hosts-out/")); + String jobRunId = startJobRun(REGION, applicationId, run.toString()); + + Response ended = awaitJobRun(REGION, applicationId, jobRunId); + + assertEquals("SUCCESS", ended.jsonPath().getString("jobRun.state")); + // Each executor has a worker of its own, as on EMR Serverless, up to the profile's two. + assertEquals("2 executors, apart from the driver\n", partFiles("hosts-out/")); + await().atMost(Duration.ofSeconds(30)).until(() -> lifecycle.getDockerClient().listContainersCmd() + .withShowAll(true).withLabelFilter(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, jobRunId)) + .exec().isEmpty()); + } + /** * A stand-in for the guide's packed virtual environment that needs no package index: its {@code bin/python} * runs the image's Python with the archive's own {@code lib} on the path, where the module the job imports is. diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java index 572bb46c3e..5f64bdb566 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -13,6 +13,7 @@ import io.floci.aws.services.emrserverless.model.JobDriver; import io.floci.aws.services.emrserverless.model.JobRun; import io.floci.aws.services.emrserverless.model.JobRunAttemptSummary; import io.floci.aws.services.emrserverless.model.JobRunRecord; +import io.floci.aws.services.emrserverless.model.MaximumCapacity; import io.floci.aws.services.emrserverless.model.MonitoringConfiguration; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; @@ -295,7 +296,7 @@ class EmrServerlessJobRunServiceTest { String driverImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/driver:7.5.0"; CreateApplicationRequest wholeApplication = applicationRequest("custom", "emr-7.5.0", "SPARK"); wholeApplication.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage)); - // Local mode runs the executors in the driver's container, so an Executor image is not used. + // The executors' worker type's image is theirs, not the driver's. wholeApplication.setWorkerTypeSpecifications( Map.of("Executor", EmrServerlessServiceTest.workerType(driverImage))); CreateApplicationRequest perWorkerType = applicationRequest("per-worker-type", "emr-7.5.0", "SPARK"); @@ -314,6 +315,67 @@ class EmrServerlessJobRunServiceTest { assertNull(runner.jobs.get(2).customImage()); } + @Test + void aSparkRunsExecutorsRunApartInTheirWorkerTypesImageWithinTheApplicationsMaximumCapacity() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner, 2); + String applicationImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/custom:7.5.0"; + String executorImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/spark/executor:7.5.0"; + CreateApplicationRequest capped = applicationRequest("capped", "emr-7.5.0", "SPARK"); + capped.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage)); + capped.setWorkerTypeSpecifications(Map.of("Executor", EmrServerlessServiceTest.workerType(executorImage))); + MaximumCapacity capacity = new MaximumCapacity(); + capacity.setCpu("12 vCPU"); + capacity.setMemory("64 GB"); + capacity.setDisk("200 GB"); + capped.setMaximumCapacity(capacity); + CreateApplicationRequest whole = applicationRequest("whole", "emr-7.5.0", "SPARK"); + whole.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage)); + String hive = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE")) + .getApplicationId(); + + Application cappedApplication = applications.createApplication(capped); + Application wholeApplication = applications.createApplication(whole); + service.startJobRun(cappedApplication.getApplicationId(), request(null, null)); + service.startJobRun(wholeApplication.getApplicationId(), request(null, null)); + service.startJobRun(applicationId, request(null, null)); + service.startJobRun(hive, hiveRequest("s3://bucket/queries/report.sql", null, null)); + for (int i = 0; i < 4; i++) { + runNext(); + } + + // Each within its application's capacity, which that application's runs share. + assertEquals(new SparkJobRunner.Executors(2, executorImage, 12, 64, 200, cappedApplication.getArn()), + runner.jobs.get(0).executors()); + // The application's image applies to every worker type; without one, the release's. + assertEquals(new SparkJobRunner.Executors(2, applicationImage, 0, 0, 0, wholeApplication.getArn()), + runner.jobs.get(1).executors()); + assertEquals(new SparkJobRunner.Executors(2, null, 0, 0, 0, + applications.getApplication(applicationId).getArn()), runner.jobs.get(2).executors()); + // Tez runs a Hive run's tasks in its driver's container. + assertNull(runner.jobs.get(3).executors()); + } + + @Test + void withoutExecutorContainersARunsExecutorsRunInItsDriversContainer() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner, 0); + + service.startJobRun(applicationId, request(null, null)); + runNext(); + + assertNull(runner.jobs.get(0).executors()); + } + + @Test + void aMaximumCapacitysAmountIsTheNumberItStartsWith() { + assertEquals(400, EmrServerlessJobRunService.capacityAmount("400 vCPU")); + assertEquals(1024, EmrServerlessJobRunService.capacityAmount("1024GB")); + assertEquals(0, EmrServerlessJobRunService.capacityAmount(null)); + assertEquals(0, EmrServerlessJobRunService.capacityAmount("GB")); + assertEquals(Long.MAX_VALUE, EmrServerlessJobRunService.capacityAmount("9".repeat(30))); + } + @Test void aHiveRunGetsTheHiveDriverWorkerTypesCustomImageElseTheApplicationsElseTheReleases() { FakeRunner runner = new FakeRunner(); @@ -1017,6 +1079,12 @@ class EmrServerlessJobRunServiceTest { null, objectMapper, 0, clock, runner, tasks::add); } + // A service whose Spark runs have up to executorContainers executors in containers of their own. + private EmrServerlessJobRunService dockerService(SparkJobRunner runner, int executorContainers) { + return new EmrServerlessJobRunService(store, applications, iamService, new RegionResolver(REGION, ACCOUNT_ID), + null, objectMapper, 0, clock, runner, tasks::add, null, null, null, executorContainers); + } + private void runNext() { tasks.remove(0).run(); } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java index d7eef73b78..1e77686eb1 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; import com.github.dockerjava.api.exception.InternalServerErrorException; +import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.StreamType; @@ -11,6 +12,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerExecStubs; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerStorageHelper; @@ -60,7 +62,10 @@ import static io.floci.aws.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; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -68,6 +73,7 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.atLeastOnce; @@ -366,6 +372,220 @@ class EmrServerlessSparkRunnerTest { verify(lifecycle, never()).connectToNetwork(anyString(), anyString()); } + @Test + void aSparkRunsExecutorsRunApartOnlyOnANetworkOfContainers() { + SparkJobRunner.Job apart = executorsJob(Map.of()); + + assertTrue(EmrServerlessSparkRunner.executorsApart(apart, "floci-network")); + assertTrue(EmrServerlessSparkRunner.executorsApart(apart, null)); + // On the host's network, or in another container's namespace, its ports would meet another run's. + assertFalse(EmrServerlessSparkRunner.executorsApart(apart, "host")); + assertFalse(EmrServerlessSparkRunner.executorsApart(apart, "container:floci")); + // A job without them, a Hive run and a step keep their executors where they were. + assertFalse(EmrServerlessSparkRunner.executorsApart(job(Duration.ZERO), "floci-network")); + assertFalse(EmrServerlessSparkRunner.executorsApart(hiveJob(List.of()).withExecutors(EXECUTORS), + "floci-network")); + assertFalse(EmrServerlessSparkRunner.executorsApart(stepJob(Map.of()).withExecutors(EXECUTORS), + "floci-network")); + } + + @Test + void aRunWhoseExecutorsRunApartTakesItsMasterFromItsContainerAndHasItsUiOn() { + List arguments = EmrServerlessSparkRunner.sparkSubmitArguments( + executorsJob(Map.of("spark.ui.enabled", "false")), ENDPOINT); + + assertFalse(arguments.contains("--master")); + // Floci's comes before the job's own, which wins. + int on = arguments.indexOf("spark.ui.enabled=true"); + assertTrue(on > 0 && arguments.indexOf("spark.ui.enabled=false") > on); + // Its kill links, which any container on the network reaches, the driver's container turns off. + assertFalse(arguments.contains("spark.ui.killEnabled=false")); + } + + @Test + void whatTheDriversContainerForcesComesAfterTheRunsOwnOptionsAndBeforeItsPrimaryResource() { + List arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job(null, + List.of("--conf", "spark.ui.killEnabled=true", "--conf=spark.authenticate.secret=mine", "--master", + "local[2]", "s3://bucket/jobs/app.jar", "--conf", "for-the-app"), + Map.of("spark.ui.killEnabled", "true"), Duration.ZERO).withExecutors(EXECUTORS), ENDPOINT); + + // The driver's container gives its master, secret and kill links after the options its count covers, + // the run's own settings and options among them, and before the run's primary resource. + int options = SparkExecutors.optionCount(arguments); + assertEquals("s3://bucket/jobs/app.jar", arguments.get(options)); + assertTrue(arguments.subList(0, options).containsAll(List.of("spark.ui.killEnabled=true", + "--conf=spark.authenticate.secret=mine", "--master", "local[2]"))); + } + + @Test + void theDriverOfARunWhoseExecutorsRunApartStartsTheMasterWithTheRunsSecretThenFlociAsksItsUi() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + EmrServerlessSparkRunner runner = runner(builder); + List> asked = ContainerExecStubs.completeEveryExec(docker, "driver", 7L, "", ""); + + runner.run(executorsJob(Map.of()), progress); + + // spark-submit, then how many of its arguments are options, which the wrapper puts its own after. + ArgumentCaptor> cmd = ArgumentCaptor.captor(); + verify(spec).withCmd(cmd.capture()); + verify(spec).withEntrypoint(List.of("/bin/bash", "-c", SparkExecutors.DRIVER_WRAPPER, "floci", + "/usr/lib/spark/bin/spark-submit", String.valueOf(SparkExecutors.optionCount(cmd.getValue())))); + assertEquals("s3://bucket/jobs/app.jar", cmd.getValue().get(SparkExecutors.optionCount(cmd.getValue()))); + verify(spec).withEnv(eq(SparkExecutors.SECRET_VARIABLE), + argThat((String secret) -> secret.matches("[0-9a-f]{64}"))); + assertFalse(cmd.getValue().contains("--master")); + assertEquals(List.of("curl", "-sf", "-m", "2", "http://127.0.0.1:4040/api/v1/applications"), + asked.getFirst()); + verify(lifecycle, never()).createAndStart(any()); + } + + @Test + void aRunsExecutorsContainersGoWithItsDriver() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("executor", + Map.of())); + EmrServerlessSparkRunner runner = runner(builder); + // A driver whose settings leave dynamic allocation off, so its two executor instances start at once. + ContainerExecStubs.completeEveryExec(docker, "driver", 0L, "[{\"id\": \"app-1\"}]", ""); + + assertEquals(0, runner.run(executorsJob(Map.of()), progress).exitCode()); + + verify(lifecycle, times(2)).createAndStart(any()); + verify(lifecycle, times(2)).stopAndRemove("executor", null, 0); + } + + @Test + void onTheHostsNetworkARunsExecutorsRunInItsDriversContainer() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + when(builder.resolveDockerNetwork(Optional.of("floci-network"))).thenReturn(Optional.of("host")); + + runner(builder).run(executorsJob(Map.of()), progress); + + verify(spec).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit")); + verify(spec).withCmd(argThat((List cmd) -> List.of("--master", "local[*]").equals(cmd.subList(0, 2)))); + verify(spec, never()).withEnv(eq(SparkExecutors.SECRET_VARIABLE), anyString()); + } + + @Test + void anExecutorsContainerIsAWorkerOnTheDriversNetworkLabelledAsTheRunsAndGoesWhenRemoved() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("executor", + Map.of())); + when(lifecycle.resolveContainerNetworkIp("executor", "floci-network")).thenReturn("172.18.0.9"); + SparkExecutors.Containers containers = runner(builder).executorContainers(executorsJob(Map.of()), + "sha256:image", "floci-network", "172.18.0.4", "secret", AWS_ENVIRONMENT, + Map.of(ContainerStorageHelper.SERVICE_LABEL, "emr-serverless")); + + SparkExecutors.Worker worker = containers.start(2, FOUR_CORE_EXECUTOR); + containers.remove(worker.containerId()); + + assertEquals(new SparkExecutors.Worker("executor", "172.18.0.9"), worker); + verify(builder).newContainer("sha256:image"); + verify(spec).withName(ContainerStorageHelper.dockerName(config, "emr-serverless-00f0000000000001-executor-2")); + verify(spec).withEntrypoint(List.of("/bin/bash", "-c", SparkExecutors.WORKER_SCRIPT)); + // The driver's AWS environment, its master and secret, and the executor's cores and memory. + verify(spec).withEnv(AWS_ENVIRONMENT); + verify(spec).withEnv(SparkExecutors.SECRET_VARIABLE, "secret"); + verify(spec).withEnv(SparkExecutors.MASTER_VARIABLE, "172.18.0.4"); + verify(spec).withEnv(SparkExecutors.CORES_VARIABLE, "4"); + verify(spec).withEnv(SparkExecutors.MEMORY_VARIABLE, "14336"); + verify(spec).withDockerNetwork(Optional.of("floci-network")); + verify(spec).withJavaTrustStore(); + // Found by a reset and the leftover sweep as the run's driver is. + verify(spec).withLabels(argThat(labels -> "emr-serverless".equals(labels.get(ContainerStorageHelper.SERVICE_LABEL)) + && SparkExecutors.COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL)))); + verify(lifecycle).stopAndRemove("executor", null, 0); + } + + @Test + void anExecutorsContainerWhoseAddressCannotBeFoundGoesBeforeItIsTheRunsToRemove() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("executor", + Map.of())); + when(lifecycle.resolveContainerNetworkIp("executor", "floci-network")) + .thenThrow(new IllegalStateException("no address")); + SparkExecutors.Containers containers = runner(builder).executorContainers(executorsJob(Map.of()), + "sha256:image", "floci-network", "172.18.0.4", "secret", AWS_ENVIRONMENT, Map.of()); + + assertThrows(IllegalStateException.class, () -> containers.start(1, FOUR_CORE_EXECUTOR)); + + verify(lifecycle).stopAndRemove("executor", null, 0); + } + + @Test + void aDriverThatCannotBeAskedAnswersNothing() { + EmrServerlessSparkRunner runner = runner(mock(ContainerBuilder.class)); + when(docker.execCreateCmd("driver")).thenThrow(new NotFoundException("gone")); + + assertNull(runner.driver("driver").get(SparkExecutors.DRIVER_UI_PORT, "/api/v1/applications")); + } + + @Test + void theRunsOfAnApplicationShareOneCapacityWhichGoesWithTheLast() { + EmrServerlessSparkRunner runner = runner(); + SparkExecutors.Capacity first = runner.joinCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a"); + SparkExecutors.Capacity second = runner.joinCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a"); + + assertSame(first, second); + assertNotSame(first, runner.joinCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/b")); + // A run of no application shares it with none. + assertNotSame(runner.joinCapacity(null), runner.joinCapacity(null)); + runner.leaveCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a", first); + assertSame(first, runner.joinCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a")); + runner.leaveCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a", first); + runner.leaveCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a", first); + assertNotSame(first, runner.joinCapacity("arn:aws:emr-serverless:eu-west-1:123456789012:/app/a")); + } + + @Test + void theReleasesImageForARunsExecutorsIsPulledWhenMissingBeforeTheDriverStarts() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + EmrServerlessSparkRunner runner = runner(builder); + ContainerExecStubs.completeEveryExec(docker, "driver", 7L, "", ""); + + runner.run(executorsJob(Map.of()), progress); + + // Not while the run waits for its executors, where a pull would hold up a cancel and the run's timeout. + InOrder order = inOrder(lifecycle); + order.verify(lifecycle).resolveImageForLaunch("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest", + ImagePullBehavior.PREFER_CACHED, null); + order.verify(lifecycle).create(any()); + } + + @Test + void anApplicationsImageForItsExecutorsIsPulledBeforeTheDriverStarts() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + String custom = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/spark/executor:7.5.0"; + String inFlocisRegistry = "localhost:5100/123456789012/eu-west-1/spark/executor:7.5.0"; + when(builder.newContainer(anyString())).thenReturn(spec); + when(builder.resolveImage(inFlocisRegistry)).thenReturn(inFlocisRegistry); + when(ecr.rewriteImageUri(custom)).thenReturn(inFlocisRegistry); + when(lifecycle.resolveImageForLaunch(inFlocisRegistry, ImagePullBehavior.DEFAULT, null)) + .thenReturn(new LaunchImage("sha256:" + "5".repeat(64), null)); + EmrServerlessSparkRunner runner = runner(builder); + ContainerExecStubs.completeEveryExec(docker, "driver", 7L, "", ""); + + runner.run(executorsJob(Map.of()).withExecutors(new SparkJobRunner.Executors(2, custom, 0, 0, 0, null)), + progress); + + InOrder order = inOrder(lifecycle); + order.verify(lifecycle).resolveImageForLaunch(inFlocisRegistry, ImagePullBehavior.DEFAULT, null); + order.verify(lifecycle).create(any()); + } + @Test void anImageInAnEcrRepositoryRunsFromFlocisRegistryPulledForEveryRun() { ContainerBuilder builder = mock(ContainerBuilder.class); @@ -1755,6 +1975,9 @@ class EmrServerlessSparkRunnerTest { when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false); when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L); when(awsEnv.flociEndpoint()).thenReturn(ENDPOINT); + // An image pulled only when missing is there, by its own name. + when(lifecycle.resolveImageForLaunch(anyString(), eq(ImagePullBehavior.PREFER_CACHED), isNull())) + .thenAnswer(pull -> new LaunchImage(pull.getArgument(0), null)); return new EmrServerlessSparkRunner(builder, lifecycle, logStreamer, awsEnv, mock(LambdaExecutionRoleCredentials.class), s3, ecr, config, new MutableClock(), Duration.ZERO); } @@ -1853,13 +2076,24 @@ class EmrServerlessSparkRunnerTest { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", 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()); + Map.of(), Map.of(), Map.of(), null); + } + + private static final SparkJobRunner.Executors EXECUTORS = new SparkJobRunner.Executors(2, null, 0, 0, 0, null); + // A 4-core 14G executor's size, whose worker and the driver's hold 4 vCPUs, 16 GB and 20 GB of disk. + private static final SparkExecutors.Size FOUR_CORE_EXECUTOR = new SparkExecutors.Size(4, 14336, + new SparkExecutors.Amount(4, 16, 20), new SparkExecutors.Amount(4, 16, 20)); + + // An EMR Serverless Spark run whose executors run in containers of their own. + private static SparkJobRunner.Job executorsJob(Map sparkDefaults) { + return job(null, List.of("s3://bucket/jobs/app.jar"), sparkDefaults, Duration.ZERO).withExecutors(EXECUTORS); } private static SparkJobRunner.Job hiveJob(List 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()); + Duration.ZERO, null, null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), + null); } // An EMR Hive step: hive-script's --args, then application, on cluster j-1's storage. @@ -1869,21 +2103,21 @@ class EmrServerlessSparkRunnerTest { List.of("hive-script", "--run-hive-script", "--args"), Duration.ZERO, null, null, Map.of(), List.of(), new SparkJobRunner.Storage("j-1-home", "j-1-mnt").withHdfs("ip-10-0-0-1.ec2.internal", "172.18.0.5", "j-1-hdfs").withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083"), - Map.of(), Map.of(), Map.of(), Map.of(), Map.of()); + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } private static SparkJobRunner.Job customImageJob(String customImage) { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", 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()); + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } private static SparkJobRunner.Job archiveJob(List archives) { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", 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()); + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } private static SparkJobRunner.Job commandJob(List command, Map sparkDefaults) { @@ -1895,7 +2129,7 @@ class EmrServerlessSparkRunnerTest { 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()); + storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } // A step on a cluster with core-site and spark-log4j2 properties: a command, or a Spark step for a null one. @@ -1904,7 +2138,7 @@ class EmrServerlessSparkRunnerTest { 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()); + null, Map.of(), List.of(), STORAGE, coreSite, sparkLog4j2, Map.of(), Map.of(), Map.of(), null); } // A step on a cluster with mapred-site, hadoop-log4j and hadoop-env: a command, or a custom JAR for a null one. @@ -1914,7 +2148,8 @@ class EmrServerlessSparkRunnerTest { 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); + null, Map.of(), List.of(), STORAGE, Map.of(), Map.of(), mapredSite, hadoopLog4j, hadoopEnvironment, + null); } // A Spark step on a cluster, which has storage. @@ -1923,13 +2158,13 @@ class EmrServerlessSparkRunnerTest { job.imageTemplate(), job.customImage(), job.dockerNetwork(), job.executionRole(), job.sparkDefaults(), job.application(), job.command(), job.timeout(), job.logFolder(), job.cloudWatchLogs(), job.environment(), job.archives(), job.storage(), job.coreSite(), job.sparkLog4j2(), job.mapredSite(), - job.hadoopLog4j(), job.hadoopEnvironment()); + job.hadoopLog4j(), job.hadoopEnvironment(), job.executors()); } private static SparkJobRunner.Job stepJob(Map sparkDefaults) { 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()); + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } } diff --git a/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java b/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java new file mode 100644 index 0000000000..dccc2223e5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java @@ -0,0 +1,420 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.services.emrserverless.SparkExecutors.Amount; +import io.floci.aws.services.emrserverless.SparkExecutors.Capacity; +import io.floci.aws.services.emrserverless.SparkExecutors.Size; +import io.floci.aws.services.emrserverless.SparkExecutors.Worker; +import io.floci.aws.services.emrserverless.SparkJobRunner.Executors; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** An EMR Serverless Spark run's executors in containers of their own, as its driver wants them. */ +class SparkExecutorsTest { + + // The image's own spark-defaults: 4 cores and 14G for the driver and each executor, dynamic allocation on. + private static final Map IMAGE_DEFAULTS = Map.of( + "spark.executor.cores", "4", "spark.executor.memory", "14G", + "spark.driver.cores", "4", "spark.driver.memory", "14G", + "spark.dynamicAllocation.enabled", "true", "spark.executor.instances", "3"); + private static final Executors TWO = new Executors(2, null, 0, 0, 0, null); + // The worker of a 4-core 14G executor, or driver: 14 GB and its 10% overhead rounded up, and a 20 GB disk. + private static final Amount FOUR_CORES = new Amount(4, 16, 20); + + // Real time, as the driver is looked at by it. + private final AtomicLong nanos = new AtomicLong(-5_000_000_000L); + private final FakeDriver driver = new FakeDriver(); + private final FakeContainers containers = new FakeContainers(); + private final Capacity capacity = new Capacity(); + + @Test + void aWorkerOffersItsExecutorsCoresAndHeapAndHoldsItsMemoryWithOverheadAndItsDisk() { + Size size = SparkExecutors.sizeOf(IMAGE_DEFAULTS); + + assertEquals(4, size.cores()); + assertEquals(14 * 1024, size.memoryMib()); + // 14 GB and 10% of it, rounded up to a whole GB: the 16 GB worker the user guide pairs with 4 vCPUs. + assertEquals(FOUR_CORES, size.executor()); + assertEquals(FOUR_CORES, size.driver()); + // The overhead is at least 384 MB, or what the job sets; a bare number is MiB; a disk as the job sets it. + Size small = SparkExecutors.sizeOf(Map.of("spark.executor.cores", "1", "spark.executor.memory", "2048", + "spark.emr-serverless.executor.disk", "50G")); + assertEquals(1, small.cores()); + assertEquals(2048, small.memoryMib()); + assertEquals(new Amount(1, 3, 50), small.executor()); + assertEquals(2, SparkExecutors.sizeOf(Map.of("spark.executor.memory", "1g", + "spark.executor.memoryOverhead", "1g")).executor().memoryGb()); + // Spark's own defaults when the job sets nothing: one core, 1 GB. + Size spark = SparkExecutors.sizeOf(Map.of()); + assertEquals(1, spark.cores()); + assertEquals(1024, spark.memoryMib()); + assertEquals(1, spark.driver().vcpus()); + } + + @Test + void emrServerlesssOverheadFactorCountsUnlessTheRolesOwnIsSet() { + // "spark.emr-serverless.memoryOverheadFactor | Sets the memory overhead to add to the driver and executor + // container memory." 14 GB and half of it are 21 GB. + Map settings = new HashMap<>(IMAGE_DEFAULTS); + settings.put("spark.emr-serverless.memoryOverheadFactor", "0.5"); + assertEquals(21, SparkExecutors.sizeOf(settings).executor().memoryGb()); + assertEquals(21, SparkExecutors.sizeOf(settings).driver().memoryGb()); + + settings.put("spark.executor.memoryOverheadFactor", "0.25"); + settings.put("spark.driver.memoryOverhead", "2g"); + assertEquals(18, SparkExecutors.sizeOf(settings).executor().memoryGb()); + assertEquals(16, SparkExecutors.sizeOf(settings).driver().memoryGb()); + } + + @Test + void anApplicationsCapacityTakesAWorkerOnlyWhileItsLimitsHaveRoomForIt() { + // Beside the driver's 4 vCPUs, 16 GB and 20 GB of disk. + assertEquals(2, taken(new Executors(9, null, 12, 0, 0, null))); + assertEquals(1, taken(new Executors(9, null, 0, 40, 0, null))); + assertEquals(3, taken(new Executors(9, null, 0, 0, 80, null))); + assertEquals(0, taken(new Executors(9, null, 2, 0, 0, null))); + assertEquals(9, taken(new Executors(9, null, 0, 0, 0, null))); + } + + @Test + void theRunsOfAnApplicationShareItsMaximumCapacity() { + // Its capacity "is cumulative across all workers at any given point in time": 12 vCPUs, for two runs whose + // drivers and executors take 4 each. + Executors twelve = new Executors(9, null, 12, 0, 0, "application"); + driver.settings(IMAGE_DEFAULTS); + driver.target(3); + SparkExecutors first = new SparkExecutors(twelve, driver, containers, capacity, nanos::get); + first.follow(); + FakeContainers others = new FakeContainers(); + SparkExecutors second = new SparkExecutors(twelve, driver, others, capacity, nanos::get); + second.follow(); + + assertEquals(List.of(1, 2), containers.started); + // Its driver runs already, so it is held, beyond the capacity, and none of its executors starts. + assertEquals(List.of(), others.started); + assertEquals(new Amount(16, 64, 80), capacity.held()); + + // Once the first run has ended, the second has room for two. + first.removeAll(); + advance(SparkExecutors.LOOK_INTERVAL); + second.follow(); + assertEquals(List.of(1, 2), others.started); + assertEquals(new Amount(12, 48, 60), capacity.held()); + second.removeAll(); + assertEquals(Amount.NONE, capacity.held()); + } + + @Test + void nothingStartsUntilTheDriversUiAnswers() { + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + + executors.follow(); + + assertEquals(List.of(), containers.started); + } + + @Test + void asManyExecutorsStartAsDynamicAllocationWantsUpToTheRunsLimit() { + driver.settings(IMAGE_DEFAULTS); + driver.target(3); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + + executors.follow(); + + assertEquals(List.of(1, 2), containers.started); + assertEquals(new Size(4, 14 * 1024, FOUR_CORES, FOUR_CORES), containers.sizes.getFirst()); + // Still wanted, none more. + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + assertEquals(List.of(1, 2), containers.started); + assertEquals(2, executors.workers().size()); + } + + @Test + void noExecutorStartsThatWouldTakeTheApplicationPastItsMaximumCapacity() { + driver.settings(IMAGE_DEFAULTS); + driver.target(5); + SparkExecutors executors = new SparkExecutors(new Executors(9, null, 12, 0, 0, null), driver, + containers, capacity, nanos::get); + + executors.follow(); + + // 4 vCPUs for the driver's worker and 4 for each executor's, of 12. + assertEquals(List.of(1, 2), containers.started); + } + + @Test + void anIdleExecutorAboveWhatSparkWantsGoesAndABusyOneStays() { + driver.settings(IMAGE_DEFAULTS); + driver.target(2); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + executors.follow(); + + driver.target(1); + driver.coresUsed(Map.of("10.0.0.1", 4, "10.0.0.2", 0)); + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + + assertEquals(List.of("executor-2"), containers.removed); + assertEquals(List.of(new Worker("executor-1", "10.0.0.1")), executors.workers()); + // Its worker's share of the capacity goes with it: the driver's and one executor's are left. + assertEquals(new Amount(8, 32, 40), capacity.held()); + // Busy, it stays above the target until it is idle. + driver.target(0); + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + assertEquals(List.of("executor-2"), containers.removed); + } + + @Test + void anExecutorWhoseContainerEndedIsStartedAgainWhileSparkStillWantsIt() { + driver.settings(IMAGE_DEFAULTS); + driver.target(2); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + executors.follow(); + + containers.ended.add("executor-1"); + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + + assertEquals(List.of(1, 2, 3), containers.started); + assertEquals(List.of("executor-2", "executor-3"), + executors.workers().stream().map(Worker::containerId).toList()); + // The container that ended goes from the daemon too, and its worker's share of the capacity with it. + assertEquals(List.of("executor-1"), containers.removed); + assertEquals(new Amount(12, 48, 60), capacity.held()); + } + + @Test + void anEndedExecutorsContainerDockerWillNotRemoveYetIsRemovedWithTheRun() { + driver.settings(IMAGE_DEFAULTS); + driver.target(1); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + executors.follow(); + containers.ended.add("executor-1"); + containers.refused.add("executor-1"); + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + + containers.refused.clear(); + executors.removeAll(); + + assertEquals(List.of("executor-2", "executor-1"), containers.removed); + } + + @Test + void anExecutorWhoseContainerCouldNotStartGivesItsShareBackAndIsStartedAtTheNextLook() { + driver.settings(IMAGE_DEFAULTS); + driver.target(1); + containers.failNextStart = true; + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + + executors.follow(); + assertTrue(executors.workers().isEmpty()); + assertEquals(FOUR_CORES, capacity.held()); + + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + assertEquals(1, executors.workers().size()); + } + + @Test + void withoutDynamicAllocationItsExecutorInstancesStart() { + Map fixed = new HashMap<>(IMAGE_DEFAULTS); + fixed.put("spark.dynamicAllocation.enabled", "false"); + fixed.put("spark.executor.instances", "1"); + driver.settings(fixed); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + + executors.follow(); + + assertEquals(List.of(1), containers.started); + } + + @Test + void aDriverWhoseUiNeverAnswersGetsOneExecutorThatFitsAnySettings() { + driver.masterHasApplication = true; + // Its sizes unknown, the one executor counts for nothing against a capacity smaller than what it offers. + SparkExecutors executors = new SparkExecutors(new Executors(2, null, 4, 8, 20, null), driver, containers, + capacity, nanos::get); + executors.follow(); + advance(SparkExecutors.UI_SILENCE.minus(Duration.ofSeconds(1))); + executors.follow(); + assertEquals(List.of(), containers.started); + + advance(SparkExecutors.LOOK_INTERVAL); + executors.follow(); + + assertEquals(List.of(1), containers.started); + assertEquals(SparkExecutors.BLIND_SIZE, containers.sizes.getFirst()); + assertEquals(Amount.NONE, capacity.held()); + } + + @Test + void theDriverIsLookedAtOnceALookInterval() { + driver.settings(IMAGE_DEFAULTS); + driver.target(1); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + executors.follow(); + int asked = driver.asked; + + executors.follow(); + + assertEquals(asked, driver.asked); + } + + @Test + void everyExecutorGoesWithTheRun() { + driver.settings(IMAGE_DEFAULTS); + driver.target(2); + SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get); + executors.follow(); + + executors.removeAll(); + + assertEquals(List.of("executor-1", "executor-2"), containers.removed); + assertTrue(executors.workers().isEmpty()); + assertEquals(Amount.NONE, capacity.held()); + } + + @Test + void sizesReadAsSparkReadsThem() { + assertEquals(14 * 1024, SparkExecutors.mebibytes("14G", 0)); + assertEquals(14 * 1024, SparkExecutors.mebibytes("14gb", 0)); + assertEquals(512, SparkExecutors.mebibytes("512m", 0)); + assertEquals(2048, SparkExecutors.mebibytes("2048", 0)); + assertEquals(7, SparkExecutors.mebibytes("not a size", 7)); + assertEquals(20, SparkExecutors.gigabytes(null)); + assertEquals(200, SparkExecutors.gigabytes("200G")); + } + + @Test + void sparkSubmitsOptionsEndAtItsPrimaryResource() { + assertEquals(4, SparkExecutors.optionCount(List.of("--conf", "a=1", "--verbose", "--conf=b=2", + "s3://bucket/app.py", "--conf", "c=3"))); + assertEquals(6, SparkExecutors.optionCount(List.of("-c", "a=1", "--name", "-x", "--supervise", "-v", + "app.jar"))); + assertEquals(0, SparkExecutors.optionCount(List.of("app.jar", "--conf", "a=1"))); + assertEquals(2, SparkExecutors.optionCount(List.of("--conf", "a=1"))); + assertEquals(1, SparkExecutors.optionCount(List.of("--conf"))); + } + + @Test + void theDriversContainerStartsTheMasterBeforeSparkSubmitAndAWorkerOffersOneExecutor() { + // The master's address, the run's secret and the UI's kill links off come after the run's own options, which + // cannot replace them, and before its primary resource. + assertTrue(SparkExecutors.DRIVER_WRAPPER.contains("submit=$1; options=$2; shift 2\nexec \"$submit\"" + + " \"${@:1:$options}\" --master \"spark://$address:7077\" --conf \"spark.driver.host=$address\"" + + " --conf \"spark.authenticate.secret=$FLOCI_SPARK_SECRET\" --conf spark.ui.killEnabled=false" + + " \"${@:$((options + 1))}\"")); + assertTrue(SparkExecutors.DRIVER_WRAPPER.contains("SPARK_MASTER_OPTS=\"-Dspark.authenticate.secret=" + + "$FLOCI_SPARK_SECRET -Dspark.master.rest.enabled=false -Dspark.ui.killEnabled=false\"")); + assertTrue(SparkExecutors.WORKER_SCRIPT.contains("--cores \"$FLOCI_EXECUTOR_CORES\" --memory" + + " \"${FLOCI_EXECUTOR_MEMORY_MB}m\" --work-dir /tmp/floci-spark-work --host \"$address\"" + + " \"spark://$FLOCI_SPARK_MASTER:7077\"")); + } + + private void advance(Duration duration) { + nanos.addAndGet(duration.toNanos()); + } + + // How many 4-core 14G executors' workers a capacity holding such a driver's takes, of nine asked for. + private static int taken(Executors limits) { + Capacity capacity = new Capacity(); + capacity.hold(FOUR_CORES); + int taken = 0; + while (taken < 9 && capacity.take(FOUR_CORES, limits)) { + taken++; + } + return taken; + } + + /** A driver whose UI and master answer as a test sets them. */ + private static final class FakeDriver implements SparkExecutors.Driver { + private String environment; + private String metrics; + private String master = "{\"workers\": [], \"activeapps\": []}"; + private boolean masterHasApplication; + private int asked; + + void settings(Map settings) { + StringBuilder pairs = new StringBuilder(); + settings.forEach((key, value) -> pairs.append(pairs.isEmpty() ? "" : ",") + .append("[\"").append(key).append("\",\"").append(value).append("\"]")); + environment = "{\"sparkProperties\": [" + pairs + "]}"; + } + + void target(int executors) { + metrics = "{\"gauges\": {\"app-1.driver.ExecutorAllocationManager.executors.numberTargetExecutors\":" + + " {\"value\": " + executors + "}}}"; + } + + void coresUsed(Map byHost) { + StringBuilder workers = new StringBuilder(); + byHost.forEach((host, cores) -> workers.append(workers.isEmpty() ? "" : ",") + .append("{\"host\": \"").append(host).append("\", \"coresused\": ").append(cores).append("}")); + master = "{\"workers\": [" + workers + "], \"activeapps\": [{\"id\": \"app-1\"}]}"; + } + + @Override + public String get(int port, String path) { + asked++; + if (port == SparkExecutors.MASTER_UI_PORT) { + return masterHasApplication ? "{\"workers\": [], \"activeapps\": [{\"id\": \"app-1\"}]}" : master; + } + if (environment == null) { + return null; + } + return switch (path) { + case "/api/v1/applications" -> "[{\"id\": \"app-1\"}]"; + case "/api/v1/applications/app-1/environment" -> environment; + case "/metrics/json/" -> metrics; + default -> null; + }; + } + } + + /** Executors' containers, each at 10.0.0.n for the nth, which run until a test ends them. */ + private static final class FakeContainers implements SparkExecutors.Containers { + private final List started = new ArrayList<>(); + private final List sizes = new ArrayList<>(); + private final List removed = new ArrayList<>(); + private final Set ended = new HashSet<>(); + private final Set refused = new HashSet<>(); + private boolean failNextStart; + + @Override + public Worker start(int index, Size size) { + if (failNextStart) { + failNextStart = false; + throw new IllegalStateException("Docker refused to start it"); + } + started.add(index); + sizes.add(size); + return new Worker("executor-" + index, "10.0.0." + index); + } + + @Override + public boolean running(String containerId) { + return !ended.contains(containerId); + } + + @Override + public void remove(String containerId) { + if (refused.contains(containerId)) { + throw new IllegalStateException("Docker refused to remove it"); + } + removed.add(containerId); + } + } +} diff --git a/src/test/java/io/floci/aws/testing/ContainerDataPlaneProfile.java b/src/test/java/io/floci/aws/testing/ContainerDataPlaneProfile.java index 2f09507826..adabe3baee 100644 --- a/src/test/java/io/floci/aws/testing/ContainerDataPlaneProfile.java +++ b/src/test/java/io/floci/aws/testing/ContainerDataPlaneProfile.java @@ -19,15 +19,16 @@ import java.util.Map; * program the link-local IMDS endpoint into a cluster's container, for the node and for its pods. * {@code EksImdsDockerIntegrationTest} relies on them. *
  • {@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. - * {@code EmrDockerRunnerDockerIntegrationTest} relies on them.
  • + * run a cluster's steps and an EMR Serverless application'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 EmrDockerRunnerDockerIntegrationTest} relies on them. * * *

    Each override is inert for the other classes. An InfluxDB container only starts when a DB * instance is created, which the IMDS test never does. The IMDS settings only act when a cluster's * container starts, and the test defaults keep EKS mocked, so only {@code EksImdsDockerIntegrationTest}, * which configures the endpoint on its own container, reaches them. The metadata server it starts - * stays up for the Timestream test, on a port that test does not use. The EMR runner modes only act + * stays up for the Timestream test, on a port that test does not use. The EMR settings only act * when a cluster runs a step or an application runs a job, which neither of the other classes does. * *

    The ELBv2 data-plane classes stay on {@link RealElbV2DataPlaneProfile}: one of them, @@ -45,6 +46,7 @@ public class ContainerDataPlaneProfile implements QuarkusTestProfile { "floci.services.eks.imds", "true", "floci.services.eks.imds-pod-network", "true", "floci.services.emr.runner-mode", "docker", - "floci.services.emrserverless.runner-mode", "docker"); + "floci.services.emrserverless.runner-mode", "docker", + "floci.services.emrserverless.executor-containers", "2"); } }