diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 758ca4a906..7fb983487d 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -145,6 +145,20 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo * **StartJobRun** keeps the run's `flexExecution` ("The Amazon EMR Serverless Flex settings for the job run"), which `GetJobRun`, `ListJobRuns` and `ListJobRunAttempts` give back; an `enabled` that is not a boolean is refused with `SerializationException`. Floci has no Flex capacity to run it on, so it changes nothing else. +* **Resource utilization**: an ended Spark run gives its `totalResourceUtilization`, "The aggregate vCPU, + memory, and storage resources used from the time the job starts to execute, until the time the job + terminates, rounded up to the nearest second", and its `billedResourceUtilization`, which includes "a 1-minute + minimum usage for workers, plus additional storage over 20 GB per worker". Floci reckons both from the workers + the run asks for, its driver and the executors it starts with, sized as the user guide's "Supported worker + configurations" size them: a worker has the vCPUs its `cores` ask for, and memory for its Spark memory and that + memory's overhead, "10% of container memory, with a minimum of 384 MB", rounded up to the sizes its vCPUs allow. + Unset, a worker has 4 vCPUs, 14G of Spark memory and 20G of disk, and a run starts 3 executors, as the "Spark job + properties" give them, so a default worker is 4 vCPUs, 16 GB and 20 GB; `spark-submit`'s `--driver-cores`, + `--driver-memory`, `--executor-cores`, `--executor-memory` and `--num-executors` set over what `--conf` sets, as + Spark takes them. Its driver's worker counts for the whole attempt. Where its executors have containers of their + own (see **Executors**), each executor's worker counts for the time its container ran, as they come and go with + Spark's target; otherwise the executors it starts with count for the whole attempt. Each attempt gives its own, + and one that never started used nothing. A Hive run gives none, its Tez tasks coming and going with its query. * **StopApplication** refuses an application with a run that has not finished, a `STREAMING` run or a `CANCELLING` one included, as the API reference says "All scheduled and running jobs must be completed or cancelled before stopping an application." It answers `ValidationException`, the one @@ -494,6 +508,6 @@ application's `imageConfiguration`; a `TezTask` image is not used, as Tez's task directory; Spark alone unpacks the others, into its own files folder. Floci reads an archive itself, whatever the execution role may read, though Spark's own read of it uses the role's credentials. * **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. An image's digest is resolved as the application starts where its `applicationLevelDigestResolution` is true, or left unset on EMR 7.13 or earlier, as the user guide's table has it, and AWS's "Custom images are resolved to a digest at application start; that digest is used for all jobs until the application restarts": the application's image configuration gets the digest of the image in Floci's ECR as its `resolvedImageDigest`, and each run pulls the image by it until the application starts again; a stopped application reports none. An image outside ECR, one in another account's repository (Floci does not check that the application may pull it), or one Floci's ECR does not hold or cannot read without Docker, has no digest to read and is resolved for each run, as every image is from 7.14 on; any other answer from Floci's ECR fails `StartApplication` with `InternalServerException`; such a run's digest comes from its attempt's own pull (see **Image** above), and a job run's image configurations carry no `applicationLevelDigestResolution`. -* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, the account's limit of 2000 `QUEUED` runs, `totalResourceUtilization` and `billedResourceUtilization` (of a job run or a session), and Flex capacity (`flexExecution` is kept and given back only). +* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, the account's limit of 2000 `QUEUED` runs, a session's `totalResourceUtilization` and `billedResourceUtilization`, and a Hive run's (see **Resource utilization**), and Flex capacity (`flexExecution` is kept and given back only). * **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background. * **Sessions in the `immediate` mode run nothing**: a session is kept with its lifecycle, but no Spark driver runs for it, and a Spark Connect call to it is refused; the `docker` mode runs one (see [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server)). 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 be65bfa1a5..3b06af7578 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -26,6 +26,7 @@ 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.RunWorkers; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; import io.floci.aws.services.emrserverless.model.Session; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; @@ -676,6 +677,7 @@ public class EmrServerlessJobRunService implements Resettable { record.setClientToken(request.getClientToken()); record.setRequest(original); record.setApplicationType(app.getType()); + record.setWorkers(workers(app, run)); record.setContainerRun(sparkRunner != null); keepDriverLogs(record, app); store.put(jobRunId, record); @@ -1223,6 +1225,17 @@ public class EmrServerlessJobRunService implements Resettable { }); } + // How long each of a run's executors' workers ran, for its attempt's resource utilization. + private synchronized void keepExecutorLifetimes(String jobRunId, long launchedIn, List lifetimes) { + if (launchedIn != generation) { + return; + } + store.get(jobRunId).ifPresent(record -> { + record.setExecutorLifetimes(lifetimes.stream().map(Duration::toMillis).toList()); + store.put(jobRunId, record); + }); + } + // A run past its timeout is CANCELLING while its driver is stopped: "the job run has timed out". private synchronized void driverTimedOut(String jobRunId, long launchedIn) { if (launchedIn != generation) { @@ -1318,7 +1331,8 @@ public class EmrServerlessJobRunService implements Resettable { JobRun run = record.getJobRun(); JobRun failed = objectMapper.convertValue(run, JobRun.class); failed.setStateDetails(details); - end(failed, STATE_FAILED, now); + end(record, failed, STATE_FAILED, now); + record.setExecutorLifetimes(null); record.getEarlierAttempts().add(failed); run.setAttempt(run.getAttempt() + 1); run.setAttemptCreatedAt(now); @@ -1329,6 +1343,8 @@ public class EmrServerlessJobRunService implements Resettable { run.setStartedAt(null); run.setEndedAt(null); run.setTotalExecutionDurationSeconds(null); + run.setTotalResourceUtilization(null); + run.setBilledResourceUtilization(null); applyImages(run, app); keepDriverLogs(record, app); store.put(run.getJobRunId(), record); @@ -1337,6 +1353,16 @@ public class EmrServerlessJobRunService implements Resettable { launch(record, app); } + /** + * The workers a Spark run asks for ({@link EmrServerlessWorkers}), from its properties as {@code spark-submit} gets + * them; none for a Hive run, whose Tez tasks come and go with its query. + */ + private static RunWorkers workers(Application app, JobRun run) { + JobDriver.SparkSubmit sparkSubmit = run.getJobDriver() != null ? run.getJobDriver().getSparkSubmit() : null; + return sparkSubmit != null ? EmrServerlessWorkers.plan(sparkProperties(sparkDefaults(app, run), sparkSubmit), + sparkSubmit.getSparkSubmitParameters()) : null; + } + /** The {@code spark-defaults} properties for a run, as {@link #classificationProperties} merges them. */ private static Map sparkDefaults(Application app, JobRun run) { return classificationProperties(app, run, SPARK_DEFAULTS); @@ -1507,7 +1533,7 @@ public class EmrServerlessJobRunService implements Resettable { queued.add(record); } else if (record.isContainerRun() && !executing.contains(run.getJobRunId())) { run.setStateDetails(INTERRUPTED); - end(run, STATE_FAILED, now); + end(record, run, STATE_FAILED, now); replay.changed.add(record); } else { replay.running(record); @@ -1606,11 +1632,11 @@ public class EmrServerlessJobRunService implements Resettable { // No source gives AWS's stateDetails for it; the wording is Floci's. run.setStateDetails("Job run timed out after " + limits.queueTimeout().toMinutes() + " minutes in the queue."); - end(run, STATE_CANCELLED, timesOutAt); + end(head, run, STATE_CANCELLED, timesOutAt); changed.add(head); } else if (endsAt != null) { timed.poll(); - end(first.record().getJobRun(), first.ending().state(), endsAt); + end(first.record(), first.record().getJobRun(), first.ending().state(), endsAt); changed.add(first.record()); startQueued(endsAt); } else if (!startQueued(now)) { @@ -1643,7 +1669,7 @@ public class EmrServerlessJobRunService implements Resettable { running(record); } else if (!driverIsTheApplications(run, app)) { run.setStateDetails(DRIVER_NOT_THE_APPLICATIONS); - end(run, STATE_FAILED, at); + end(record, run, STATE_FAILED, at); } else { run.setState(STATE_SCHEDULED); launched.add(record); @@ -1701,11 +1727,12 @@ public class EmrServerlessJobRunService implements Resettable { } private void finish(JobRunRecord record, String state, Instant endedAt) { - end(record.getJobRun(), state, endedAt); + end(record, record.getJobRun(), state, endedAt); store.put(record.getJobRun().getJobRunId(), record); } - private static void end(JobRun run, String state, Instant endedAt) { + // Ends an attempt of a run, as of endedAt, with what its workers used. + private void end(JobRunRecord record, JobRun run, String state, Instant endedAt) { run.setState(state); run.setEndedAt(endedAt); run.setUpdatedAt(endedAt); @@ -1713,6 +1740,19 @@ public class EmrServerlessJobRunService implements Resettable { // A container run cancelled or failed before its driver ran never started. run.setTotalExecutionDurationSeconds(run.getStartedAt() != null ? (int) Duration.between(run.getStartedAt(), endedAt).toSeconds() : 0); + EmrServerlessWorkers.account(run, workersOf(record), record.getExecutorLifetimes()); + } + + /** + * The workers a run asked for: as it was admitted, or, for a Spark run stored before Floci kept them, from its + * application and request now, while its application is live. + */ + private RunWorkers workersOf(JobRunRecord record) { + JobRun run = record.getJobRun(); + if (record.getWorkers() == null && run.getJobDriver() != null && run.getJobDriver().getSparkSubmit() != null) { + applications.findLive(run.getApplicationId()).ifPresent(app -> record.setWorkers(workers(app, run))); + } + return record.getWorkers(); } // Every attempt of a run, oldest first: the earlier ones, then the latest. @@ -1945,5 +1985,11 @@ public class EmrServerlessJobRunService implements Resettable { return !RequestScopes.callAs(job.accountId(), job.region(), () -> stillGoing(job.runId(), launchedIn)); } + + @Override + public void executorsRan(List lifetimes) { + RequestScopes.runAs(job.accountId(), job.region(), + () -> keepExecutorLifetimes(job.runId(), launchedIn, lifetimes)); + } } } 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 ead5dcae45..a97cb02f90 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -725,6 +725,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo // application's capacity with them. if (executors != null) { executors.removeAll(); + progress.executorsRan(executors.lifetimes()); } if (capacity != null) { leaveCapacity(job.executors().application(), capacity); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessWorkers.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessWorkers.java new file mode 100644 index 0000000000..85f875e6f6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessWorkers.java @@ -0,0 +1,193 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.services.emrserverless.model.JobRun; +import io.floci.aws.services.emrserverless.model.RunWorkers; + +import java.time.Duration; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The workers a Spark job run asks for, sized as EMR Serverless sizes them, and the resources they use while it runs + * (EMR Serverless User Guide, "Supported worker configurations" and "Spark job properties"). + * + *

A worker has the vCPUs its {@code cores} ask for, "1, 2, 4, 8, 16, or 32 vCPUs", and memory for its Spark memory + * and that memory's overhead, "10% of container memory, with a minimum of 384 MB", rounded up to the sizes its vCPUs + * allow, read as {@link SparkExecutors} reads them for an application's maximum capacity. Its disk is 20 GB to + * 200 GB. Unset, the cores are 4, the memory "For workers smaller than 32 vCPUs, 14G" and "For 32 vCPUs, 109G", the + * disk 20G, and the executors 3. With dynamic allocation on, as it is by default, a run starts with + * {@code spark.dynamicAllocation.initialExecutors}, or {@code spark.executor.instances} where that is larger, as + * Spark's own configuration reads, and no fewer than {@code minExecutors}. + */ +final class EmrServerlessWorkers { + + private static final List VCPUS = List.of(1, 2, 4, 8, 16, 32); + // The memory sizes of a 32-vCPU worker: "Three discrete values: 60 GB, 120 GB, or 244 GB". + private static final List LARGEST_WORKER_MEMORY = List.of(60L, 120L, 244L); + private static final int DEFAULT_CORES = 4; + private static final long DEFAULT_MEMORY_MIB = 14 * 1024; + private static final long LARGEST_WORKER_DEFAULT_MEMORY_MIB = 109 * 1024; + private static final int DEFAULT_EXECUTORS = 3; + private static final long MIN_DISK_GB = 20; + private static final long MAX_DISK_GB = 200; + // "You only pay for additional storage beyond 20 GB that you configure per worker." + private static final long INCLUDED_DISK_GB = 20; + // "The billed resources include a 1-minute minimum usage for workers" (the API reference's JobRun). + private static final long MINIMUM_BILLED_MILLIS = 60_000; + private static final double SECONDS_PER_HOUR = 3600; + /** + * spark-submit's options that size a run, and the property each sets, which "--conf" cannot override: Spark's + * option parser takes them over a property of the same setting. + */ + private static final Map SIZE_OPTIONS = Map.of("--driver-cores", "spark.driver.cores", + "--driver-memory", "spark.driver.memory", "--executor-cores", "spark.executor.cores", + "--executor-memory", "spark.executor.memory", "--num-executors", "spark.executor.instances"); + + private EmrServerlessWorkers() { + } + + /** + * The workers of a Spark run whose properties, its {@code spark-defaults} and {@code --conf} settings, these are, + * with what its {@code sparkSubmitParameters}' sizing options set over them. + */ + static RunWorkers plan(Map properties, String sparkSubmitParameters) { + Map settings = new HashMap<>(properties); + List parameters = EmrServerlessSparkRunner.splitParameters(sparkSubmitParameters); + for (int i = 0; i < parameters.size(); i++) { + String parameter = parameters.get(i); + int equals = parameter.indexOf('='); + String option = equals > 0 ? parameter.substring(0, equals) : parameter; + String property = SIZE_OPTIONS.get(option); + if (property != null && equals > 0) { + settings.put(property, parameter.substring(equals + 1)); + } else if (property != null && i + 1 < parameters.size()) { + settings.put(property, parameters.get(++i)); + } + } + int driverVcpu = vcpus(settings.get("spark.driver.cores")); + int executorVcpu = vcpus(settings.get("spark.executor.cores")); + return new RunWorkers(driverVcpu, memoryGb(settings, "spark.driver", driverVcpu), + diskGb(settings.get("spark.emr-serverless.driver.disk")), executorVcpu, + memoryGb(settings, "spark.executor", executorVcpu), + diskGb(settings.get("spark.emr-serverless.executor.disk")), executors(settings)); + } + + /** + * Sets an ended attempt's resource utilization from its {@code workers}: "The aggregate vCPU, memory, and storage + * resources used from the time the job starts to execute, until the time the job terminates, rounded up to the + * nearest second", and what was billed for them, which includes "a 1-minute minimum usage for workers, plus + * additional storage over 20 GB per worker". Its driver's worker runs for the whole attempt. Its executors' run + * for {@code executorLifetimes}, each worker's from its start to its end, where its executors had containers that + * came and went with Spark's target; else the executors it starts with run for the whole attempt. An attempt + * that never started used none. Nothing is set without workers, as for a Hive run. + */ + static void account(JobRun run, RunWorkers workers, List executorLifetimes) { + if (workers == null) { + return; + } + boolean started = run.getStartedAt() != null && run.getEndedAt() != null; + long millis = started ? Duration.between(run.getStartedAt(), run.getEndedAt()).toMillis() : 0; + double driverSeconds = seconds(millis); + double driverBilled = started ? seconds(Math.max(millis, MINIMUM_BILLED_MILLIS)) : 0; + double executorSeconds; + double executorBilled; + if (executorLifetimes != null) { + executorSeconds = seconds(executorLifetimes.stream().mapToLong(Long::longValue).sum()); + executorBilled = seconds(executorLifetimes.stream() + .mapToLong(lifetime -> Math.max(lifetime, MINIMUM_BILLED_MILLIS)).sum()); + } else { + executorSeconds = (double) workers.getExecutors() * driverSeconds; + executorBilled = (double) workers.getExecutors() * driverBilled; + } + run.setTotalResourceUtilization(utilization(workers, driverSeconds, executorSeconds, + workers.getDriverDiskGb(), workers.getExecutorDiskGb())); + run.setBilledResourceUtilization(utilization(workers, driverBilled, executorBilled, + Math.max(0, workers.getDriverDiskGb() - INCLUDED_DISK_GB), + Math.max(0, workers.getExecutorDiskGb() - INCLUDED_DISK_GB))); + } + + // Milliseconds rounded up to whole seconds. + private static double seconds(long millis) { + return Math.ceilDiv(millis, 1000); + } + + private static Map utilization(RunWorkers workers, double driverSeconds, double executorSeconds, + long driverDiskGb, long executorDiskGb) { + Map utilization = new LinkedHashMap<>(); + utilization.put("vCPUHour", hours(workers.getDriverVcpu(), driverSeconds, workers.getExecutorVcpu(), + executorSeconds)); + utilization.put("memoryGBHour", hours(workers.getDriverMemoryGb(), driverSeconds, + workers.getExecutorMemoryGb(), executorSeconds)); + utilization.put("storageGBHour", hours(driverDiskGb, driverSeconds, executorDiskGb, executorSeconds)); + return utilization; + } + + private static double hours(long driverAmount, double driverSeconds, long executorAmount, double executorSeconds) { + return (driverAmount * driverSeconds + executorAmount * executorSeconds) / SECONDS_PER_HOUR; + } + + // The fewest vCPUs a worker can have for its cores, at most 32. + private static int vcpus(String cores) { + int asked = whole(cores, DEFAULT_CORES); + return VCPUS.stream().filter(vcpu -> vcpu >= asked).findFirst().orElse(VCPUS.getLast()); + } + + /** + * A worker's memory in GB: its Spark memory and that memory's overhead, rounded up to the sizes its vCPUs allow + * ("Minimum 8 GB, maximum 30 GB, in 1 GB increments" for 4 vCPUs, say). + */ + private static int memoryGb(Map settings, String role, int vcpu) { + long heap = SparkExecutors.mebibytes(settings.get(role + ".memory"), + vcpu == VCPUS.getLast() ? LARGEST_WORKER_DEFAULT_MEMORY_MIB : DEFAULT_MEMORY_MIB); + long needed = SparkExecutors.workerGb(heap, settings, role); + if (vcpu == VCPUS.getLast()) { + return LARGEST_WORKER_MEMORY.stream().filter(size -> size >= needed).findFirst() + .orElse(LARGEST_WORKER_MEMORY.getLast()).intValue(); + } + long min = 2L * vcpu; + long max = switch (vcpu) { + case 1 -> 8; + case 2 -> 16; + case 4 -> 30; + case 8 -> 60; + default -> 120; + }; + long step = vcpu <= 4 ? 1 : vcpu / 2; + long steps = Math.ceilDiv(Math.max(0, Math.min(needed, max) - min), step); + return (int) Math.min(max, min + steps * step); + } + + // A worker's disk in GB, 20 to 200. + private static int diskGb(String disk) { + return (int) Math.max(MIN_DISK_GB, Math.min(MAX_DISK_GB, SparkExecutors.gigabytes(disk))); + } + + /** + * The executors a run starts with: {@code spark.executor.instances} without dynamic allocation; with it, its + * {@code initialExecutors}, "If --num-executors (or spark.executor.instances) is set and larger than this value, + * it will be used as the initial number of executors" (Spark's configuration), no fewer than {@code minExecutors} + * and no more than {@code maxExecutors}. + */ + private static int executors(Map settings) { + int instances = whole(settings.get("spark.executor.instances"), DEFAULT_EXECUTORS); + if ("false".equalsIgnoreCase(settings.get("spark.dynamicAllocation.enabled"))) { + return instances; + } + int initial = Math.max(whole(settings.get("spark.dynamicAllocation.initialExecutors"), DEFAULT_EXECUTORS), + whole(settings.get("spark.dynamicAllocation.minExecutors"), 0)); + if (settings.containsKey("spark.executor.instances")) { + initial = Math.max(initial, instances); + } + return Math.min(initial, whole(settings.get("spark.dynamicAllocation.maxExecutors"), initial)); + } + + private static int whole(String value, int fallback) { + try { + return value != null ? Math.max(0, Integer.parseInt(value.trim())) : fallback; + } catch (NumberFormatException e) { + return fallback; + } + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java b/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java index 197e42c66f..dcdd6a4f9e 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkExecutors.java @@ -211,6 +211,9 @@ final class SparkExecutors { 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<>(); + // When each running executor's worker started, by its container, and how long each that has ended ran. + private final Map started = new HashMap<>(); + private final List lifetimes = new ArrayList<>(); private int nextIndex = 1; private boolean looked; private long nextLook; @@ -251,6 +254,7 @@ final class SparkExecutors { if (!containers.running(worker.containerId())) { each.remove(); capacity.release(size.executor()); + ended(worker.containerId()); remove(worker.containerId()); } } @@ -275,6 +279,7 @@ final class SparkExecutors { throw e; } workers.add(worker); + started.put(worker.containerId(), nanoTime.getAsLong()); } if (workers.size() > wanted) { removeIdle(workers.size() - wanted); @@ -284,10 +289,27 @@ final class SparkExecutors { } } + /** + * How long each executor's worker ran, from its start to its removal, for those that have ended: every one, once + * {@link #removeAll} has run. + */ + List lifetimes() { + return List.copyOf(lifetimes); + } + + // An executor's worker has ended: how long it ran is kept. + private void ended(String containerId) { + Long since = started.remove(containerId); + if (since != null) { + lifetimes.add(Duration.ofNanos(Math.max(0, nanoTime.getAsLong() - since))); + } + } + /** 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()); + ended(worker.containerId()); remove(worker.containerId()); } workers.clear(); @@ -376,12 +398,12 @@ final class SparkExecutors { // 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) { + 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; + return Math.ceilDiv(heapMib > Long.MAX_VALUE - overheadMib ? Long.MAX_VALUE : heapMib + overheadMib, 1024); } private static double fraction(String value) { @@ -432,6 +454,7 @@ final class SparkExecutors { Worker worker = workers.get(i); if (Integer.valueOf(0).equals(coresUsed.get(worker.address()))) { containers.remove(worker.containerId()); + ended(worker.containerId()); workers.remove(i); capacity.release(size.executor()); count--; @@ -458,24 +481,32 @@ final class SparkExecutors { } } - // A size as Spark takes it, "14G" or "1024m", in MiB, a bare number being MiB, as spark.executor.memory has it. + /** + * A size as Spark takes it, "14G" or "1024m", in MiB, a bare number being MiB, as spark.executor.memory has it; + * {@code otherwise} for one that is not a size, or too large for a long. + */ 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; - }; + try { + long amount = Long.parseLong(size.group(1)); + return switch (size.group(2).toLowerCase(Locale.ROOT)) { + case "k" -> Math.max(1, amount / 1024); + case "g" -> Math.multiplyExact(amount, 1024L); + case "t" -> Math.multiplyExact(amount, 1024L * 1024); + case "p" -> Math.multiplyExact(amount, 1024L * 1024 * 1024); + default -> amount; + }; + } catch (NumberFormatException | ArithmeticException e) { + return otherwise; + } } // 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; + return value != null ? Math.max(1, Math.ceilDiv(mebibytes(value, DEFAULT_DISK_GB * 1024), 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 9286fad76b..ab26ec78d8 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -96,6 +96,13 @@ public interface SparkJobRunner { * that runs is stopped. */ boolean cancelled(); + + /** + * How long each of the run's executors' workers ran, from its start to its end, where its executors had + * containers of their own, told as the run ends. + */ + default void executorsRan(List lifetimes) { + } } /** What a run's container runs as: its driver, or one of its executors. */ diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/JobRun.java b/src/main/java/io/floci/aws/services/emrserverless/model/JobRun.java index 15efde0e8b..25c930e57a 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/JobRun.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/JobRun.java @@ -35,6 +35,9 @@ public class JobRun { private Map retryPolicy; // StartJobRun's flexExecution as sent; null where it gave none. private Map flexExecution; + // The ended attempt's TotalResourceUtilization and billed ResourceUtilization; null until it ends. + private Map totalResourceUtilization; + private Map billedResourceUtilization; private Integer attempt; @JsonFormat(shape = JsonFormat.Shape.NUMBER) private Instant attemptCreatedAt; @@ -92,6 +95,16 @@ public class JobRun { public Map getFlexExecution() { return flexExecution; } public void setFlexExecution(Map flexExecution) { this.flexExecution = flexExecution; } + + public Map getTotalResourceUtilization() { return totalResourceUtilization; } + public void setTotalResourceUtilization(Map totalResourceUtilization) { + this.totalResourceUtilization = totalResourceUtilization; + } + + public Map getBilledResourceUtilization() { return billedResourceUtilization; } + public void setBilledResourceUtilization(Map billedResourceUtilization) { + this.billedResourceUtilization = billedResourceUtilization; + } public Integer getAttempt() { return attempt; } public void setAttempt(Integer attempt) { this.attempt = attempt; } public Instant getAttemptCreatedAt() { return attemptCreatedAt; } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java b/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java index 1fcf2c48e1..b5851e679a 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java @@ -16,7 +16,8 @@ import java.util.Map; * mode runs, whose state its container decides. A run retried after a failed attempt keeps each earlier * attempt as GetJobRun reports it for that attempt, oldest first; {@code jobRun} is the latest. Each attempt's * driver log destinations are kept as it was admitted, by attempt number. A container run cancelled with a grace - * period keeps when that period ends, until which its driver may run on to shut down by itself. + * period keeps when that period ends, until which its driver may run on to shut down by itself. A Spark run keeps + * the workers it asked for as it was admitted, which each attempt's resource utilization is reckoned from. */ @RegisterForReflection public class JobRunRecord { @@ -30,6 +31,9 @@ public class JobRunRecord { private List earlierAttempts = new ArrayList<>(); private Map driverLogs = new LinkedHashMap<>(); private Instant shutdownDeadline; + private RunWorkers workers; + // How long, in milliseconds, each executor's worker of its latest attempt ran, where they had containers. + private List executorLifetimes; public JobRun getJobRun() { return jobRun; } public void setJobRun(JobRun jobRun) { this.jobRun = jobRun; } @@ -49,4 +53,8 @@ public class JobRunRecord { public void setDriverLogs(Map driverLogs) { this.driverLogs = driverLogs; } public Instant getShutdownDeadline() { return shutdownDeadline; } public void setShutdownDeadline(Instant shutdownDeadline) { this.shutdownDeadline = shutdownDeadline; } + public RunWorkers getWorkers() { return workers; } + public void setWorkers(RunWorkers workers) { this.workers = workers; } + public List getExecutorLifetimes() { return executorLifetimes; } + public void setExecutorLifetimes(List executorLifetimes) { this.executorLifetimes = executorLifetimes; } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/RunWorkers.java b/src/main/java/io/floci/aws/services/emrserverless/model/RunWorkers.java new file mode 100644 index 0000000000..8042797019 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/RunWorkers.java @@ -0,0 +1,47 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The workers a Spark job run asks for, as EMR Serverless sizes them: its driver and each of its executors, in vCPUs + * and in GB of memory and of disk, and how many executors it starts with. A run's resource utilization is reckoned + * from them. + */ +@RegisterForReflection +public class RunWorkers { + private int driverVcpu; + private int driverMemoryGb; + private int driverDiskGb; + private int executorVcpu; + private int executorMemoryGb; + private int executorDiskGb; + private int executors; + + public RunWorkers() {} + + public RunWorkers(int driverVcpu, int driverMemoryGb, int driverDiskGb, int executorVcpu, int executorMemoryGb, + int executorDiskGb, int executors) { + this.driverVcpu = driverVcpu; + this.driverMemoryGb = driverMemoryGb; + this.driverDiskGb = driverDiskGb; + this.executorVcpu = executorVcpu; + this.executorMemoryGb = executorMemoryGb; + this.executorDiskGb = executorDiskGb; + this.executors = executors; + } + + public int getDriverVcpu() { return driverVcpu; } + public void setDriverVcpu(int driverVcpu) { this.driverVcpu = driverVcpu; } + public int getDriverMemoryGb() { return driverMemoryGb; } + public void setDriverMemoryGb(int driverMemoryGb) { this.driverMemoryGb = driverMemoryGb; } + public int getDriverDiskGb() { return driverDiskGb; } + public void setDriverDiskGb(int driverDiskGb) { this.driverDiskGb = driverDiskGb; } + public int getExecutorVcpu() { return executorVcpu; } + public void setExecutorVcpu(int executorVcpu) { this.executorVcpu = executorVcpu; } + public int getExecutorMemoryGb() { return executorMemoryGb; } + public void setExecutorMemoryGb(int executorMemoryGb) { this.executorMemoryGb = executorMemoryGb; } + public int getExecutorDiskGb() { return executorDiskGb; } + public void setExecutorDiskGb(int executorDiskGb) { this.executorDiskGb = executorDiskGb; } + public int getExecutors() { return executors; } + public void setExecutors(int executors) { this.executors = executors; } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java index ce240f30e3..e1c2d63fa3 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java @@ -768,4 +768,19 @@ class EmrServerlessJobRunIntegrationTest { givenReq().queryParam("shutdownGracePeriodInSeconds", 30).when().delete(run).then().statusCode(200); givenReq().when().get(run).then().statusCode(200).body("jobRun.state", equalTo("CANCELLED")); } + + @Test + void anEndedSparkRunGivesItsTotalAndBilledResourceUtilization() { + String applicationId = createApplication(""); + String jobRunId = startedRunId(applicationId, sparkRun(UUID.randomUUID().toString(), "")); + + // Ended as it started, it used nothing, and is billed a minute of its workers and none of their disk. + givenReq().when().get("/applications/" + applicationId + "/jobruns/" + jobRunId).then().statusCode(200) + .body("jobRun.state", equalTo("SUCCESS")) + .body("jobRun.totalResourceUtilization.keySet()", + containsInAnyOrder("vCPUHour", "memoryGBHour", "storageGBHour")) + .body("jobRun.totalResourceUtilization.vCPUHour", equalTo(0.0f)) + .body("jobRun.billedResourceUtilization.storageGBHour", equalTo(0.0f)) + .body("jobRun.billedResourceUtilization.memoryGBHour", greaterThan(1.0f)); + } } 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 e04e30d8e1..f26745e07e 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -1142,6 +1142,64 @@ class EmrServerlessJobRunServiceTest { assertEquals("SerializationException", refused.getErrorCode()); } + @Test + void anEndedSparkRunGivesItsResourceUtilizationAndAHiveRunNone() { + EmrServerlessJobRunService service = service(90); + StartJobRunRequest sized = request(null, null); + sized.getJobDriver().getSparkSubmit() + .setSparkSubmitParameters("--conf spark.dynamicAllocation.enabled=false" + + " --conf spark.executor.instances=1 --conf spark.executor.cores=2"); + String spark = service.startJobRun(applicationId, sized).getJobRunId(); + String hiveApplication = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE")) + .getApplicationId(); + String hive = service.startJobRun(hiveApplication, hiveRequest("s3://bucket/queries/report.sql", null, null)) + .getJobRunId(); + + assertNull(service.getJobRun(applicationId, spark, null).getTotalResourceUtilization(), + "a run still running has used nothing yet"); + clock.advance(Duration.ofSeconds(90)); + JobRun ended = service.getJobRun(applicationId, spark, null); + + // A default driver, 4 vCPUs, 16 GB and 20 GB, and one executor of 2 vCPUs, whose 14G and 1.4G of overhead + // round up to a 2-vCPU worker's largest 16 GB, for 90 seconds. + assertEquals("SUCCESS", ended.getState()); + assertEquals(Map.of("vCPUHour", 6 * 90 / 3600.0, "memoryGBHour", 32 * 90 / 3600.0, + "storageGBHour", 40 * 90 / 3600.0), ended.getTotalResourceUtilization()); + assertEquals(Map.of("vCPUHour", 6 * 90 / 3600.0, "memoryGBHour", 32 * 90 / 3600.0, "storageGBHour", 0.0), + ended.getBilledResourceUtilization()); + JobRun hiveRun = service.getJobRun(hiveApplication, hive, null); + assertEquals("SUCCESS", hiveRun.getState()); + assertNull(hiveRun.getTotalResourceUtilization()); + } + + @Test + void aRunWhoseExecutorsHadContainersCountsTheTimeEachRanAndOneStoredWithoutWorkersGetsThemAsItEnds() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner); + String measured = service.startJobRun(applicationId, request(null, null)).getJobRunId(); + runner.whileRunning = () -> clock.advance(Duration.ofSeconds(100)); + runner.executorLifetimes = List.of(Duration.ofSeconds(30), Duration.ofMillis(90_500)); + runNext(); + + // The driver for its attempt, a little over 100 seconds as the test's clock ticks, rounded up; the executors + // for 121 seconds between them, each billed a minute at least. + JobRun ended = service.getJobRun(applicationId, measured, null); + long driver = Math.ceilDiv(Duration.between(ended.getStartedAt(), ended.getEndedAt()).toMillis(), 1000); + assertEquals(101, driver); + assertEquals((4 * driver + 4 * 121) / 3600.0, ended.getTotalResourceUtilization().get("vCPUHour")); + assertEquals((4 * driver + 4 * 151) / 3600.0, ended.getBilledResourceUtilization().get("vCPUHour")); + + EmrServerlessJobRunService immediate = service(90); + String stored = immediate.startJobRun(applicationId, request(null, null)).getJobRunId(); + JobRunRecord record = store.get(stored).orElseThrow(); + record.setWorkers(null); + store.put(stored, record); + clock.advance(Duration.ofSeconds(90)); + + assertEquals(16 * 90 / 3600.0, + immediate.getJobRun(applicationId, stored, null).getTotalResourceUtilization().get("vCPUHour")); + } + @Test void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() { FakeRunner runner = new FakeRunner(); @@ -1853,6 +1911,9 @@ class EmrServerlessJobRunServiceTest { Outcome outcome = Outcome.exitedWith(0); Runnable whileRunning = () -> { }; Runnable whileTimingOut = () -> { }; + // How long its executors' workers ran, told as the run ends, as the Docker runner tells it for executors with + // containers of their own; null for none told. + List executorLifetimes; // The manifest digest each custom image resolves to, told before the driver starts as the Docker runner does, // and the executors' where their pull resolves another, as a push between the two pulls gives. final Map digests = new HashMap<>(); @@ -1882,6 +1943,9 @@ class EmrServerlessJobRunServiceTest { progress.timedOut(); whileTimingOut.run(); } + if (executorLifetimes != null) { + progress.executorsRan(executorLifetimes); + } return stopped.contains(job.runId()) ? Outcome.halted() : outcome; } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessWorkersTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessWorkersTest.java new file mode 100644 index 0000000000..9687c41095 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessWorkersTest.java @@ -0,0 +1,132 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.services.emrserverless.model.JobRun; +import io.floci.aws.services.emrserverless.model.RunWorkers; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class EmrServerlessWorkersTest { + + private static final Instant STARTED = Instant.parse("2026-11-22T00:00:00Z"); + + private static List sizes(RunWorkers workers) { + return List.of(workers.getDriverVcpu(), workers.getDriverMemoryGb(), workers.getDriverDiskGb(), + workers.getExecutorVcpu(), workers.getExecutorMemoryGb(), workers.getExecutorDiskGb(), + workers.getExecutors()); + } + + private static JobRun ran(long millis) { + JobRun run = new JobRun(); + run.setStartedAt(STARTED); + run.setEndedAt(STARTED.plusMillis(millis)); + return run; + } + + @Test + void anUnsetRunHasADefaultDriverAndThreeDefaultExecutors() { + // 14G of Spark memory and its 10% overhead come to 15.4 GB, which a 4-vCPU worker rounds up to 16. + assertEquals(List.of(4, 16, 20, 4, 16, 20, 3), sizes(EmrServerlessWorkers.plan(Map.of(), null))); + } + + @Test + void eachWorkerIsSizedToTheMemoryItsVcpusAllow() { + RunWorkers workers = EmrServerlessWorkers.plan(Map.of( + "spark.driver.cores", "2", "spark.driver.memory", "4g", + "spark.executor.cores", "8", "spark.executor.memory", "20480m", + "spark.emr-serverless.executor.disk", "50G"), null); + + // 4 GB and 384 MB of overhead round up to 5 GB; 20 GB and 2 GB to 24 GB, in 8 vCPUs' 4 GB steps. + assertEquals(List.of(2, 5, 20, 8, 24, 50, 3), sizes(workers)); + assertEquals(List.of(4, 12, 20, 32, 120, 200, 3), sizes(EmrServerlessWorkers.plan(Map.of( + "spark.driver.cores", "3", "spark.driver.memory", "8g", "spark.driver.memoryOverhead", "4096", + "spark.executor.cores", "32", "spark.emr-serverless.executor.disk", "500G"), null))); + } + + @Test + void theExecutorsARunStartsWithFollowItsDynamicAllocation() { + assertEquals(5, EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.enabled", "false", + "spark.executor.instances", "5"), null).getExecutors()); + assertEquals(6, EmrServerlessWorkers.plan(Map.of("spark.executor.instances", "6"), null).getExecutors()); + assertEquals(2, EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.initialExecutors", "1", + "spark.dynamicAllocation.minExecutors", "2"), null).getExecutors()); + assertEquals(1, EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.maxExecutors", "1"), null) + .getExecutors()); + } + + @Test + void anAttemptUsesItsWorkersForItsSecondsAndIsBilledAMinuteAtLeastAndStorageOver20Gb() { + RunWorkers defaults = EmrServerlessWorkers.plan(Map.of(), null); + JobRun ninetySeconds = ran(90_000); + EmrServerlessWorkers.account(ninetySeconds, defaults, null); + + // 16 vCPUs, 64 GB and 80 GB of disk for 90 seconds; none of the disk is over 20 GB a worker. + assertEquals(Map.of("vCPUHour", 0.4, "memoryGBHour", 1.6, "storageGBHour", 2.0), + ninetySeconds.getTotalResourceUtilization()); + assertEquals(Map.of("vCPUHour", 0.4, "memoryGBHour", 1.6, "storageGBHour", 0.0), + ninetySeconds.getBilledResourceUtilization()); + + RunWorkers bigDisks = EmrServerlessWorkers.plan(Map.of("spark.emr-serverless.executor.disk", "50g"), null); + JobRun brief = ran(35_400); + EmrServerlessWorkers.account(brief, bigDisks, null); + + // Rounded up to 36 seconds; billed for 60, and for 30 GB of each executor's disk. + assertEquals(16 * 36 / 3600.0, brief.getTotalResourceUtilization().get("vCPUHour")); + assertEquals(170 * 36 / 3600.0, brief.getTotalResourceUtilization().get("storageGBHour")); + assertEquals(16 * 60 / 3600.0, brief.getBilledResourceUtilization().get("vCPUHour")); + assertEquals(90 * 60 / 3600.0, brief.getBilledResourceUtilization().get("storageGBHour")); + } + + @Test + void anAttemptThatNeverStartedUsedNothingAndOneWithoutWorkersGivesNone() { + JobRun neverStarted = new JobRun(); + neverStarted.setEndedAt(STARTED); + EmrServerlessWorkers.account(neverStarted, EmrServerlessWorkers.plan(Map.of(), null), null); + assertEquals(Map.of("vCPUHour", 0.0, "memoryGBHour", 0.0, "storageGBHour", 0.0), + neverStarted.getBilledResourceUtilization()); + + JobRun hive = ran(60_000); + EmrServerlessWorkers.account(hive, null, null); + assertNull(hive.getTotalResourceUtilization()); + assertNull(hive.getBilledResourceUtilization()); + } + + @Test + void sparkSubmitsSizingOptionsWinOverTheSettingsTheySet() { + // The properties as spark-defaults and --conf give them, which the options then set over. + RunWorkers workers = EmrServerlessWorkers.plan(Map.of("spark.executor.memory", "4g", + "spark.executor.cores", "2", "spark.dynamicAllocation.enabled", "false"), + "--driver-cores 8 --driver-memory=20g --executor-memory 8g --num-executors=5 --class example.Main"); + + assertEquals(List.of(8, 24, 20, 2, 9, 20, 5), sizes(workers)); + } + + @Test + void settingsTooLargeForTheirTypesGiveTheLargestWorkersAndNoNegativeUse() { + RunWorkers huge = EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.enabled", "false", + "spark.executor.instances", String.valueOf(Integer.MAX_VALUE), + "spark.executor.memory", "99999999999999999999g", "spark.driver.memory", "9007199254740993p"), null); + JobRun run = ran(3_600_000); + EmrServerlessWorkers.account(run, huge, null); + + // The memory that does not read as a size takes the default; the executors are what was asked for. + assertEquals(List.of(4, 16, 20, 4, 16, 20, Integer.MAX_VALUE), sizes(huge)); + assertEquals(4.0 + 4.0 * Integer.MAX_VALUE, run.getTotalResourceUtilization().get("vCPUHour")); + } + + @Test + void executorsWhoseContainersCameAndWentAreCountedForTheTimeEachRan() { + RunWorkers defaults = EmrServerlessWorkers.plan(Map.of(), null); + JobRun run = ran(100_000); + EmrServerlessWorkers.account(run, defaults, List.of(30_000L, 90_500L)); + + // The driver for 100 seconds and the executors for 121 between them; billed a minute at least each. + assertEquals((4 * 100 + 4 * 121) / 3600.0, run.getTotalResourceUtilization().get("vCPUHour")); + assertEquals((4 * 100 + 4 * 151) / 3600.0, run.getBilledResourceUtilization().get("vCPUHour")); + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java b/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java index dccc2223e5..d318783220 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/SparkExecutorsTest.java @@ -287,6 +287,24 @@ class SparkExecutorsTest { assertEquals(Amount.NONE, capacity.held()); } + @Test + void eachExecutorsWorkerIsTimedFromItsStartToItsEnd() { + 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(); + advance(Duration.ofSeconds(10)); + executors.removeAll(); + + assertEquals(List.of(SparkExecutors.LOOK_INTERVAL, SparkExecutors.LOOK_INTERVAL.plusSeconds(10)), + executors.lifetimes()); + } + @Test void sizesReadAsSparkReadsThem() { assertEquals(14 * 1024, SparkExecutors.mebibytes("14G", 0)); @@ -294,6 +312,9 @@ class SparkExecutorsTest { assertEquals(512, SparkExecutors.mebibytes("512m", 0)); assertEquals(2048, SparkExecutors.mebibytes("2048", 0)); assertEquals(7, SparkExecutors.mebibytes("not a size", 7)); + // Too large for a long, as written or once in MiB. + assertEquals(7, SparkExecutors.mebibytes("99999999999999999999g", 7)); + assertEquals(7, SparkExecutors.mebibytes("9007199254740993p", 7)); assertEquals(20, SparkExecutors.gigabytes(null)); assertEquals(200, SparkExecutors.gigabytes("200G")); }