diff --git a/docs/services/emr-containers.md b/docs/services/emr-containers.md index 9b3e1e4226..ac6e699d0d 100644 --- a/docs/services/emr-containers.md +++ b/docs/services/emr-containers.md @@ -78,9 +78,13 @@ cluster's container provider id in the request's account and Region, the run is `stateDetails` "Cluster *id* does not exist." and `failureReason` `CLUSTER_UNAVAILABLE`, as that page gives it. Otherwise, in the `immediate` runner mode, the run is `COMPLETED` at once, or `RUNNING` for `job-run-duration-seconds` and then `COMPLETED`, and `CancelJobRun` moves a run that has not finished to -`CANCELLED`; in the `docker` one it runs (see [Running job runs](#running-job-runs)). A run with a -`retryPolicyConfiguration` reports `retryPolicyExecution` with one attempt. The release label is not -checked against EMR on EKS's releases. +`CANCELLED`; in the `docker` one it runs (see [Running job runs](#running-job-runs)). A +`retryPolicyConfiguration` whose `maxAttempts` is not from 1 to 2,147,483,647 is refused with +`ValidationException` ("Retry policy configuration's parameter value of maxAttempts is invalid"), as the +development guide's "Using job retry policies" gives it. A `maxAttempts` of 1 disables retries, and then +neither the policy nor `retryPolicyExecution` is shown ("These fields will not be visible when retry policy +is disabled in the job"); with more, the run reports `retryPolicyExecution`, its `currentAttemptCount` +starting at 1. The release label is not checked against EMR on EKS's releases. **Concurrent job limits.** `StartJobRun` applies the virtual cluster's limits, as the development guide's "Concurrent job limits for virtual clusters" describes them. At most `maxConcurrentJobRuns` runs are @@ -178,10 +182,19 @@ wrapper with `FLOCI_SERVICES_EMRCONTAINERS_RUNNER_MODE=docker` (see [Docker](../ stream's name starts at the virtual cluster's id. Each line goes as the driver wrote it, but for an empty one, which CloudWatch Logs refuses as an event. A run from a job template whose destination leaves out its `logGroupName` or `logUri`, which the template's model allows, is refused with `ValidationException`, as - `StartJobRun` refuses a request that does. The `` has the form a Spark - application on Kubernetes gets, `spark-` and 32 hexadecimal digits, but is Floci's own: the driver's local - mode reports another. Floci runs no job submitter, so there are no submitter logs, and its executors run + `StartJobRun` refuses a request that does. With retries enabled, the driver pod's name has a suffix of + each attempt's own, `spark--driver-`, as the guide gives it, so each attempt's logs + go to a folder and streams of their own, under the run's one ``. That id has the form + a Spark application on Kubernetes gets, `spark-` and 32 hexadecimal digits, but is Floci's own: the driver's + local mode reports another. Floci runs no job submitter, so there are no submitter logs, and its executors run in the driver's container, so their output is the driver's. `persistentAppUI`, `containerLogRotationConfiguration` and `managedLogs` are kept but not applied. -* **Not emulated yet**: a `retryPolicyConfiguration` does not start the driver again, and a run waits for its - container however long it takes, with no `job-start-timeout`. +* **Retries**: with a `maxAttempts` above 1, a driver that exits with an error is started again, "restarted + automatically if it fails", until the run has made `maxAttempts` attempts, after "an exponential retry + interval of (10 seconds, 20 seconds, 40 seconds ...) which is capped at 6 minutes". Between its attempts + the run is `SUBMITTED` and keeps its running slot, and each new attempt raises `currentAttemptCount`. A run + whose last attempt fails is `FAILED` as above. `CancelJobRun` between attempts cancels the run at once. A + run Floci stopped between its attempts waits out the rest of its backoff once it is read again, and then + makes its next attempt. A driver that cannot start, or that Floci stopped, is not retried. Floci sends no + EMR on EKS events, so there is no `EMR Job Run New Driver Attempt` event for each new driver. +* **Not emulated yet**: a run waits for its container however long it takes, with no `job-start-timeout`. diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java index 14e95a578e..d1f107c8a1 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java @@ -58,7 +58,9 @@ import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -92,6 +94,18 @@ public class EmrContainersService implements Resettable, StoredResourceArns { private static final String CLIENT_TOKEN = "_clientToken"; private static final String DUE_AT = "_dueAt"; + // When a run whose driver failed starts its next attempt, while it waits for its retry's backoff. + private static final String RETRY_AT = "_retryAt"; + // The id of the Spark application a run submits, the same for each of its attempts: a retry restarts the driver + // pod, which the guide tells apart by its suffix alone. + private static final String SPARK_APPLICATION_ID = "_sparkApplicationId"; + // "an exponential retry interval of (10 seconds, 20 seconds, 40 seconds ...) which is capped at 6 minutes" + // (EMR on EKS Development Guide, "Using job retry policies"). + private static final Duration FIRST_RETRY_DELAY = Duration.ofSeconds(10); + private static final Duration MAX_RETRY_DELAY = Duration.ofMinutes(6); + private static final String INVALID_MAX_ATTEMPTS = + "Retry policy configuration's parameter value of maxAttempts is invalid"; + private static final int DRIVER_POD_SUFFIX_LENGTH = 5; // Where a job run held in its virtual cluster's queue stands in it, the first to start lowest. private static final String QUEUE_POSITION = "_queuePosition"; private static final String ACCESS_ENTRY_INTEGRATED = "_eksAccessEntryIntegrated"; @@ -157,6 +171,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { // image-template and docker-network, each null when not set. private final String imageTemplate; private final String dockerNetwork; + // Where a retry waits for its backoff in the docker runner mode; null in the immediate one. + private final Delays delays; // The ARNs of the runs whose containers a thread of this process runs; a launched run not here was left by a // restart. private final Set executing = new HashSet<>(); @@ -177,7 +193,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { RUNNER_DOCKER.equalsIgnoreCase(config.services().emrcontainers().runnerMode()) ? sparkRunner : null, Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-containers-run-", 0).factory()), config.services().emrcontainers().imageTemplate().orElse(null), - config.services().emrcontainers().dockerNetwork().orElse(null)); + config.services().emrcontainers().dockerNetwork().orElse(null), + RUNNER_DOCKER.equalsIgnoreCase(config.services().emrcontainers().runnerMode()) ? Delays.timer() : null); // Before any run of this process starts: a driver an earlier one left belongs to a run read as FAILED. if (this.sparkRunner != null && config.services().emrcontainers().reconcileContainersOnStartup()) { sparkRunner.removeLeftoverDrivers(SERVICE); @@ -193,7 +210,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { IamService iamService, RequestContext requestContext, Clock clock, int jobRunDurationSeconds) { this(virtualClusters, jobRuns, endpoints, jobTemplates, securityConfigurations, mapper, regionResolver, - eksService, iamService, requestContext, clock, jobRunDurationSeconds, null, Runnable::run, null, null); + eksService, iamService, requestContext, clock, jobRunDurationSeconds, null, Runnable::run, null, null, + null); } EmrContainersService(AccountAwareStorageBackend virtualClusters, @@ -204,7 +222,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns { ObjectMapper mapper, RegionResolver regionResolver, EksService eksService, IamService iamService, RequestContext requestContext, Clock clock, int jobRunDurationSeconds, SparkJobRunner sparkRunner, Executor runExecutor, - String imageTemplate, String dockerNetwork) { + String imageTemplate, String dockerNetwork, Delays delays) { this.virtualClusters = virtualClusters; this.jobRuns = jobRuns; this.endpoints = endpoints; @@ -221,6 +239,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns { this.runExecutor = runExecutor; this.imageTemplate = imageTemplate; this.dockerNetwork = dockerNetwork; + this.delays = delays; } @PreDestroy @@ -228,6 +247,35 @@ public class EmrContainersService implements Resettable, StoredResourceArns { if (runExecutor instanceof ExecutorService executor) { executor.shutdownNow(); } + if (delays != null) { + delays.close(); + } + } + + /** Runs a task once its delay has passed, as a retry waits for its backoff; a test runs them when it chooses. */ + interface Delays { + + void after(Duration delay, Runnable task); + + default void close() { + } + + /** Delays on a daemon thread of their own. */ + static Delays timer() { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( + Thread.ofPlatform().daemon().name("emr-containers-retries").factory()); + return new Delays() { + @Override + public void after(Duration delay, Runnable task) { + executor.schedule(task, delay.toMillis(), TimeUnit.MILLISECONDS); + } + + @Override + public void close() { + executor.shutdownNow(); + } + }; + } } private static AccountAwareStorageBackend storage(StorageFactory storageFactory, String file) { @@ -400,15 +448,27 @@ public class EmrContainersService implements Resettable, StoredResourceArns { } run.put("createdAt", timestamp(now)); run.put("createdBy", createdBy()); + run.put(SPARK_APPLICATION_ID, sparkApplicationId()); ObjectNode tags = tags(template.get("jobTags")); tags.setAll(tags(request.get("tags"))); if (tags.size() > MAX_TAGS) { throw tooManyTags(); } run.set("tags", tags); - if (request.hasNonNull("retryPolicyConfiguration")) { - run.set("retryPolicyConfiguration", request.get("retryPolicyConfiguration").deepCopy()); - run.set("retryPolicyExecution", object("currentAttemptCount", 1)); + // "The valid maxAttempts range is from 1 to 2,147,483,647", and "If maxAttempts of the + // retryPolicyConfiguration is set to 1, it means that no retries will be done": the policy and its execution + // "will not be visible when retry policy is disabled in the job" (EMR on EKS Development Guide, "Using job + // retry policies"). + JsonNode retryPolicy = request.get("retryPolicyConfiguration"); + if (retryPolicy != null && !retryPolicy.isNull()) { + JsonNode maxAttempts = retryPolicy.path("maxAttempts"); + if (!maxAttempts.isIntegralNumber() || !maxAttempts.canConvertToInt() || maxAttempts.intValue() < 1) { + throw invalid(INVALID_MAX_ATTEMPTS); + } + if (maxAttempts.intValue() > 1) { + run.set("retryPolicyConfiguration", retryPolicy.deepCopy()); + run.set("retryPolicyExecution", object("currentAttemptCount", 1)); + } } // Concurrent job limits are "enforced at StartJobRun, before any pods are created": a run beyond the @@ -470,7 +530,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns { ObjectNode cancelled = run.deepCopy(); if (CANCEL_PENDING.equals(state)) { return object("id", id).put("virtualClusterId", virtualClusterId); - } else if (launched(run)) { + } else if (launched(run) && !run.has(RETRY_AT)) { // "CANCEL_PENDING - A job run has been requested for cancellation. Amazon EMR on EKS is trying to cancel // the job on the virtual cluster", until its driver is stopped. cancelled.put("state", CANCEL_PENDING); @@ -478,8 +538,10 @@ public class EmrContainersService implements Resettable, StoredResourceArns { runExecutor.execute(() -> sparkRunner.stop(id)); return object("id", id).put("virtualClusterId", virtualClusterId); } + // A queued run, or one between its attempts, whose next attempt the backoff's end then finds cancelled. finish(cancelled, CANCELLED, now()); jobRuns.put(cancelled.get("arn").textValue(), cancelled); + executing.remove(cancelled.get("arn").textValue()); // A running slot it frees goes to the queue's first run now. settledRuns(virtualClusterId); return object("id", id).put("virtualClusterId", virtualClusterId); @@ -993,7 +1055,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { * moment to the run first in the queue, "As running slots free up, queued job runs start automatically"; a run * still queued 30 minutes after it was submitted fails. A slot free now, once the limit is raised or a run is * cancelled, goes to the queue now. A run whose container runs holds its slot until its driver ends, and one - * whose container no thread of this process runs, as after a restart, has failed. + * whose container no thread of this process runs, as after a restart, has failed; one an earlier process left + * between its attempts waits out the rest of its backoff. */ private List settledRuns(ObjectNode cluster) { String prefix = cluster.get("arn").textValue() + JOB_RUNS; @@ -1005,7 +1068,13 @@ public class EmrContainersService implements Resettable, StoredResourceArns { Set changed = Collections.newSetFromMap(new IdentityHashMap<>()); List leftovers = new ArrayList<>(); for (ObjectNode run : runs) { - if (launched(run) && !executing.contains(run.get("arn").textValue())) { + String arn = run.get("arn").textValue(); + if (launched(run) && !executing.contains(arn) && run.has(RETRY_AT) && delays != null) { + // Between its attempts when an earlier process stopped, so no driver of it runs: its backoff goes on + // from where it was, and its next attempt starts once it has passed, at once if it already has. + Duration left = Duration.ofMillis(Math.max(0, run.get(RETRY_AT).longValue() - now.toEpochMilli())); + awaitNextAttempt(arn, left, generation); + } else if (launched(run) && !executing.contains(arn)) { finish(run, FAILED, now); run.put("stateDetails", MONITORING_FAILED); run.put("failureReason", INTERNAL_ERROR); @@ -1140,8 +1209,16 @@ public class EmrContainersService implements Resettable, StoredResourceArns { for (ObjectNode run : submitted) { String arn = run.get("arn").textValue(); try { + String applicationId = run.path(SPARK_APPLICATION_ID).textValue(); + if (applicationId == null) { + // A run stored before runs kept their application's id gets one now, for its later attempts too. + applicationId = sparkApplicationId(); + ObjectNode withId = run.deepCopy(); + withId.put(SPARK_APPLICATION_ID, applicationId); + jobRuns.put(arn, withId); + } SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, imageTemplate, dockerNetwork, - sparkApplicationId()); + applicationId, driverPod(run)); runExecutor.execute(() -> execute(arn, job, launchedIn)); } catch (RuntimeException e) { LOG.warnv(e, "EMR on EKS job run {0} could not be handed to a thread", run.get("id").textValue()); @@ -1174,6 +1251,72 @@ public class EmrContainersService implements Resettable, StoredResourceArns { RequestScopes.runAs(job.accountId(), job.region(), () -> ended(arn, ended, launchedIn)); } + // The attempt a run is on, 1 for its first, as its retryPolicyExecution counts them. + private static int attempt(ObjectNode run) { + return run.path("retryPolicyExecution").path("currentAttemptCount").asInt(1); + } + + // How many attempts a run may make: its retry policy's maxAttempts, 1 where retries are disabled. + private static int maxAttempts(ObjectNode run) { + return run.path("retryPolicyConfiguration").path("maxAttempts").asInt(1); + } + + /** + * Starts a run's next attempt once its backoff has passed: "Retry policies cause a job driver pod to be restarted + * automatically if it fails", after "an exponential retry interval of (10 seconds, 20 seconds, 40 seconds ...) + * which is capped at 6 minutes". Until then it is SUBMITTED, again "submitted to the virtual cluster", and keeps + * its slot; this process still follows it, so it is no leftover of a restart. + */ + private void retry(String arn, ObjectNode run, Instant now, long launchedIn) { + Duration delay = retryDelay(attempt(run)); + run.put("state", SUBMITTED); + run.put(RETRY_AT, now.plus(delay).toEpochMilli()); + jobRuns.put(arn, run); + awaitNextAttempt(arn, delay, launchedIn); + LOG.infov("EMR on EKS job run {0} failed attempt {1}, retrying in {2}s", run.get("id").textValue(), + attempt(run), delay.toSeconds()); + } + + // A run between its attempts holds its slot, this process following it, until its next attempt starts after delay. + private void awaitNextAttempt(String arn, Duration delay, long launchedIn) { + executing.add(arn); + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + delays.after(delay, () -> RequestScopes.runAs(parsed.accountId(), parsed.region(), + () -> nextAttempt(arn, launchedIn))); + } + + // The backoff after a run's attempt-th attempt failed: 10 seconds, doubling after each failure, at most 6 minutes. + static Duration retryDelay(int attempt) { + long seconds = FIRST_RETRY_DELAY.toSeconds() << Math.min(attempt - 1, 16); + return Duration.ofSeconds(Math.min(seconds, MAX_RETRY_DELAY.toSeconds())); + } + + // A run's backoff has passed: its next attempt starts, its driver in a container again, unless it was cancelled. + private synchronized void nextAttempt(String arn, long launchedIn) { + if (launchedIn != generation) { + return; + } + jobRuns.get(arn).filter(run -> SUBMITTED.equals(run.path("state").textValue()) && run.has(RETRY_AT)) + .ifPresent(stored -> { + ObjectNode run = stored.deepCopy(); + run.remove(RETRY_AT); + run.with("retryPolicyExecution").put("currentAttemptCount", attempt(run) + 1); + jobRuns.put(arn, run); + executing.remove(arn); + launch(List.of(run)); + }); + } + + /** + * The name a run's driver pod has, which names the folder of its logs: "Driver pod names follow the format + * spark--driver-", "The random-suffix is only present if the retry policy is enabled for the + * job", a suffix of each attempt's own. + */ + static String driverPod(ObjectNode run) { + String pod = "spark-" + run.get("id").textValue() + "-driver"; + return maxAttempts(run) > 1 ? pod + "-" + newId(DRIVER_POD_SUFFIX_LENGTH) : pod; + } + // A run's driver runs: "In Spark applications, this means that the Spark driver process is in the running state." private synchronized void driverStarted(String arn, long launchedIn) { if (launchedIn != generation) { @@ -1214,6 +1357,9 @@ public class EmrContainersService implements Resettable, StoredResourceArns { finish(run, CANCELLED, now); } else if (outcome.exitCode() != null && outcome.exitCode() == 0) { finish(run, COMPLETED, now); + } else if (outcome.exitCode() != null && attempt(run) < maxAttempts(run)) { + retry(arn, run, now, launchedIn); + return; } else { finish(run, FAILED, now); if (outcome.exitCode() != null) { @@ -1245,6 +1391,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns { run.put("finishedAt", timestamp(at)); run.remove(DUE_AT); run.remove(QUEUE_POSITION); + run.remove(RETRY_AT); } /** diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java index 39e7534cbb..e2aa5442c0 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java @@ -102,10 +102,10 @@ final class EmrContainersSparkJobs { * {@code spark.kubernetes.driver.container.image}, or else {@code spark.kubernetes.container.image}, names; its * driver's environment its {@code spark.kubernetes.driverEnv.} properties; its {@code spark.archives} are * unpacked in its working directory, as they are in a pod's. Its driver's logs go to {@link #driverLogFolder} and - * {@link #driverCloudWatchLogs}, under {@code sparkApplicationId}. + * {@link #driverCloudWatchLogs}, under {@code sparkApplicationId} and its driver pod's name, {@code driverPod}. */ static SparkJobRunner.Job job(ObjectNode run, String imageTemplate, String dockerNetwork, - String sparkApplicationId) { + String sparkApplicationId, String driverPod) { AwsArnUtils.Arn arn = AwsArnUtils.parse(run.get("arn").textValue()); String releaseLabel = run.get("releaseLabel").textValue(); JsonNode sparkSql = run.path("jobDriver").path("sparkSqlJobDriver"); @@ -130,8 +130,8 @@ final class EmrContainersSparkJobs { return new SparkJobRunner.Job(EmrContainersService.SERVICE, run.get("id").textValue(), arn.accountId(), arn.region(), releaseLabel, SparkJobRunner.Engine.SPARK, image(imageTemplate, releaseLabel), customImage, dockerNetwork, run.get("executionRoleArn").textValue(), sparkDefaults, application, - command, Duration.ZERO, driverLogFolder(run, sparkApplicationId), - driverCloudWatchLogs(run, sparkApplicationId), + command, Duration.ZERO, driverLogFolder(run, sparkApplicationId, driverPod), + driverCloudWatchLogs(run, sparkApplicationId, driverPod), EmrServerlessJobRunService.environment(properties, DRIVER_ENV_PREFIX), EmrServerlessJobRunService.archives(properties), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); @@ -142,10 +142,10 @@ final class EmrContainersSparkJobs { * /logUri/virtual-cluster-id/jobs/job-id/containers/spark-application-id/spark-job-id-driver/(stderr.gz/stdout.gz)" * (EMR on EKS Development Guide, "Configure a job run to use Amazon S3 logs"). */ - static String driverLogFolder(ObjectNode run, String sparkApplicationId) { + static String driverLogFolder(ObjectNode run, String sparkApplicationId, String driverPod) { String logUri = run.path("configurationOverrides").path("monitoringConfiguration") .path("s3MonitoringConfiguration").path("logUri").textValue(); - return EmrServerlessSparkRunner.logFolder(logUri, driverLogPath(run, sparkApplicationId) + "/"); + return EmrServerlessSparkRunner.logFolder(logUri, driverLogPath(run, sparkApplicationId, driverPod) + "/"); } /** @@ -155,7 +155,8 @@ final class EmrContainersSparkJobs { * "Configure a job run to use Amazon CloudWatch Logs"). Without a {@code logStreamNamePrefix} a stream's name * starts at the virtual cluster's id. */ - static SparkJobRunner.CloudWatchLogs driverCloudWatchLogs(ObjectNode run, String sparkApplicationId) { + static SparkJobRunner.CloudWatchLogs driverCloudWatchLogs(ObjectNode run, String sparkApplicationId, + String driverPod) { JsonNode cloudWatch = run.path("configurationOverrides").path("monitoringConfiguration") .path("cloudWatchMonitoringConfiguration"); String logGroup = cloudWatch.path("logGroupName").textValue(); @@ -164,14 +165,14 @@ final class EmrContainersSparkJobs { } String prefix = cloudWatch.path("logStreamNamePrefix").textValue(); String driver = (prefix != null && !prefix.isEmpty() ? prefix + "/" : "") - + driverLogPath(run, sparkApplicationId) + "/"; + + driverLogPath(run, sparkApplicationId, driverPod) + "/"; return new SparkJobRunner.CloudWatchLogs(logGroup, driver + STDOUT, driver + STDERR); } - // virtual-cluster-id/jobs/job-id/containers/spark-application-id/spark-job-id-driver, the driver pod's name. - private static String driverLogPath(ObjectNode run, String sparkApplicationId) { - String jobId = run.get("id").textValue(); - return run.get("virtualClusterId").textValue() + "/jobs/" + jobId + "/containers/" + sparkApplicationId - + "/spark-" + jobId + "-driver"; + // virtual-cluster-id/jobs/job-id/containers/spark-application-id/driver-pod, the driver pod's name being + // spark-job-id-driver, with an attempt's suffix where the run retries. + private static String driverLogPath(ObjectNode run, String sparkApplicationId, String driverPod) { + return run.get("virtualClusterId").textValue() + "/jobs/" + run.get("id").textValue() + "/containers/" + + sparkApplicationId + "/" + driverPod; } } diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java index 572c705a3a..a434f46421 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java @@ -52,6 +52,8 @@ class EmrContainersServiceTest { private final ObjectMapper mapper = new ObjectMapper(); private MutableClock clock; private EksService eks; + // The retries' backoffs a docker service waits for, which the test ends when it chooses. + private final QueuedDelays delays = new QueuedDelays(); @BeforeEach void setUp() { @@ -694,7 +696,7 @@ class EmrContainersServiceTest { when(iam.resolveCallerArn(eq(null))).thenReturn(Optional.empty()); return new EmrContainersService(stores.get(0), stores.get(1), stores.get(2), stores.get(3), stores.get(4), mapper, new RegionResolver(REGION, ACCOUNT_ID), eks, iam, null, clock, 0, runner, executor, - "registry.internal/emr-on-eks/spark/%s", "floci-net"); + "registry.internal/emr-on-eks/spark/%s", "floci-net", delays); } private EmrContainersService dockerService(FakeRunner runner, QueuedExecutor executor) { @@ -988,6 +990,194 @@ class EmrContainersServiceTest { "the same Spark application id names both"); } + private String startRetriedJobRun(EmrContainersService service, String clusterId, String retryPolicy) { + return service.startJobRun(clusterId, json(""" + {"clientToken": "%s", "executionRoleArn": "%s", "releaseLabel": "%s", + "jobDriver": {"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py"}}, + "retryPolicyConfiguration": %s, + "configurationOverrides": {"monitoringConfiguration": { + "s3MonitoringConfiguration": {"logUri": "s3://logs"}}}} + """.formatted(UUID.randomUUID(), ROLE, RELEASE, retryPolicy))).get("id").textValue(); + } + + @Test + void dockerRunWhoseDriverFailsIsRetriedAfterAnExponentialBackoffUntilItsAttemptsRunOut() { + FakeRunner runner = new FakeRunner(); + runner.outcome = SparkJobRunner.Outcome.exitedWith(1); + QueuedExecutor executor = new QueuedExecutor(); + EmrContainersService service = dockerService(runner, executor); + String clusterId = virtualCluster(service, EKS_CLUSTER); + String id = startRetriedJobRun(service, clusterId, "{\"maxAttempts\": 3}"); + + executor.runAll(); + + JsonNode waiting = jobRun(service, clusterId, id); + assertEquals("SUBMITTED", state(waiting), "between its attempts"); + assertEquals(1, waiting.at("/retryPolicyExecution/currentAttemptCount").intValue()); + assertEquals(List.of(Duration.ofSeconds(10)), delays.delays); + + delays.runAll(); + executor.runAll(); + assertEquals(2, jobRun(service, clusterId, id).at("/retryPolicyExecution/currentAttemptCount").intValue()); + assertEquals(List.of(Duration.ofSeconds(10), Duration.ofSeconds(20)), delays.delays); + delays.runAll(); + executor.runAll(); + + JsonNode run = jobRun(service, clusterId, id); + assertEquals("FAILED", state(run)); + assertEquals("USER_ERROR", run.get("failureReason").textValue()); + assertEquals(3, run.at("/retryPolicyExecution/currentAttemptCount").intValue()); + assertEquals(3, run.at("/retryPolicyConfiguration/maxAttempts").intValue()); + assertEquals(3, runner.jobs.size(), "a driver for each attempt"); + assertEquals(2, delays.delays.size(), "no backoff after the last"); + List folders = runner.jobs.stream().map(SparkJobRunner.Job::logFolder).toList(); + for (String folder : folders) { + assertTrue(folder.matches("s3://logs/" + clusterId + "/jobs/" + id + + "/containers/spark-[0-9a-f]{32}/spark-" + id + "-driver-[0-9a-z]{5}/"), folder); + } + assertEquals(3, Set.copyOf(folders).size(), "each attempt's driver pod has a suffix of its own"); + assertEquals(1, folders.stream().map(folder -> folder.split("/")[7]).distinct().count(), + "a retry restarts the driver of the same Spark application"); + } + + @Test + void dockerRunStoredWithoutItsApplicationIdKeepsTheOneItsFirstAttemptGets() { + List> stores = stores(); + FakeRunner runner = new FakeRunner(); + runner.outcome = SparkJobRunner.Outcome.exitedWith(1); + QueuedExecutor executor = new QueuedExecutor(); + EmrContainersService service = dockerService(runner, executor, stores); + String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}"); + startJobRun(service, clusterId); + String id = startRetriedJobRun(service, clusterId, "{\"maxAttempts\": 2}"); + // Queued as a run stored before runs kept their application's id was. + String arn = jobRun(service, clusterId, id).get("arn").textValue(); + ObjectNode stored = stores.get(1).get(arn).orElseThrow().deepCopy(); + stored.remove("_sparkApplicationId"); + stores.get(1).put(arn, stored); + + executor.runAll(); + delays.runAll(); + executor.runAll(); + + List attempts = runner.jobs.stream().filter(job -> job.runId().equals(id)).toList(); + assertEquals(2, attempts.size()); + assertEquals(attempts.get(0).logFolder().split("/")[7], attempts.get(1).logFolder().split("/")[7]); + assertEquals("FAILED", state(jobRun(service, clusterId, id))); + } + + @Test + void dockerRunAnEarlierProcessLeftBetweenItsAttemptsWaitsOutItsBackoffAndRetries() { + List> stores = stores(); + FakeRunner failing = new FakeRunner(); + failing.outcome = SparkJobRunner.Outcome.exitedWith(1); + QueuedExecutor earlierExecutor = new QueuedExecutor(); + EmrContainersService earlier = dockerService(failing, earlierExecutor, stores); + String clusterId = virtualCluster(earlier, EKS_CLUSTER); + String id = startRetriedJobRun(earlier, clusterId, "{\"maxAttempts\": 2}"); + earlierExecutor.runAll(); + assertEquals(List.of(Duration.ofSeconds(10)), delays.delays); + // The earlier process stops 4 seconds into the backoff, its timer with it. + delays.forget(); + clock.advance(Duration.ofSeconds(4)); + + FakeRunner runner = new FakeRunner(); + QueuedExecutor executor = new QueuedExecutor(); + EmrContainersService restarted = dockerService(runner, executor, stores); + JsonNode waiting = jobRun(restarted, clusterId, id); + + assertEquals("SUBMITTED", state(waiting), "not a run left running"); + assertEquals(1, waiting.at("/retryPolicyExecution/currentAttemptCount").intValue()); + assertEquals(List.of(Duration.ofSeconds(6)), delays.delays, "the rest of its backoff"); + delays.runAll(); + executor.runAll(); + JsonNode run = jobRun(restarted, clusterId, id); + assertEquals("COMPLETED", state(run)); + assertEquals(2, run.at("/retryPolicyExecution/currentAttemptCount").intValue()); + assertEquals(1, runner.jobs.size()); + assertTrue(runner.leftoversRemoved.isEmpty()); + assertEquals(failing.jobs.get(0).logFolder().split("/")[7], runner.jobs.get(0).logFolder().split("/")[7], + "the same Spark application"); + } + + @Test + void dockerRunWhoseRetriedDriverSucceedsCompletes() { + FakeRunner runner = new FakeRunner(); + runner.outcome = SparkJobRunner.Outcome.exitedWith(1); + QueuedExecutor executor = new QueuedExecutor(); + EmrContainersService service = dockerService(runner, executor); + String clusterId = virtualCluster(service, EKS_CLUSTER); + String id = startRetriedJobRun(service, clusterId, "{\"maxAttempts\": 5}"); + executor.runAll(); + + runner.outcome = SparkJobRunner.Outcome.exitedWith(0); + delays.runAll(); + executor.runAll(); + + JsonNode run = jobRun(service, clusterId, id); + assertEquals("COMPLETED", state(run)); + assertEquals(2, run.at("/retryPolicyExecution/currentAttemptCount").intValue()); + } + + @Test + void dockerRunCancelledBetweenItsAttemptsIsCancelledAtOnce() { + FakeRunner runner = new FakeRunner(); + runner.outcome = SparkJobRunner.Outcome.exitedWith(1); + QueuedExecutor executor = new QueuedExecutor(); + EmrContainersService service = dockerService(runner, executor); + String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}"); + String id = startRetriedJobRun(service, clusterId, "{\"maxAttempts\": 2}"); + String queued = startJobRun(service, clusterId).get("id").textValue(); + executor.runAll(); + assertEquals("PENDING", state(jobRun(service, clusterId, queued)), "the retried run keeps its slot"); + + service.cancelJobRun(clusterId, id); + + assertEquals("CANCELLED", state(jobRun(service, clusterId, id))); + assertEquals("SUBMITTED", state(jobRun(service, clusterId, queued)), "the freed slot goes to the queue"); + delays.runAll(); + executor.runAll(); + assertEquals("CANCELLED", state(jobRun(service, clusterId, id)), "its backoff's end starts nothing"); + assertEquals(1, runner.jobs.stream().filter(job -> job.runId().equals(id)).count()); + } + + @Test + void retryPolicyOfOneAttemptIsNotShownAndAnInvalidOneIsRefused() { + EmrContainersService service = service(0); + String clusterId = virtualCluster(service, EKS_CLUSTER); + + JsonNode disabled = jobRun(service, clusterId, startRetriedJobRun(service, clusterId, "{\"maxAttempts\": 1}")); + JsonNode enabled = jobRun(service, clusterId, startRetriedJobRun(service, clusterId, "{\"maxAttempts\": 2}")); + + assertFalse(disabled.has("retryPolicyConfiguration"), "not visible when retry policy is disabled"); + assertFalse(disabled.has("retryPolicyExecution")); + assertEquals(2, enabled.at("/retryPolicyConfiguration/maxAttempts").intValue()); + assertEquals(1, enabled.at("/retryPolicyExecution/currentAttemptCount").intValue()); + for (String invalid : List.of("0", "-1")) { + AwsException refused = assertThrows(AwsException.class, + () -> startRetriedJobRun(service, clusterId, "{\"maxAttempts\": " + invalid + "}"), invalid); + assertEquals("ValidationException", refused.getErrorCode()); + assertEquals("Retry policy configuration's parameter value of maxAttempts is invalid", + refused.getMessage()); + } + // Not a 32-bit integer at all, which the model's JavaInteger refuses first. + for (String invalid : List.of("2147483648", "\"2\"")) { + AwsException refused = assertThrows(AwsException.class, + () -> startRetriedJobRun(service, clusterId, "{\"maxAttempts\": " + invalid + "}"), invalid); + assertEquals("ValidationException", refused.getErrorCode()); + } + } + + @Test + void retryBackoffDoublesFromTenSecondsToSixMinutes() { + assertEquals(Duration.ofSeconds(10), EmrContainersService.retryDelay(1)); + assertEquals(Duration.ofSeconds(20), EmrContainersService.retryDelay(2)); + assertEquals(Duration.ofSeconds(40), EmrContainersService.retryDelay(3)); + assertEquals(Duration.ofSeconds(320), EmrContainersService.retryDelay(6)); + assertEquals(Duration.ofMinutes(6), EmrContainersService.retryDelay(7)); + assertEquals(Duration.ofMinutes(6), EmrContainersService.retryDelay(Integer.MAX_VALUE)); + } + @Test void monitoringDestinationWithoutItsLogGroupOrUriIsRefusedFromATemplateAsFromARequest() { EmrContainersService service = service(0); @@ -1028,6 +1218,30 @@ class EmrContainersServiceTest { assertEquals("COMPLETED", state(jobRun(service, clusterId, id))); } + /** Waits each backoff until the test ends them all, on the test's thread. */ + private static final class QueuedDelays implements EmrContainersService.Delays { + final List delays = new ArrayList<>(); + private final Deque tasks = new ArrayDeque<>(); + + @Override + public void after(Duration delay, Runnable task) { + delays.add(delay); + tasks.add(task); + } + + void runAll() { + while (!tasks.isEmpty()) { + tasks.removeFirst().run(); + } + } + + // The backoffs waited for so far go, as a process's timer goes with it. + void forget() { + delays.clear(); + tasks.clear(); + } + } + /** Runs what the service hands its run threads only when the test says so, on the test's thread. */ private static final class QueuedExecutor implements Executor { private final Deque tasks = new ArrayDeque<>(); diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java index 292148547b..16f1d8ac26 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java @@ -19,6 +19,7 @@ class EmrContainersSparkJobsTest { "arn:aws:emr-containers:eu-west-1:123456789012:/virtualclusters/vc1/jobruns/run1"; private static final String ROLE = "arn:aws:iam::123456789012:role/emr-job"; private static final String APPLICATION = "spark-0123456789abcdef0123456789abcdef"; + private static final String DRIVER = "spark-run1-driver"; private final ObjectMapper mapper = new ObjectMapper(); @@ -65,7 +66,7 @@ class EmrContainersSparkJobsTest { {"classification": "spark-defaults", "properties": {"spark.sql.shuffle.partitions": "4"}}]} """); - SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, "floci-net", APPLICATION); + SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, "floci-net", APPLICATION, DRIVER); assertEquals("emr-containers", job.service()); assertEquals("run1", job.runId()); @@ -101,7 +102,7 @@ class EmrContainersSparkJobsTest { "logStreamNamePrefix": "nightly"}}} """); - SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION); + SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION, DRIVER); String driver = "vc1/jobs/run1/containers/" + APPLICATION + "/spark-run1-driver/"; assertEquals("s3://logs/emr/" + driver, job.logFolder()); @@ -118,7 +119,7 @@ class EmrContainersSparkJobsTest { "cloudWatchMonitoringConfiguration": {"logGroupName": "jobs"}}} """); - SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION); + SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION, DRIVER); String driver = "vc1/jobs/run1/containers/" + APPLICATION + "/spark-run1-driver/"; assertEquals("s3://logs/" + driver, job.logFolder()); @@ -138,7 +139,7 @@ class EmrContainersSparkJobsTest { "sparkSqlParameters": "--conf spark.executor.instances=2 -hivevar table=reviews"}} """, null); - SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION); + SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION, DRIVER); assertEquals(List.of("spark-sql", "--conf", "spark.executor.instances=2", "-hivevar", "table=reviews", "-f", "s3://bucket/query.sql"), job.command()); @@ -157,7 +158,7 @@ class EmrContainersSparkJobsTest { "properties": {"spark.kubernetes.container.image": "custom/all:1"}}]} """); - SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION); + SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION, DRIVER); assertEquals("custom/driver:1", job.customImage(), "the driver's own image wins over the job's"); assertEquals(Map.of("PYSPARK_PYTHON", "./env/bin/python"), job.environment()); @@ -166,6 +167,7 @@ class EmrContainersSparkJobsTest { {"sparkSubmitJobDriver": {"entryPoint": "local:///app/job.py", "sparkSubmitParameters": "--conf spark.kubernetes.container.image=custom/all:2"}} """, null); - assertEquals("custom/all:2", EmrContainersSparkJobs.job(onlyJobImage, null, null, APPLICATION).customImage()); + assertEquals("custom/all:2", + EmrContainersSparkJobs.job(onlyJobImage, null, null, APPLICATION, DRIVER).customImage()); } }