diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 98819dd8aa..e2c83791f6 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -62,13 +62,15 @@ another. `CreateApplication` stores every configuration `UpdateApplication` does, `runtimeConfiguration`, `monitoringConfiguration`, `schedulerConfiguration`, `diskEncryptionConfiguration`, `interactiveConfiguration`, `identityCenterConfiguration` and `jobLevelCostAllocationConfiguration` -among them, and `GetApplication` returns each as it was written. +among them, and `GetApplication` returns each as it was written, except for `schedulerConfiguration` (see +**Concurrency and queuing** under job runs). `UpdateApplication` answers with the updated application, as `GetApplication` reports it. `UpdateApplication` changes any setting of a `CREATED` or `STOPPED` application, and of a `STARTED` one its `maximumCapacity` and its custom images, `imageConfiguration` and `workerTypeSpecifications`, as the user guide's -"Updating Running Applications" describes. For every other setting the API reference's "An application has to be in +"Updating Running Applications" describes, and a `schedulerConfiguration` naming only `maxConcurrentRuns`, as its +"Job concurrency and queuing" page has it. For every other setting the API reference's "An application has to be in a stopped or created state in order to be updated" holds: a `STARTED` application's update naming one, even beside those or with its current value, is refused with `ValidationException`, "Application must be in a stopped or created state in order to be updated.", and so is an image change on an application with `initialCapacity` ("Custom image @@ -92,11 +94,29 @@ In the default `immediate` runner mode, job runs are metadata only: nothing exec the job run states and `GetJobRun`'s response shape, and settles when it is read. In the `docker` runner mode a Spark run executes; see [Running Spark job runs](#running-spark-job-runs). -* **Lifecycle**: a run is `RUNNING` from the moment it is submitted. With the default +* **Lifecycle**: a run is `RUNNING` from the moment it is submitted, or from the moment it leaves the queue + (see **Concurrency and queuing**). With the default `job-run-duration-seconds` of `0`, a `BATCH` run is `SUCCESS` as soon as it starts; a positive duration keeps it `RUNNING` that long. A run whose duration would pass its `executionTimeoutMinutes` (720 when not given, as AWS reports it) is `CANCELLED` at the timeout. A `STREAMING` run stays `RUNNING` until it is cancelled. +* **Concurrency and queuing**: as the user guide's "Job concurrency and queuing for an EMR Serverless + application" describes, at most `maxConcurrentRuns` of an application's batch and streaming runs run at once. + A run submitted beyond that is `QUEUED`, and the first queued run starts when one of them ends or is cancelled. + A run still queued `queueTimeoutMinutes` after it was submitted is `CANCELLED`, as the job run states give + a run that "has timed out" as a reason to be cancelled. Its `stateDetails` is Floci's wording, as no source + gives AWS's. A run that leaves the queue reports `queuedDurationMilliseconds`. A queued run is cancelled at + once, and keeps `StopApplication` from stopping the application. Queuing is "supported on Amazon EMR release + 7.0.0 and higher" and "enabled by default on Amazon EMR release 7.3.0 and higher", the AWS runtime for Apache + Spark's releases included. An application that sets no `schedulerConfiguration` queues only from 7.3.0, with + the defaults of 15 runs and 360 minutes. `maxConcurrentRuns` must be 1 to 1000 and `queueTimeoutMinutes` 15 + to 720, or the request is refused with `ValidationException`, in Floci's wording. Terraform's acceptance tests + record how AWS keeps the configuration. A member a request leaves out takes its default, and here keeps the + value already set where there is one. An empty object turns queuing off, on 7.3.0 and later too, and the + application then returns no `schedulerConfiguration`. Raising `maxConcurrentRuns` on a `STARTED` application + starts queued runs at once. With the default + `job-run-duration-seconds` of `0`, a `BATCH` run ends as it starts and never holds a slot, so only + `STREAMING` runs, or runs given a duration, wait. * **Auto-start**: a run submitted to a `CREATED` or `STOPPED` application starts the application, as `autoStartConfiguration.enabled` defaults to `true`. With auto-start turned off, the run is refused with `ValidationException` until the application is started. A run on a terminated @@ -313,7 +333,9 @@ worker of its own on EMR Serverless (see **Executors** below). the default, or on the host's network or another container's network namespace, where two runs' ports would meet, the executors run in the driver's container instead, in Spark's local mode. -* **States**: a run is `SCHEDULED` while its image is pulled and its container starts (the first run +* **States**: a run beyond its application's `maxConcurrentRuns` is `QUEUED` first, its container not started until + it leaves the queue (see **Concurrency and queuing** under job runs). A run is `SCHEDULED` while its image is + pulled and its container starts (the first run of a release pulls its image, 3.5 to 4.3 GB unpacked; a pull still downloading after [`floci.docker.image-pull-timeout-seconds`](../configuration/docker.md), five minutes by default, is tried again, three attempts in all, so on a slow connection raise it or run `docker pull` on the @@ -457,6 +479,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, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization` (of a job run or a session), and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once). +* **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 `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once). * **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/EmrServerlessController.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java index 9a3082663a..d45252eadf 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java @@ -112,7 +112,7 @@ public class EmrServerlessController { public UpdateApplicationResponse updateApplication(@PathParam("applicationId") String applicationId, UpdateApplicationRequest request) { UpdateApplicationResponse response = new UpdateApplicationResponse(); - response.setApplication(service.updateApplication(applicationId, request)); + response.setApplication(jobRuns.updateApplication(applicationId, request)); return response; } 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 4bf8e116f4..1dc543811a 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -29,6 +29,7 @@ import io.floci.aws.services.emrserverless.model.MaximumCapacity; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; import io.floci.aws.services.emrserverless.model.Session; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; +import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification; import io.floci.aws.services.iam.IamService; import jakarta.annotation.PreDestroy; @@ -42,13 +43,21 @@ import java.time.Instant; import java.time.OffsetDateTime; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Deque; +import java.util.HashMap; import java.util.HashSet; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -69,6 +78,9 @@ import java.util.regex.Pattern; * and FAILED otherwise. Cancelling it, or its execution timeout, makes it CANCELLING until the driver * is stopped, then CANCELLED. * + *

In either mode a run beyond its application's {@code maxConcurrentRuns} waits QUEUED until one of the + * application's runs ends, or until its queue timeout ({@link EmrServerlessScheduler}). + * *

Every public method is synchronized: admitting a run (look up its client token, then write * it), settling one and cancelling one each read and then write a run, and must not interleave. A * container run's changes come from the thread that runs it, under the same lock. @@ -84,6 +96,7 @@ public class EmrServerlessJobRunService implements Resettable { static final String STATE_FAILED = "FAILED"; static final String STATE_CANCELLING = "CANCELLING"; static final String STATE_CANCELLED = "CANCELLED"; + static final String STATE_QUEUED = "QUEUED"; private static final String MODE_BATCH = "BATCH"; private static final String MODE_STREAMING = "STREAMING"; private static final String RUNNER_DOCKER = "docker"; @@ -127,7 +140,7 @@ public class EmrServerlessJobRunService implements Resettable { private static final Set TERMINAL_STATES = Set.of(STATE_SUCCESS, STATE_FAILED, STATE_CANCELLED); private static final List STATES = List.of("SUBMITTED", "PENDING", "SCHEDULED", STATE_RUNNING, - STATE_SUCCESS, "FAILED", "CANCELLING", STATE_CANCELLED, "QUEUED"); + STATE_SUCCESS, "FAILED", "CANCELLING", STATE_CANCELLED, STATE_QUEUED); // JobRunStateSet holds at most 8 states. private static final int MAX_FILTER_STATES = 8; private static final List MODES = List.of(MODE_BATCH, MODE_STREAMING); @@ -184,6 +197,9 @@ public class EmrServerlessJobRunService implements Resettable { private long generation; // The latest sequence a run was given, nextSequence. private long lastSequence; + // Each account's run ids by application, so that settling one application reads its runs alone; built from the + // store the first time an account's are needed, kept as runs start, and dropped by a reset. + private final Map>> runIdsByApplication = new HashMap<>(); @Inject public EmrServerlessJobRunService(StorageFactory storageFactory, EmrServerlessService applications, @@ -296,10 +312,13 @@ public class EmrServerlessJobRunService implements Resettable { if (body.getTags() != null) { EmrServerlessService.validateTags(body.getTags()); } + List runs = settleApplication(applicationId, null); JobRunRecord record = applications.admit(applicationId, "a job run is submitted", app -> checkBatchTimeout(app, body), app -> { - JobRunRecord admitted = newRun(app, body, original); - if (sparkRunner != null) { + EmrServerlessScheduler.Limits limits = EmrServerlessScheduler.limits(app); + boolean queued = limits != null && active(runs).size() >= limits.maxConcurrentRuns(); + JobRunRecord admitted = newRun(app, body, original, queued); + if (sparkRunner != null && !queued) { launch(admitted, app); } return admitted; @@ -402,12 +421,11 @@ public class EmrServerlessJobRunService implements Resettable { throw SmithyValidationErrors.validationException(violations); } List matching = new ArrayList<>(); - for (JobRunRecord record : store.scan(key -> true)) { + for (JobRunRecord record : settleApplication(applicationId, null)) { JobRun run = record.getJobRun(); - if (!applicationId.equals(run.getApplicationId()) || !inRequestRegion(run)) { + if (!inRequestRegion(run)) { continue; } - settle(record); if ((states != null && !states.isEmpty() && !states.contains(run.getState())) || (createdAtAfter != null && !run.getCreatedAt().isAfter(createdAtAfter)) || (createdAtBefore != null && !run.getCreatedAt().isBefore(createdAtBefore)) @@ -435,10 +453,9 @@ public class EmrServerlessJobRunService implements Resettable { */ public synchronized void stopApplication(String applicationId) { applications.getApplication(applicationId); - for (JobRunRecord record : store.scan(key -> true)) { + for (JobRunRecord record : settleApplication(applicationId, null)) { JobRun run = record.getJobRun(); - if (applicationId.equals(run.getApplicationId()) && inRequestRegion(run) - && !isTerminal(settle(record).getJobRun())) { + if (inRequestRegion(run) && !isTerminal(run)) { throw new AwsException("ValidationException", "All scheduled and running jobs must be completed " + "or cancelled before stopping an application.", 400); } @@ -456,6 +473,14 @@ public class EmrServerlessJobRunService implements Resettable { if (isTerminal(record.getJobRun())) { throw new AwsException("ValidationException", "Job run is not in a cancellable state", 400); } + Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS); + if (STATE_QUEUED.equals(record.getJobRun().getState())) { + // Nothing runs it yet, and it holds no running slot. + leaveQueue(record.getJobRun(), now); + finish(record, STATE_CANCELLED, now); + LOG.infov("Cancelled queued EMR Serverless job run {0} on application {1}", jobRunId, applicationId); + return record.getJobRun(); + } if (record.isContainerRun()) { JobRun run = record.getJobRun(); if (!STATE_CANCELLING.equals(run.getState())) { @@ -465,11 +490,24 @@ public class EmrServerlessJobRunService implements Resettable { } return run; } - finish(record, STATE_CANCELLED, clock.instant().truncatedTo(ChronoUnit.MILLIS)); + finish(record, STATE_CANCELLED, now); LOG.infov("Cancelled EMR Serverless job run {0} on application {1}", jobRunId, applicationId); + // Its running slot goes to the first queued run now. + settleApplication(applicationId, record); return record.getJobRun(); } + /** + * Updates the application, as {@link EmrServerlessService#updateApplication} does, with its runs brought up to the + * moment first under the limits they had, so that a higher {@code maxConcurrentRuns} starts queued runs from now. + */ + public synchronized Application updateApplication(String applicationId, UpdateApplicationRequest request) { + settleApplication(applicationId, null); + Application app = applications.updateApplication(applicationId, request); + settleApplication(applicationId, null); + return app; + } + public synchronized Map listTags(EmrServerlessService.ResourceArn resource) { JobRun run = runFor(resource).getJobRun(); return run.getTags() != null ? new LinkedHashMap<>(run.getTags()) : new LinkedHashMap<>(); @@ -567,7 +605,7 @@ public class EmrServerlessJobRunService implements Resettable { return lastSequence; } - private JobRunRecord newRun(Application app, StartJobRunRequest request, JsonNode original) { + private JobRunRecord newRun(Application app, StartJobRunRequest request, JsonNode original, boolean queued) { AwsArnUtils.Arn applicationArn = AwsArnUtils.parse(app.getArn()); String jobRunId = EmrServerlessService.newId(); Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS); @@ -582,7 +620,7 @@ public class EmrServerlessJobRunService implements Resettable { run.setCreatedAt(now); run.setUpdatedAt(now); requested(run, request); - run.setState(sparkRunner != null ? STATE_SCHEDULED : STATE_RUNNING); + run.setState(queued ? STATE_QUEUED : sparkRunner != null ? STATE_SCHEDULED : STATE_RUNNING); run.setStateDetails(""); run.setReleaseLabel(app.getReleaseLabel()); run.setNetworkConfiguration(app.getNetworkConfiguration()); @@ -590,7 +628,7 @@ public class EmrServerlessJobRunService implements Resettable { run.setAttemptCreatedAt(now); run.setAttemptUpdatedAt(now); applyImages(run, app); - if (sparkRunner == null) { + if (sparkRunner == null && !queued) { run.setStartedAt(now); } @@ -603,6 +641,7 @@ public class EmrServerlessJobRunService implements Resettable { record.setContainerRun(sparkRunner != null); keepDriverLogs(record, app); store.put(jobRunId, record); + indexRun(run); return record; } @@ -655,7 +694,7 @@ public class EmrServerlessJobRunService implements Resettable { private void launch(JobRunRecord record, Application app) { JobRun run = record.getJobRun(); JobDriver.Hive hive = run.getJobDriver().getHive(); - if ((hive != null) != HIVE_TYPE.equalsIgnoreCase(app.getType())) { + if (!driverIsTheApplications(run, app)) { run.setStateDetails(DRIVER_NOT_THE_APPLICATIONS); finish(record, STATE_FAILED, run.getCreatedAt()); return; @@ -1042,11 +1081,13 @@ public class EmrServerlessJobRunService implements Resettable { public synchronized void beforeReset() { generation++; executing.clear(); + runIdsByApplication.clear(); } @Override - public void clear() { - // The runs live in storage, which the reset has already wiped. + public synchronized void clear() { + // The runs live in storage, which the reset has already wiped; ids read before the wipe go with them. + runIdsByApplication.clear(); } // Whether a run's driver may still start, or go on: a cancelled run is past it, and so is one a reset removed. @@ -1153,6 +1194,8 @@ public class EmrServerlessJobRunService implements Resettable { finish(record, STATE_FAILED, now); } LOG.infov("EMR Serverless job run {0} ended {1}", jobRunId, run.getState()); + // Its running slot goes to the first queued run. + settleApplication(run.getApplicationId(), record); } /** @@ -1352,38 +1395,227 @@ public class EmrServerlessJobRunService implements Resettable { } } - /** - * Finishes a BATCH run that has been RUNNING for the configured duration, or cancels it at its - * execution timeout when that comes first: "If the job run exceeds this duration, Amazon EMR - * Serverless cancels it automatically." - */ private JobRunRecord settle(JobRunRecord record) { - JobRun run = record.getJobRun(); - if (record.isContainerRun()) { - // Its thread ends it; without one, Floci stopped while it ran and nothing is left to. - if (!isTerminal(run) && !executing.contains(run.getJobRunId())) { - run.setStateDetails(INTERRUPTED); - finish(record, STATE_FAILED, clock.instant().truncatedTo(ChronoUnit.MILLIS)); + settleApplication(record.getJobRun().getApplicationId(), record); + return record; + } + + /** + * The application's runs, {@code given} among them as the caller holds it, brought up to now, each change stored + * in one write. What happened since is replayed in order. A BATCH run of the immediate runner mode is SUCCESS once + * it has been RUNNING for the configured duration, or CANCELLED at its execution timeout when that comes first: "If + * the job run exceeds this duration, Amazon EMR Serverless cancels it automatically." The running slot a run frees + * goes at that moment to the first queued run: "Remaining jobs are queued until one of the running jobs + * terminates." A run still queued at its queue timeout "times out", which the job run states make a reason to be + * cancelled. A container run left without the thread that runs it was stopped by Floci's own shutdown, and is + * FAILED. A slot free now, after a cancel, an update or a container run's end, goes to the queue now. + */ + private List settleApplication(String applicationId, JobRunRecord given) { + List runs = runsOf(applicationId, given); + Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS); + Application app = applications.findLive(applicationId).orElse(null); + Replay replay = new Replay(app, app != null ? EmrServerlessScheduler.limits(app) : null); + List queued = new ArrayList<>(); + for (JobRunRecord record : runs) { + JobRun run = record.getJobRun(); + if (isTerminal(run)) { + continue; + } + if (STATE_QUEUED.equals(run.getState())) { + queued.add(record); + } else if (record.isContainerRun() && !executing.contains(run.getJobRunId())) { + run.setStateDetails(INTERRUPTED); + end(run, STATE_FAILED, now); + replay.changed.add(record); + } else { + replay.running(record); } - return record; } - if (isTerminal(run) || MODE_STREAMING.equals(run.getMode())) { - return record; + queued.sort(Comparator.comparingLong(JobRunRecord::getSequence)); + replay.queue.addAll(queued); + replay.run(now); + if (!replay.changed.isEmpty()) { + Map writes = new LinkedHashMap<>(); + replay.changed.forEach(record -> writes.put(record.getJobRun().getJobRunId(), record)); + store.putAll(writes); + } + // Once the changes are stored, and each counted as going first: a thread that runs at once would read them, and + // read a container run that has no thread as one Floci's shutdown stopped. + replay.launched.forEach(record -> executing.add(record.getJobRun().getJobRunId())); + replay.launched.forEach(record -> launch(record, app)); + return runs; + } + + /** + * The runs of the application {@code applicationId}, {@code given} as the caller holds it, read by their ids alone. + * Each account's ids are taken from its stored runs the first time they are needed, and kept as runs start. + */ + private List runsOf(String applicationId, JobRunRecord given) { + Map> byApplication = runIdsByApplication.computeIfAbsent(regionResolver.getAccountId(), + account -> { + Map> built = new HashMap<>(); + for (JobRunRecord record : store.scan(key -> true)) { + built.computeIfAbsent(record.getJobRun().getApplicationId(), id -> new LinkedHashSet<>()) + .add(record.getJobRun().getJobRunId()); + } + return built; + }); + List runs = new ArrayList<>(); + for (String jobRunId : byApplication.getOrDefault(applicationId, Set.of())) { + if (given != null && given.getJobRun().getJobRunId().equals(jobRunId)) { + runs.add(given); + } else { + store.get(jobRunId).ifPresent(runs::add); + } + } + return runs; + } + + // Keeps a new run's id with its application's, once the account's ids have been taken from its stored runs. + private void indexRun(JobRun run) { + Map> byApplication = runIdsByApplication.get(regionResolver.getAccountId()); + if (byApplication != null) { + byApplication.computeIfAbsent(run.getApplicationId(), id -> new LinkedHashSet<>()).add(run.getJobRunId()); + } + } + + /** One settling of an application's runs: what holds a running slot, what waits for one, and what changed. */ + private final class Replay { + private final Application app; + private final EmrServerlessScheduler.Limits limits; + // The runs that end on their own, by when; the others that hold a slot, which their thread or a cancel ends. + private final PriorityQueue timed = new PriorityQueue<>(Comparator.comparing(Timed::at)); + private int untimed; + private final Deque queue = new ArrayDeque<>(); + // By identity: whatever the records' own equality. + private final Set changed = Collections.newSetFromMap(new IdentityHashMap<>()); + private final List launched = new ArrayList<>(); + + Replay(Application app, EmrServerlessScheduler.Limits limits) { + this.app = app; + this.limits = limits; + } + + void running(JobRunRecord record) { + Ending ending = timedEnding(record); + if (ending != null) { + timed.add(new Timed(record, ending)); + } else { + untimed++; + } + } + + /** + * Replays the endings and queue timeouts due by {@code now} in order, each freed slot going to the queue at + * that moment, and then the slots free now; a run started now that ends at once frees its slot again. + */ + void run(Instant now) { + while (true) { + Timed first = timed.peek(); + Instant endsAt = first != null && !first.at().isAfter(now) ? first.at() : null; + JobRunRecord head = queue.peekFirst(); + Instant timesOutAt = head != null && limits != null + ? head.getJobRun().getCreatedAt().plus(limits.queueTimeout()) : null; + if (timesOutAt != null && !timesOutAt.isAfter(now) + && (endsAt == null || timesOutAt.isBefore(endsAt))) { + queue.pollFirst(); + JobRun run = head.getJobRun(); + leaveQueue(run, timesOutAt); + // 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); + changed.add(head); + } else if (endsAt != null) { + timed.poll(); + end(first.record().getJobRun(), first.ending().state(), endsAt); + changed.add(first.record()); + startQueued(endsAt); + } else if (!startQueued(now)) { + return; + } + } + } + + /** + * Starts the first queued runs at the moment {@code at} while the limit leaves a running slot, and says whether + * it took any from the queue: RUNNING in the immediate runner mode, SCHEDULED in the docker one, its driver + * launched once the changes are stored. A run whose driver is not its application's type fails as it leaves + * the queue, as {@link #launch} fails one, and takes no slot. + */ + boolean startQueued(Instant at) { + boolean took = false; + while (app != null && !queue.isEmpty() + && (limits == null || timed.size() + untimed < limits.maxConcurrentRuns())) { + JobRunRecord record = queue.pollFirst(); + JobRun run = record.getJobRun(); + leaveQueue(run, at); + run.setUpdatedAt(at); + run.setAttemptUpdatedAt(at); + record.setContainerRun(sparkRunner != null); + changed.add(record); + took = true; + if (sparkRunner == null) { + run.setState(STATE_RUNNING); + run.setStartedAt(at); + running(record); + } else if (!driverIsTheApplications(run, app)) { + run.setStateDetails(DRIVER_NOT_THE_APPLICATIONS); + end(run, STATE_FAILED, at); + } else { + run.setState(STATE_SCHEDULED); + launched.add(record); + untimed++; + } + } + return took; + } + } + + // A run that ends on its own, and how. + private record Timed(JobRunRecord record, Ending ending) { + Instant at() { + return ending.at(); + } + } + + // A run leaves the QUEUED state at the moment at, after waiting there since it was created. + private static void leaveQueue(JobRun run, Instant at) { + run.setQueuedDurationMilliseconds(Duration.between(run.getCreatedAt(), at).toMillis()); + } + + /** Whether a run's driver is its application's type: a {@code hive} one on a Hive application, else Spark's. */ + private static boolean driverIsTheApplications(JobRun run, Application app) { + return (run.getJobDriver().getHive() != null) == HIVE_TYPE.equalsIgnoreCase(app.getType()); + } + + // The runs that hold a running slot: those that have not ended and are not queued. + private static List active(List runs) { + return runs.stream() + .filter(record -> !isTerminal(record.getJobRun()) + && !STATE_QUEUED.equals(record.getJobRun().getState())) + .toList(); + } + + /** + * When a run of the immediate runner mode ends, and how: a BATCH run after the configured duration, or at its + * execution timeout when that comes first. Null for a container run, which its thread ends, and for a STREAMING + * run, which runs until it is cancelled. + */ + private Ending timedEnding(JobRunRecord record) { + JobRun run = record.getJobRun(); + if (record.isContainerRun() || MODE_STREAMING.equals(run.getMode()) || run.getStartedAt() == null) { + return null; } long timeoutSeconds = run.getExecutionTimeoutMinutes() == null || run.getExecutionTimeoutMinutes() == 0 ? Long.MAX_VALUE : run.getExecutionTimeoutMinutes() * 60; if (runDurationSeconds > timeoutSeconds) { - Instant timedOutAt = run.getStartedAt().plusSeconds(timeoutSeconds); - if (!clock.instant().isBefore(timedOutAt)) { - finish(record, STATE_CANCELLED, timedOutAt); - } - return record; + return new Ending(run.getStartedAt().plusSeconds(timeoutSeconds), STATE_CANCELLED); } - Instant finishedAt = run.getStartedAt().plusSeconds(runDurationSeconds); - if (!clock.instant().isBefore(finishedAt)) { - finish(record, STATE_SUCCESS, finishedAt); - } - return record; + return new Ending(run.getStartedAt().plusSeconds(runDurationSeconds), STATE_SUCCESS); + } + + private record Ending(Instant at, String state) { } private void finish(JobRunRecord record, String state, Instant endedAt) { diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessScheduler.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessScheduler.java new file mode 100644 index 0000000000..b0b597472f --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessScheduler.java @@ -0,0 +1,114 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.emrserverless.model.Application; +import io.floci.aws.services.emrserverless.model.SchedulerConfiguration; + +import java.time.Duration; +import java.util.Map; +import java.util.Set; + +/** + * An application's job concurrency and queuing, from the EMR Serverless user guide's "Job concurrency and queuing for + * an EMR Serverless application": at most {@code maxConcurrentRuns} of its batch and streaming job runs run at once, + * and the rest wait QUEUED until one of them ends, or until {@code queueTimeoutMinutes} have passed. It "is supported + * on Amazon EMR release 7.0.0 and higher" and "enabled by default on Amazon EMR release 7.3.0 and higher". + */ +final class EmrServerlessScheduler { + + static final String MAX_CONCURRENT_RUNS = "maxConcurrentRuns"; + static final String QUEUE_TIMEOUT_MINUTES = "queueTimeoutMinutes"; + // SchedulerConfiguration: "If scheduler configuration is enabled on your application, the default value is 15", and + // 360 minutes for the queue timeout; "The valid range is 1 to 1000", and "from 15 to 720". + static final int DEFAULT_MAX_CONCURRENT_RUNS = 15; + static final int DEFAULT_QUEUE_TIMEOUT_MINUTES = 360; + private static final int MAX_CONCURRENT_RUNS_LIMIT = 1000; + private static final int MIN_QUEUE_TIMEOUT_MINUTES = 15; + private static final int MAX_QUEUE_TIMEOUT_MINUTES = 720; + + /** How many of an application's runs may run at once, and how long one may wait QUEUED. */ + record Limits(int maxConcurrentRuns, Duration queueTimeout) { + } + + private EmrServerlessScheduler() { + } + + /** + * The limits an application's runs keep to, or null when its runs never queue: on a release before 7.0.0, on one + * before 7.3.0 whose application sets none, and on any whose application an empty configuration turned queuing + * off. The AWS runtime for Apache Spark's releases come after 7.14.0. + */ + static Limits limits(Application app) { + if (Boolean.TRUE.equals(app.getSchedulerOff())) { + return null; + } + String release = app.getReleaseLabel(); + boolean sparkRuntime = EmrServerlessJobRunService.sparkRuntime(release); + if (!sparkRuntime && !EmrServerlessJobRunService.releaseAtLeast(EmrServerlessJobRunService.RELEASE_LABEL, + release, 7, 0)) { + return null; + } + SchedulerConfiguration configuration = app.getSchedulerConfiguration(); + boolean configured = configuration != null && !configuration.getProperties().isEmpty(); + if (!configured && !sparkRuntime && !EmrServerlessJobRunService.releaseAtLeast( + EmrServerlessJobRunService.RELEASE_LABEL, release, 7, 3)) { + return null; + } + Map properties = configured ? configuration.getProperties() : Map.of(); + return new Limits(member(properties, MAX_CONCURRENT_RUNS, DEFAULT_MAX_CONCURRENT_RUNS), + Duration.ofMinutes(member(properties, QUEUE_TIMEOUT_MINUTES, DEFAULT_QUEUE_TIMEOUT_MINUTES))); + } + + /** + * The scheduler configuration an application holds once a request sets {@code requested} over {@code current}. + * Terraform's acceptance tests, run against AWS, found that an empty one turns queuing off and leaves the + * application without one, which this gives as null, and that a member it leaves out takes its default; here a + * member left out keeps the value {@code current} holds, or else takes its default. No source gives AWS's refusal + * of a value out of range, so its wording is Floci's. + */ + static SchedulerConfiguration merged(SchedulerConfiguration current, SchedulerConfiguration requested) { + Map asked = requested.getProperties(); + if (asked.isEmpty()) { + return null; + } + Map held = current != null ? current.getProperties() : Map.of(); + SchedulerConfiguration merged = new SchedulerConfiguration(); + merged.setProperty(MAX_CONCURRENT_RUNS, checked(asked, MAX_CONCURRENT_RUNS, 1, MAX_CONCURRENT_RUNS_LIMIT, + member(held, MAX_CONCURRENT_RUNS, DEFAULT_MAX_CONCURRENT_RUNS))); + merged.setProperty(QUEUE_TIMEOUT_MINUTES, checked(asked, QUEUE_TIMEOUT_MINUTES, MIN_QUEUE_TIMEOUT_MINUTES, + MAX_QUEUE_TIMEOUT_MINUTES, member(held, QUEUE_TIMEOUT_MINUTES, DEFAULT_QUEUE_TIMEOUT_MINUTES))); + return merged; + } + + /** + * Sets on the application the configuration {@link #merged} gave, null for none: an empty one asked for turns + * queuing off, as "specifying an empty SchedulerConfiguration{} (without any attributes) disables the feature". + */ + static void apply(Application app, SchedulerConfiguration merged) { + app.setSchedulerConfiguration(merged); + app.setSchedulerOff(merged == null ? Boolean.TRUE : null); + } + + /** Whether an update's scheduler configuration changes only what a STARTED application lets change. */ + static boolean startedApplicationMayTake(SchedulerConfiguration requested) { + // "You can update maxConcurrentRuns for an application in the STARTED state." + return requested == null || requested.getProperties().keySet().equals(Set.of(MAX_CONCURRENT_RUNS)); + } + + private static int member(Map properties, String name, int fallback) { + return properties.get(name) instanceof Number number ? number.intValue() : fallback; + } + + private static int checked(Map asked, String name, int min, int max, int fallback) { + Object value = asked.get(name); + if (value == null) { + return fallback; + } + if (!(value instanceof Integer || value instanceof Long) || ((Number) value).longValue() < min + || ((Number) value).longValue() > max) { + throw new AwsException("ValidationException", "schedulerConfiguration." + name + + " must be an integer from " + min + " to " + max + ".", 400); + } + return ((Number) value).intValue(); + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java index f3b6d235f3..4eded14994 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java @@ -24,6 +24,7 @@ import io.floci.aws.services.emrserverless.model.ApplicationSummary; import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; import io.floci.aws.services.emrserverless.model.ImageConfiguration; import io.floci.aws.services.emrserverless.model.ListApplicationsRequest; +import io.floci.aws.services.emrserverless.model.SchedulerConfiguration; import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification; import io.floci.aws.services.iam.IamService; @@ -59,14 +60,13 @@ public class EmrServerlessService { // on a key or a value. TagKey and TagValue share one character set in the API model. private static final String NOT_STOPPED_FOR_UPDATE = "Application must be in a stopped or created state in order to be updated."; - // The settings an update may change only on a CREATED or STOPPED application: all but its maximum capacity and - // its custom images, which a STARTED one takes too (checkStartedUpdate). + // The settings an update may change only on a CREATED or STOPPED application: all but its maximum capacity, its + // custom images and its scheduler's maxConcurrentRuns, which a STARTED one takes too (checkStartedUpdate). private static final List> STOPPED_ONLY_SETTINGS = List.of( UpdateApplicationRequest::getReleaseLabel, UpdateApplicationRequest::getInitialCapacity, UpdateApplicationRequest::getAutoStartConfiguration, UpdateApplicationRequest::getAutoStopConfiguration, UpdateApplicationRequest::getNetworkConfiguration, UpdateApplicationRequest::getArchitecture, UpdateApplicationRequest::getMonitoringConfiguration, UpdateApplicationRequest::getRuntimeConfiguration, - UpdateApplicationRequest::getSchedulerConfiguration, UpdateApplicationRequest::getDiskEncryptionConfiguration, UpdateApplicationRequest::getInteractiveConfiguration, UpdateApplicationRequest::getIdentityCenterConfiguration, @@ -127,6 +127,8 @@ public class EmrServerlessService { throw new AwsException("ValidationException", "clientToken is required", 400); } validateImages(request.getImageConfiguration(), request.getWorkerTypeSpecifications(), true); + SchedulerConfiguration scheduler = request.getSchedulerConfiguration() != null + ? EmrServerlessScheduler.merged(null, request.getSchedulerConfiguration()) : null; String region = regionResolver.getRegion(); if (request.getClientToken() != null) { @@ -166,7 +168,9 @@ public class EmrServerlessService { app.setWorkerTypeSpecifications(request.getWorkerTypeSpecifications()); app.setMonitoringConfiguration(request.getMonitoringConfiguration()); app.setRuntimeConfiguration(request.getRuntimeConfiguration()); - app.setSchedulerConfiguration(request.getSchedulerConfiguration()); + if (request.getSchedulerConfiguration() != null) { + EmrServerlessScheduler.apply(app, scheduler); + } app.setDiskEncryptionConfiguration(request.getDiskEncryptionConfiguration()); app.setInteractiveConfiguration(request.getInteractiveConfiguration()); app.setIdentityCenterConfiguration(request.getIdentityCenterConfiguration()); @@ -215,6 +219,10 @@ public class EmrServerlessService { } else if (!"CREATED".equals(state) && !"STOPPED".equals(state)) { throw new AwsException("ValidationException", NOT_STOPPED_FOR_UPDATE, 400); } + // Before anything changes: a refused value leaves the application as it was. + SchedulerConfiguration scheduler = request.getSchedulerConfiguration() != null + ? EmrServerlessScheduler.merged(app.getSchedulerConfiguration(), request.getSchedulerConfiguration()) + : null; if (request.getReleaseLabel() != null) { app.setReleaseLabel(request.getReleaseLabel()); @@ -255,7 +263,7 @@ public class EmrServerlessService { app.setRuntimeConfiguration(request.getRuntimeConfiguration()); } if (request.getSchedulerConfiguration() != null) { - app.setSchedulerConfiguration(request.getSchedulerConfiguration()); + EmrServerlessScheduler.apply(app, scheduler); } if (request.getDiskEncryptionConfiguration() != null) { app.setDiskEncryptionConfiguration(request.getDiskEncryptionConfiguration()); @@ -280,13 +288,15 @@ public class EmrServerlessService { * What an update may change on a STARTED application, from AWS's "Updating Running Applications": its maximum * capacity, "for a STARTED application to modify the scaling boundary", and its custom images, "without stopping * it", though "Custom image updates on running applications are not supported on applications with - * pre-initialized capacity configured". Any other setting still needs the application "in a stopped or created + * pre-initialized capacity configured". The concurrency and queuing guide adds "You can update maxConcurrentRuns + * for an application in the STARTED state". Any other setting still needs the application "in a stopped or created * state". A run already going keeps the image and maximum capacity it was launched with, as "existing workloads * continue with the original image" and "The new settings only apply to workers on new workloads"; a new run, or a * new attempt of one, takes the application's current ones. */ private static void checkStartedUpdate(Application app, UpdateApplicationRequest request) { - if (STOPPED_ONLY_SETTINGS.stream().anyMatch(setting -> setting.apply(request) != null)) { + if (STOPPED_ONLY_SETTINGS.stream().anyMatch(setting -> setting.apply(request) != null) + || !EmrServerlessScheduler.startedApplicationMayTake(request.getSchedulerConfiguration())) { throw new AwsException("ValidationException", NOT_STOPPED_FOR_UPDATE, 400); } boolean images = request.getImageConfiguration() != null || request.getWorkerTypeSpecifications() != null; @@ -580,6 +590,11 @@ public class EmrServerlessService { .filter(app -> !"TERMINATED".equals(app.getState())); } + /** The application, when it exists and has not been deleted, which leaves it TERMINATED. */ + public synchronized Optional findLive(String applicationId) { + return live(applicationId); + } + /** Whether the application exists and has not been deleted, which leaves it TERMINATED. */ public synchronized boolean isLive(String applicationId) { return live(applicationId).isPresent(); diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/Application.java b/src/main/java/io/floci/aws/services/emrserverless/model/Application.java index 49774fd811..d637577cc2 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/Application.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/Application.java @@ -44,6 +44,9 @@ public class Application { private MonitoringConfiguration monitoringConfiguration; private List runtimeConfiguration; private SchedulerConfiguration schedulerConfiguration; + // Whether an empty schedulerConfiguration turned queuing off, which leaves the application with none, so that a + // release that queues by default does not; Floci's own, as the API has none. + private Boolean schedulerOff; private DiskEncryptionConfiguration diskEncryptionConfiguration; private InteractiveConfiguration interactiveConfiguration; private IdentityCenterConfiguration identityCenterConfiguration; @@ -91,6 +94,8 @@ public class Application { public void setMonitoringConfiguration(MonitoringConfiguration monitoringConfiguration) { this.monitoringConfiguration = monitoringConfiguration; } public List getRuntimeConfiguration() { return runtimeConfiguration; } public void setRuntimeConfiguration(List runtimeConfiguration) { this.runtimeConfiguration = runtimeConfiguration; } + public Boolean getSchedulerOff() { return schedulerOff; } + public void setSchedulerOff(Boolean schedulerOff) { this.schedulerOff = schedulerOff; } public SchedulerConfiguration getSchedulerConfiguration() { return schedulerConfiguration; } public void setSchedulerConfiguration(SchedulerConfiguration schedulerConfiguration) { this.schedulerConfiguration = schedulerConfiguration; } public DiskEncryptionConfiguration getDiskEncryptionConfiguration() { return diskEncryptionConfiguration; } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/GetApplicationResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/GetApplicationResponse.java index ec1a1cfa95..ad787e1dec 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/GetApplicationResponse.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/GetApplicationResponse.java @@ -8,7 +8,7 @@ public class GetApplicationResponse { // The application is stored with the clientToken CreateApplication's retries are matched on, which // GetApplication's Application does not have. It is left out here, not on Application, so storage keeps it. - @JsonIgnoreProperties({"clientToken", "pinnedImages"}) + @JsonIgnoreProperties({"clientToken", "pinnedImages", "schedulerOff"}) private Application application; public Application getApplication() { 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 b10eab87e9..8697321b10 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 @@ -42,6 +42,8 @@ public class JobRun { private Instant startedAt; @JsonFormat(shape = JsonFormat.Shape.NUMBER) private Instant endedAt; + // "The total time for a job in the QUEUED state in milliseconds", once it has left that state. + private Long queuedDurationMilliseconds; private ImageConfiguration imageConfiguration; private Map workerTypeSpecifications; @@ -95,6 +97,10 @@ public class JobRun { public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; } public Instant getEndedAt() { return endedAt; } public void setEndedAt(Instant endedAt) { this.endedAt = endedAt; } + public Long getQueuedDurationMilliseconds() { return queuedDurationMilliseconds; } + public void setQueuedDurationMilliseconds(Long queuedDurationMilliseconds) { + this.queuedDurationMilliseconds = queuedDurationMilliseconds; + } public ImageConfiguration getImageConfiguration() { return imageConfiguration; } public void setImageConfiguration(ImageConfiguration imageConfiguration) { this.imageConfiguration = imageConfiguration; } public Map getWorkerTypeSpecifications() { return workerTypeSpecifications; } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/UpdateApplicationResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/UpdateApplicationResponse.java index 2603126d16..fa6908fdf2 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/UpdateApplicationResponse.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/UpdateApplicationResponse.java @@ -8,7 +8,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection; public class UpdateApplicationResponse { // Without the clientToken storage keeps, as GetApplicationResponse leaves it out. - @JsonIgnoreProperties({"clientToken", "pinnedImages"}) + @JsonIgnoreProperties({"clientToken", "pinnedImages", "schedulerOff"}) private Application application; public Application getApplication() { 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 69351ebce6..dc384daff8 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java @@ -409,6 +409,36 @@ class EmrServerlessJobRunIntegrationTest { .body("jobRun.endedAt", instanceOf(Number.class)); } + @Test + void aRunBeyondMaxConcurrentRunsWaitsQueuedUntilTheRunningOneIsCancelled() { + String applicationId = createApplication(", \"schedulerConfiguration\": {\"maxConcurrentRuns\": 1}"); + String application = "/applications/" + applicationId; + givenReq().when().get(application).then().statusCode(200) + .body("application.schedulerConfiguration.maxConcurrentRuns", equalTo(1)) + .body("application.schedulerConfiguration.queueTimeoutMinutes", equalTo(360)); + String running = startedRunId(applicationId, + sparkRun(UUID.randomUUID().toString(), ", \"mode\": \"STREAMING\"")); + String queued = startedRunId(applicationId, + sparkRun(UUID.randomUUID().toString(), ", \"mode\": \"STREAMING\"")); + + givenReq().when().get(application + "/jobruns/" + queued).then().statusCode(200) + .body("jobRun.state", equalTo("QUEUED")) + .body("jobRun", not(hasKey("startedAt"))); + givenReq().when().get(application + "/jobruns?states=QUEUED").then().statusCode(200) + .body("jobRuns.id", equalTo(List.of(queued))); + + givenReq().when().delete(application + "/jobruns/" + running).then().statusCode(200); + givenReq().when().get(application + "/jobruns/" + queued).then().statusCode(200) + .body("jobRun.state", equalTo("RUNNING")) + .body("jobRun.queuedDurationMilliseconds", instanceOf(Number.class)); + givenReq().when().delete(application + "/jobruns/" + queued).then().statusCode(200); + givenReq().when().post(application + "/stop").then().statusCode(200); + givenReq().body("{\"clientToken\": \"%s\", \"schedulerConfiguration\": {}}".formatted(UUID.randomUUID())) + .when().patch(application).then().statusCode(200) + .body("application.schedulerConfiguration", nullValue()) + .body("application", not(hasKey("schedulerOff"))); + } + @Test void anApplicationWithARunStillGoingIsNotStopped() { String applicationId = createApplication(""); 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 2c0179a1ca..8e99ab49e0 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -20,6 +20,7 @@ import io.floci.aws.services.emrserverless.model.JobRunSummary; import io.floci.aws.services.emrserverless.model.MaximumCapacity; import io.floci.aws.services.emrserverless.model.MonitoringConfiguration; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; +import io.floci.aws.services.emrserverless.model.SchedulerConfiguration; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; import io.floci.aws.services.iam.IamService; @@ -1105,6 +1106,216 @@ class EmrServerlessJobRunServiceTest { } // A SPARK application on releaseLabel, with monitoring as its monitoring configuration (null for none). + // An application on releaseLabel with these scheduler members, none for no scheduler configuration. + private String queuingApplication(String releaseLabel, Map scheduler) { + CreateApplicationRequest create = applicationRequest("queuing", releaseLabel, "SPARK"); + if (!scheduler.isEmpty()) { + create.setSchedulerConfiguration(EmrServerlessServiceTest.scheduler(scheduler)); + } + return applications.createApplication(create).getApplicationId(); + } + + private String start(EmrServerlessJobRunService service, String app, String mode) { + return service.startJobRun(app, request(mode, null)).getJobRunId(); + } + + @Test + void aRunBeyondMaxConcurrentRunsIsQueuedAndStartsTheMomentARunEnds() { + EmrServerlessJobRunService service = service(600); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 1)); + String first = start(service, app, null); + clock.advance(Duration.ofSeconds(1)); + String second = start(service, app, null); + + assertEquals("RUNNING", service.getJobRun(app, first, null).getState()); + JobRun queued = service.getJobRun(app, second, null); + assertEquals("QUEUED", queued.getState()); + assertNull(queued.getStartedAt()); + assertNull(queued.getQueuedDurationMilliseconds()); + assertEquals(List.of(second), service.listJobRuns(app, List.of("QUEUED"), null, null, null, null, null) + .items().stream().map(JobRunSummary::getId).toList()); + + // Read only once both have ended: the second started the moment the first ended. + clock.advance(Duration.ofHours(1)); + JobRun ended = service.getJobRun(app, first, null); + JobRun started = service.getJobRun(app, second, null); + assertEquals("SUCCESS", started.getState()); + assertEquals(ended.getEndedAt(), started.getStartedAt()); + assertEquals(Duration.between(started.getCreatedAt(), ended.getEndedAt()).toMillis(), + started.getQueuedDurationMilliseconds()); + assertEquals(600, started.getTotalExecutionDurationSeconds()); + } + + @Test + void aRunStillQueuedAtTheQueueTimeoutIsCancelled() { + EmrServerlessJobRunService service = service(0); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 1, "queueTimeoutMinutes", 15)); + start(service, app, "STREAMING"); + String queued = start(service, app, null); + + clock.advance(Duration.ofMinutes(15)); + JobRun run = service.getJobRun(app, queued, null); + assertEquals("CANCELLED", run.getState()); + assertEquals(run.getCreatedAt().plus(Duration.ofMinutes(15)), run.getEndedAt()); + assertEquals(900_000L, run.getQueuedDurationMilliseconds()); + assertNull(run.getStartedAt()); + assertEquals(0, run.getTotalExecutionDurationSeconds()); + assertTrue(run.getStateDetails().contains("15 minutes"), run.getStateDetails()); + } + + @Test + void aCancelOrAHigherLimitOnTheStartedApplicationStartsTheQueuedRunsInOrderAtOnce() { + EmrServerlessJobRunService service = service(0); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 1)); + String first = start(service, app, "STREAMING"); + String second = start(service, app, "STREAMING"); + String third = start(service, app, "STREAMING"); + String fourth = start(service, app, "STREAMING"); + + clock.advance(Duration.ofMinutes(1)); + service.cancelJobRun(app, third); + JobRun cancelled = service.getJobRun(app, third, null); + assertEquals("CANCELLED", cancelled.getState()); + assertEquals(Duration.between(cancelled.getCreatedAt(), cancelled.getEndedAt()).toMillis(), + cancelled.getQueuedDurationMilliseconds()); + assertTrue(cancelled.getQueuedDurationMilliseconds() >= 60_000L); + + service.cancelJobRun(app, first); + Instant firstEnded = service.getJobRun(app, first, null).getEndedAt(); + JobRun next = service.getJobRun(app, second, null); + assertEquals("RUNNING", next.getState()); + assertFalse(next.getStartedAt().isBefore(firstEnded)); + assertTrue(Duration.between(firstEnded, next.getStartedAt()).toSeconds() < 1, next.getStartedAt()::toString); + assertEquals("QUEUED", service.getJobRun(app, fourth, null).getState()); + AwsException stop = assertThrows(AwsException.class, () -> service.stopApplication(app)); + assertEquals("ValidationException", stop.getErrorCode()); + + UpdateApplicationRequest raise = new UpdateApplicationRequest(); + raise.setSchedulerConfiguration(EmrServerlessServiceTest.scheduler(Map.of("maxConcurrentRuns", 2))); + service.updateApplication(app, raise); + assertEquals("RUNNING", service.getJobRun(app, fourth, null).getState()); + } + + @Test + void runsQueueByDefaultFromRelease730AndNeverBeforeRelease700() { + EmrServerlessJobRunService service = service(0); + String byDefault = queuingApplication("emr-7.3.0", Map.of()); + String sparkRuntime = queuingApplication("emr-spark-8.0.0", Map.of()); + String notByDefault = queuingApplication("emr-7.2.0", Map.of()); + String tooEarly = queuingApplication("emr-6.15.0", Map.of("maxConcurrentRuns", 1)); + for (int run = 0; run < 15; run++) { + for (String app : List.of(byDefault, sparkRuntime, notByDefault, tooEarly)) { + start(service, app, "STREAMING"); + } + } + + assertEquals("QUEUED", service.getJobRun(byDefault, start(service, byDefault, "STREAMING"), null).getState()); + assertEquals("QUEUED", + service.getJobRun(sparkRuntime, start(service, sparkRuntime, "STREAMING"), null).getState()); + assertEquals("RUNNING", + service.getJobRun(notByDefault, start(service, notByDefault, "STREAMING"), null).getState()); + assertEquals("RUNNING", service.getJobRun(tooEarly, start(service, tooEarly, "STREAMING"), null).getState()); + } + + @Test + void aQueuedBatchRunThatStartsWithoutADurationEndsAsItStarts() { + EmrServerlessJobRunService service = service(0); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 1)); + String streaming = start(service, app, "STREAMING"); + String batch = start(service, app, null); + assertEquals("QUEUED", service.getJobRun(app, batch, null).getState()); + + service.cancelJobRun(app, streaming); + + JobRun run = service.getJobRun(app, batch, null); + assertEquals("SUCCESS", run.getState()); + assertEquals(run.getStartedAt(), run.getEndedAt()); + } + + @Test + void manyRunsEndingTogetherHandTheirSlotsOnInOrder() { + EmrServerlessJobRunService service = service(600); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 5)); + List runs = new ArrayList<>(); + for (int run = 0; run < 20; run++) { + runs.add(start(service, app, null)); + } + + clock.advance(Duration.ofHours(1)); + List ended = runs.stream().map(id -> service.getJobRun(app, id, null)).toList(); + for (int run = 0; run < ended.size(); run++) { + assertEquals("SUCCESS", ended.get(run).getState(), "run " + run); + if (run >= 5) { + assertEquals(ended.get(run - 5).getEndedAt(), ended.get(run).getStartedAt(), "run " + run); + } + } + } + + @Test + void anEmptySchedulerConfigurationTurnsQueuingOffOnAReleaseThatQueuesByDefault() { + EmrServerlessJobRunService service = service(0); + CreateApplicationRequest create = applicationRequest("off", "emr-7.5.0", "SPARK"); + create.setSchedulerConfiguration(new SchedulerConfiguration()); + String app = applications.createApplication(create).getApplicationId(); + assertNull(applications.getApplication(app).getSchedulerConfiguration()); + for (int run = 0; run < 15; run++) { + start(service, app, "STREAMING"); + } + + assertEquals("RUNNING", service.getJobRun(app, start(service, app, "STREAMING"), null).getState()); + } + + @Test + void aQueuedRunWhoseDriverIsNotItsApplicationsFailsAsItLeavesTheQueueAndTakesNoSlot() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 1)); + String first = start(service, app, null); + StartJobRunRequest hive = request(null, null); + JobDriver.Hive query = new JobDriver.Hive(); + query.setQuery("s3://bucket/query.sql"); + JobDriver hiveDriver = new JobDriver(); + hiveDriver.setHive(query); + hive.setJobDriver(hiveDriver); + String mismatched = service.startJobRun(app, hive).getJobRunId(); + String next = start(service, app, null); + clock.advance(Duration.ofSeconds(5)); + + runNext(); + + JobRun failed = service.getJobRun(app, mismatched, null); + assertEquals("FAILED", failed.getState()); + assertEquals(EmrServerlessJobRunService.DRIVER_NOT_THE_APPLICATIONS, failed.getStateDetails()); + assertTrue(failed.getEndedAt().isAfter(failed.getCreatedAt()), "it fails as it leaves the queue"); + assertEquals(failed.getCreatedAt().plusMillis(failed.getQueuedDurationMilliseconds()), failed.getEndedAt()); + assertEquals("SCHEDULED", service.getJobRun(app, next, null).getState()); + assertEquals("SUCCESS", service.getJobRun(app, first, null).getState()); + } + + @Test + void aQueuedContainerRunStartsItsDriverOnlyOnceTheRunningOneHasEnded() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner); + String app = queuingApplication("emr-7.5.0", Map.of("maxConcurrentRuns", 1)); + String first = start(service, app, null); + String second = start(service, app, null); + String third = start(service, app, null); + + assertEquals(1, tasks.size(), "only the first run's driver is launched"); + assertEquals("QUEUED", service.getJobRun(app, second, null).getState()); + service.cancelJobRun(app, third); + assertEquals("CANCELLED", service.getJobRun(app, third, null).getState()); + assertFalse(runner.stopped.contains(third), "a queued run has no driver to stop"); + + runNext(); + assertEquals("SUCCESS", service.getJobRun(app, first, null).getState()); + assertEquals("SCHEDULED", service.getJobRun(app, second, null).getState()); + runNext(); + assertEquals("SUCCESS", service.getJobRun(app, second, null).getState()); + assertEquals(List.of(first, second), runner.driversStarted); + assertTrue(tasks.isEmpty()); + } + private String application(String name, String releaseLabel, MonitoringConfiguration monitoring) { CreateApplicationRequest create = applicationRequest(name, releaseLabel, "SPARK"); create.setMonitoringConfiguration(monitoring); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessServiceTest.java index 14bc8b0e83..7b2b81f856 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessServiceTest.java @@ -12,6 +12,7 @@ import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; import io.floci.aws.services.emrserverless.model.ImageConfiguration; import io.floci.aws.services.emrserverless.model.InitialCapacityConfig; import io.floci.aws.services.emrserverless.model.MaximumCapacity; +import io.floci.aws.services.emrserverless.model.SchedulerConfiguration; import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification; import io.floci.aws.testing.InMemoryStorageFactory; @@ -414,6 +415,86 @@ class EmrServerlessServiceTest { assertEquals("emr-7.5.0", unchanged.getReleaseLabel()); } + /** + * As Terraform's acceptance tests found AWS keeping it: a member left out takes its default, or here keeps the one + * set, and an empty configuration turns queuing off, the application returning none. + */ + @Test + void aSchedulerConfigurationFillsWhatItLeavesOutAndAnEmptyOneRemovesIt() { + EmrServerlessService service = service(); + CreateApplicationRequest create = createRequest(); + create.setSchedulerConfiguration(scheduler(Map.of("maxConcurrentRuns", 5))); + String applicationId = service.createApplication(create).getApplicationId(); + assertEquals(Map.of("maxConcurrentRuns", 5, "queueTimeoutMinutes", 360), + service.getApplication(applicationId).getSchedulerConfiguration().getProperties()); + + UpdateApplicationRequest timeout = new UpdateApplicationRequest(); + timeout.setSchedulerConfiguration(scheduler(Map.of("queueTimeoutMinutes", 60))); + service.updateApplication(applicationId, timeout); + assertEquals(Map.of("maxConcurrentRuns", 5, "queueTimeoutMinutes", 60), + service.getApplication(applicationId).getSchedulerConfiguration().getProperties()); + + UpdateApplicationRequest off = new UpdateApplicationRequest(); + off.setSchedulerConfiguration(new SchedulerConfiguration()); + assertNull(service.updateApplication(applicationId, off).getSchedulerConfiguration()); + + for (Map outOfRange : List.>of(Map.of("maxConcurrentRuns", 0), + Map.of("maxConcurrentRuns", 1001), Map.of("queueTimeoutMinutes", 14), + Map.of("queueTimeoutMinutes", 721), Map.of("maxConcurrentRuns", "5"))) { + UpdateApplicationRequest refused = new UpdateApplicationRequest(); + refused.setSchedulerConfiguration(scheduler(outOfRange)); + AwsException error = assertThrows(AwsException.class, + () -> service.updateApplication(applicationId, refused), outOfRange::toString); + assertEquals("ValidationException", error.getErrorCode()); + } + } + + @Test + void anUpdateRefusedForItsSchedulerConfigurationChangesNothingElse() { + EmrServerlessService service = service(); + CreateApplicationRequest create = createRequest(); + create.setMaximumCapacity(capacity("100 vCPU")); + String applicationId = service.createApplication(create).getApplicationId(); + UpdateApplicationRequest update = new UpdateApplicationRequest(); + update.setMaximumCapacity(capacity("200 vCPU")); + update.setSchedulerConfiguration(scheduler(Map.of("maxConcurrentRuns", 0))); + + assertThrows(AwsException.class, () -> service.updateApplication(applicationId, update)); + + Application unchanged = service.getApplication(applicationId); + assertEquals("100 vCPU", unchanged.getMaximumCapacity().getCpu()); + assertNull(unchanged.getSchedulerConfiguration()); + } + + @Test + void aStartedApplicationTakesANewMaxConcurrentRunsButNoOtherSchedulerChange() { + EmrServerlessService service = service(); + CreateApplicationRequest create = createRequest(); + create.setSchedulerConfiguration(scheduler(Map.of("maxConcurrentRuns", 5, "queueTimeoutMinutes", 60))); + String applicationId = service.createApplication(create).getApplicationId(); + service.startApplication(applicationId); + + UpdateApplicationRequest concurrency = new UpdateApplicationRequest(); + concurrency.setSchedulerConfiguration(scheduler(Map.of("maxConcurrentRuns", 8))); + assertEquals(Map.of("maxConcurrentRuns", 8, "queueTimeoutMinutes", 60), + service.updateApplication(applicationId, concurrency).getSchedulerConfiguration().getProperties()); + for (Map other : List.>of(Map.of("queueTimeoutMinutes", 30), + Map.of("maxConcurrentRuns", 8, "queueTimeoutMinutes", 60), Map.of())) { + UpdateApplicationRequest refused = new UpdateApplicationRequest(); + refused.setSchedulerConfiguration(scheduler(other)); + AwsException error = assertThrows(AwsException.class, + () -> service.updateApplication(applicationId, refused), other::toString); + assertEquals("Application must be in a stopped or created state in order to be updated.", + error.getMessage()); + } + } + + static SchedulerConfiguration scheduler(Map members) { + SchedulerConfiguration scheduler = new SchedulerConfiguration(); + members.forEach(scheduler::setProperty); + return scheduler; + } + @Test void aStartedApplicationWithInitialCapacityTakesANewMaximumCapacityButNoNewImages() { EmrServerlessService service = service();