mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(emr-serverless): run a Spark job's executors in their own containers (#8168)
EMR Serverless gives a Spark job's driver and each of its executors a worker of their own; a docker job run ran them all in one container, in Spark's local mode. With executor-containers above 0, the driver's container now runs Spark's standalone master beside the driver, and each executor runs in a container of its own, a standalone worker offering one executor's cores and memory. Floci follows the driver through its UI: an executor's size from its settings, and how many executors dynamic allocation wants from its metrics. It starts executor containers, or removes idle ones, to match: at most executor-containers at once, and none that would take the application past its maximumCapacity. They share a secret per run, run the Executor worker type's image, and go with the driver. executor-containers is 0 by default: then, or on the host's network, the executors run in the driver's container, as before.
This commit is contained in:
1 parent
9f9b116f73
commit
438e01a225
13 files changed
+1582
-57
No files matched your search
@@ -1180,6 +1180,16 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
Optional<String> 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 <em>this same</em> Floci left on the daemon (matched by the
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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<String> 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<JobRunRecord> store, EmrServerlessService applications,
|
||||
IamService iamService, RegionResolver regionResolver, RequestContext requestContext,
|
||||
ObjectMapper objectMapper, int runDurationSeconds, Clock clock,
|
||||
SparkJobRunner sparkRunner, Executor runExecutor,
|
||||
String imageTemplate, String hiveImageTemplate, String dockerNetwork,
|
||||
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<String, String> 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
|
||||
|
||||
@@ -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<String, SparkExecutors.Capacity> 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<SessionCreds> 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<Archive> archives = archives(job);
|
||||
List<String> 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<String> 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<String> sparkSubmit = job.sparkLog4j2().isEmpty() && job.storage() == null
|
||||
? List.of(SPARK_SUBMIT) : List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci", SPARK_SUBMIT);
|
||||
List<String> sparkSubmit = new ArrayList<>();
|
||||
if (!job.sparkLog4j2().isEmpty() || job.storage() != null) {
|
||||
sparkSubmit.addAll(List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci"));
|
||||
}
|
||||
List<String> 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<String> awsEnvironment,
|
||||
Map<String, String> driverLabels) {
|
||||
Map<String, String> 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<String> sparkSubmitArguments(Job job, String flociEndpoint, List<String> executorEnvironment) {
|
||||
List<String> arguments = new ArrayList<>(List.of("--master", master(job)));
|
||||
List<String> 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())) {
|
||||
|
||||
@@ -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<String> 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<Worker> 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<String> 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<Worker> 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<Worker> 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<String> 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<String, String> 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<String, String> 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<String, String> 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<String, JsonNode> 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<String, Integer> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> environment,
|
||||
List<String> archives, Storage storage, Map<String, String> coreSite,
|
||||
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
|
||||
Map<String, String> hadoopEnvironment) {
|
||||
Map<String, String> 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) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user