feat(glue): run Spark job scripts in a container (#8568)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-19 11:14:30 -04:00
1 parent 379ac190c3
commit a06be2d292
13 files changed
+2182 -9

No files matched your search

+20 -1
View File
@@ -169,7 +169,7 @@ retroactively.
| GetJobRuns | Lists a job's runs, newest first. |
| BatchStopJobRun | Stops running runs of a job and reports the rest in `Errors`. |
Job runs do not execute the job's script. A run follows Glue's state machine and response shape: it
By default job runs do not execute the job's script (see [Running Spark job scripts](#running-spark-job-scripts)). A run follows Glue's state machine and response shape: it
takes the job's worker type, worker count, timeout and Glue version unless the request overrides them,
and `MaxConcurrentRuns` (1 when unset) rejects a start with `ConcurrentRunsExceededException` unless
`JobRunQueuingEnabled` is set. With the default `job-run-duration-seconds` of 0 a run is `SUCCEEDED` as
@@ -178,6 +178,22 @@ soon as it starts. A positive value keeps each run `RUNNING` for that many secon
timeout ends `TIMEOUT` when the timeout is reached. Queued runs are admitted straight away rather than
waiting in `WAITING`.
#### Running Spark job scripts
With `FLOCI_SERVICES_GLUE_RUNNER_MODE=docker`, `StartJobRun` runs the script of a Spark job (`Command.Name` `glueetl`) whose
`ScriptLocation` is in S3, with `spark-submit` in a container of AWS's Glue 5.0 image, which holds the Glue ETL library. The
script gets the job's `DefaultArguments` with the run's `Arguments` over them, plus `--JOB_NAME` and `--JOB_RUN_ID`, so
`awsglue.utils.getResolvedOptions` reads them. Its AWS calls reach Floci with the credentials of the job's `Role`.
The run is `RUNNING` while the script runs (or `WAITING` while `JobRunQueuingEnabled` is set and `MaxConcurrentRuns` is in use,
starting once a slot frees), then `SUCCEEDED` when it exits with 0 or `FAILED` with an `ErrorMessage` when it does not or cannot
start; `TIMEOUT` when the job's `Timeout` passes; `STOPPED` after `BatchStopJobRun`. Python shell, streaming and Ray jobs, and
jobs whose script is not in S3, keep the simulation above. The image is large (AWS asks for at least 7 GB of disk) and needs a
Docker daemon (explicitly mount `/var/run/docker.sock` when running Floci in a container or Testcontainers wrapper with
`FLOCI_SERVICES_GLUE_RUNNER_MODE=docker`), which is why the mode is off by default. When the Docker daemon is unreachable at
start, runs fall back to the simulation above; if Docker fails mid-run or Floci restarts while a run is executing or waiting,
the run is `FAILED`.
#### Crawlers
| Action | Description |
@@ -373,6 +389,9 @@ Each table bucket of the account is then a child catalog, `s3tablescatalog/<buck
|---|---|---|
| `FLOCI_SERVICES_GLUE_ENABLED` | `true` | Enable or disable the service |
| `FLOCI_SERVICES_GLUE_JOB_RUN_DURATION_SECONDS` | `0` | Seconds a job run stays `RUNNING` before it succeeds; `0` finishes it as soon as it starts |
| `FLOCI_SERVICES_GLUE_RUNNER_MODE` | `immediate` | `docker` runs the script of a `glueetl` job in a container; `immediate` runs no script |
| `FLOCI_SERVICES_GLUE_IMAGE` | `public.ecr.aws/glue/aws-glue-libs:5` | The image a `docker` job run uses |
| `FLOCI_SERVICES_GLUE_DOCKER_NETWORK` | | Docker network for the job containers; unset uses the global default |
| `FLOCI_SERVICES_GLUE_CRAWLER_RUN_DURATION_SECONDS` | `0` | Seconds a crawl keeps the crawler `RUNNING` before it succeeds; `0` finishes it as soon as it starts |
## Integration with Athena
@@ -2713,6 +2713,20 @@ public interface EmulatorConfig {
/** How long a crawl keeps the crawler RUNNING before it succeeds; 0 = a crawl finishes as soon as it starts. */
@WithDefault("0")
int crawlerRunDurationSeconds();
/**
* How a Spark ({@code glueetl}) job run executes: {@code immediate} follows Glue's state machine and runs no
* script; {@code docker} runs the job's script in a container of {@link #image()}, which needs a Docker daemon
* and about 7 GB of disk for the image.
*/
@WithDefault("immediate")
String runnerMode();
/** The image a {@code docker} job run uses: AWS's image for running Glue 5.0 jobs locally. */
@WithDefault("public.ecr.aws/glue/aws-glue-libs:5") // partition-literal: configurable; ECR Public exists only in the commercial partition
String image();
Optional<String> dockerNetwork();
}
interface SesServiceConfig {
@@ -0,0 +1,463 @@
package io.floci.aws.services.glue;
import com.github.dockerjava.api.command.InspectContainerResponse;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.S3Uri;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerLaunches;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerReconciler;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
import io.floci.aws.core.common.docker.RetryingTarCopier;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.services.iam.model.SessionCreds;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.floci.aws.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BooleanSupplier;
/**
* Runs a Glue job's script with {@code spark-submit} in a container of AWS's Glue image, which holds the Glue ETL
* library, so {@code awsglue.utils.getResolvedOptions} reads the script's arguments. The script's AWS calls reach
* Floci with the job role's credentials.
*/
@ApplicationScoped
public class DockerGlueScriptRunner implements GlueScriptRunner, ContainerTeardown {
private static final Logger LOG = Logger.getLogger(DockerGlueScriptRunner.class);
static final String SERVICE = "glue";
private static final String WORKSPACE = "/home/hadoop/workspace/";
private static final String DEFAULT_SCRIPT_NAME = "script.py";
private static final String SPARK_SUBMIT = "spark-submit";
private static final int STOP_TIMEOUT_SECONDS = 0;
private static final int MAX_FAILED_LOOKS = 3;
private static final int SCRIPT_BUFFER_BYTES = 64 * 1024;
private static final Duration POLL_INTERVAL = Duration.ofMillis(250);
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
private final LaunchedContainerAwsEnv awsEnv;
private final LambdaExecutionRoleCredentials roleCredentials;
private final IamService iamService;
private final ServiceRoleAuthorizer roleAuthorizer;
private final RegionResolver regionResolver;
private final S3Service s3Service;
private final EmulatorConfig config;
private final Clock clock;
private final Duration pollInterval;
private final ContainerLaunches launches = new ContainerLaunches();
private final ContainerReconciler reconciler;
@Inject
public DockerGlueScriptRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv,
LambdaExecutionRoleCredentials roleCredentials, IamService iamService,
ServiceRoleAuthorizer roleAuthorizer, RegionResolver regionResolver,
S3Service s3Service, EmulatorConfig config, Clock clock) {
this(containerBuilder, lifecycleManager, logStreamer, awsEnv, roleCredentials, iamService, roleAuthorizer,
regionResolver, s3Service, config, clock, POLL_INTERVAL);
}
DockerGlueScriptRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv,
LambdaExecutionRoleCredentials roleCredentials, RegionResolver regionResolver,
S3Service s3Service, EmulatorConfig config, Clock clock, Duration pollInterval) {
this(containerBuilder, lifecycleManager, logStreamer, awsEnv, roleCredentials, null, null, regionResolver,
s3Service, config, clock, pollInterval);
}
DockerGlueScriptRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv,
LambdaExecutionRoleCredentials roleCredentials, IamService iamService,
ServiceRoleAuthorizer roleAuthorizer, RegionResolver regionResolver,
S3Service s3Service, EmulatorConfig config, Clock clock, Duration pollInterval) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.awsEnv = awsEnv;
this.roleCredentials = roleCredentials;
this.iamService = iamService;
this.roleAuthorizer = roleAuthorizer;
this.regionResolver = regionResolver;
this.s3Service = s3Service;
this.config = config;
this.clock = clock;
this.pollInterval = pollInterval;
this.reconciler = new ContainerReconciler(lifecycleManager, LOG);
}
@Override
public boolean isAvailable() {
try {
lifecycleManager.getDockerClient().pingCmd().exec();
return true;
} catch (RuntimeException e) {
LOG.debugv(e, "Docker daemon is not reachable for Glue script execution");
return false;
}
}
@Override
public Outcome run(Run run, Progress progress) {
Instant startedOn = run.startedOn() != null ? run.startedOn() : clock.instant();
Instant deadline = run.timeout().isZero() ? null : startedOn.plus(run.timeout());
ContainerLaunches.Launch launch = launches.begin(run.runId());
Optional<SessionCreds> credentials = Optional.empty();
Closeable logHandle = null;
try {
// A cancel before the run was in launches had nothing to stop, so it is read here.
if (progress.cancelled()) {
return Outcome.halted();
}
if (timedOut(deadline)) {
return timedOutOutcome(run);
}
S3Uri script = S3Uri.parse(run.scriptLocation());
requireReadable(run, script);
credentials = resolveCredentials(run);
String network = containerBuilder.resolveDockerNetwork(Optional.ofNullable(run.dockerNetwork()))
.orElse(null);
String scriptPath = WORKSPACE + scriptName(script);
String resolvedImage = launchImage(run);
if (progress.cancelled()) {
return Outcome.halted();
}
if (timedOut(deadline)) {
return timedOutOutcome(run);
}
ContainerSpec spec = containerBuilder.newContainer(resolvedImage)
.withName(ContainerStorageHelper.dockerName(config, SERVICE + "-" + run.runId()))
.withEnv(awsEnv.sdkBaselineEnv(run.region(), Optional.empty(), credentials, run.accountId()))
.withEntrypoint(List.of(SPARK_SUBMIT))
.withCmd(commandLine(scriptPath, awsEnv.flociEndpoint(), run.region(), run.accountId(),
run.arguments()))
.withDockerNetwork(Optional.ofNullable(network))
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation()
.withLabels(labels(run))
.withJavaTrustStore()
.build();
String containerId = lifecycleManager.create(spec);
launch.started(containerId);
// A stop, a reset or a shutdown while the image was pulled is read now, before the script starts.
BooleanSupplier stopped = () -> launch.stopRequested() || progress.cancelled();
if (stopped.getAsBoolean()) {
return Outcome.halted();
}
if (timedOut(deadline)) {
return timedOutOutcome(run);
}
putScript(run, script, scriptPath, containerId, stopped);
if (stopped.getAsBoolean()) {
return Outcome.halted();
}
if (timedOut(deadline)) {
return timedOutOutcome(run);
}
lifecycleManager.startCreated(containerId, spec);
logHandle = logStreamer.attachConsoleOnly(containerId, SERVICE + ":" + run.runId());
return awaitEnd(containerId, run, launch, progress, deadline);
} catch (InterruptedException e) {
// Floci is shutting down: its teardown stops the container.
Thread.currentThread().interrupt();
return Outcome.halted();
} catch (RuntimeException e) {
if (launch.stopRequested() || progress.cancelled()) {
// A reset removed the container while it was being watched, or the run was stopped.
return Outcome.halted();
}
LOG.warnv(e, "Glue job run {0} of {1} could not run", run.runId(), run.jobName());
return Outcome.couldNotStart(e.getMessage());
} finally {
String unclaimed = launches.end(run.runId(), launch);
if (unclaimed != null) {
lifecycleManager.stopAndRemove(unclaimed, logHandle, STOP_TIMEOUT_SECONDS);
} else if (logHandle != null) {
// Floci's teardown claimed the container, but the log stream is still this run's to close.
lifecycleManager.closeLogStreamAfterContainerStop(logHandle);
}
credentials.ifPresent(session -> roleCredentials.unregister(run.accountId(), session.accessKeyId()));
}
}
@Override
public void stop(String runId) {
ContainerLaunches.Launch launch = launches.get(runId);
if (launch != null) {
// run() reads it once the container is up and at each look at it after, and removes it itself.
launch.requestStop();
}
}
/** Stops every run inside {@link #run}, so a reset or a shutdown orphans none. */
@Override
public void stopManagedContainers() {
launches.stopAll(lifecycleManager, STOP_TIMEOUT_SECONDS);
}
@Override
public void removeLeftoverContainers() {
String owner = ContainerStorageHelper.ownerIdentity(config);
reconciler.reconcile(
Map.of(ContainerStorageHelper.SERVICE_LABEL, SERVICE, ContainerStorageHelper.OWNER_LABEL, owner),
container -> true);
}
/**
* What follows {@code spark-submit}: Floci's settings for the script's own S3 and Glue Data Catalog access,
* the script, and its arguments.
*/
static List<String> commandLine(String scriptPath, String flociEndpoint, String region, String accountId,
List<String> arguments) {
List<String> command = new ArrayList<>();
// The s3 scheme a Glue script reads is served by S3A too, and aws.glue.endpoint routes Glue Catalog calls.
for (String setting : List.of(
"spark.hadoop.fs.s3a.endpoint=" + flociEndpoint,
"spark.hadoop.fs.s3a.endpoint.region=" + region,
"spark.hadoop.fs.s3a.path.style.access=true",
"spark.hadoop.fs.s3a.connection.ssl.enabled=" + flociEndpoint.startsWith("https"),
"spark.hadoop.fs.s3a.committer.magic.track.commits.in.memory.enabled=true",
"spark.hadoop.fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem",
"spark.hadoop.fs.AbstractFileSystem.s3.impl=org.apache.hadoop.fs.s3a.S3A",
"spark.hadoop.aws.glue.endpoint=" + flociEndpoint,
"spark.hadoop.hive.metastore.glue.catalogid=" + accountId,
"spark.hadoop.aws.region=" + region)) {
command.add("--conf");
command.add(setting);
}
command.add(scriptPath);
command.addAll(arguments);
return command;
}
/** The script's file name, which {@code spark-submit} needs to end in {@code .py} to run it as Python. */
static String scriptName(S3Uri script) {
String key = script.key();
String name = key.substring(key.lastIndexOf('/') + 1);
return name.endsWith(".py") ? name : DEFAULT_SCRIPT_NAME;
}
private Optional<SessionCreds> resolveCredentials(Run run) {
String roleRef = run.role();
boolean enforcement = isIamEnforcementEnabled();
if (roleRef == null || roleRef.isBlank()) {
if (enforcement) {
throw new IllegalArgumentException("Glue job " + run.jobName() + " has no IAM role.");
}
return Optional.empty();
}
String roleArn = resolveRoleArn(run, roleRef, enforcement);
if (roleArn == null) {
return Optional.empty();
}
if (enforcement) {
requireUsableRole(run, roleArn);
}
Optional<SessionCreds> session = roleCredentials.forRole(roleArn, run.accountId(), run.runId());
if (session.isEmpty()) {
if (enforcement) {
throw new IllegalArgumentException("The role " + roleRef + " does not exist.");
}
LOG.debugv("Glue job run {0} uses fallback credentials; role {1} was not found in IAM",
run.runId(), roleRef);
}
return session;
}
private String resolveRoleArn(Run run, String roleRef, boolean enforcement) {
String partition = regionResolver.partitionForRegion(run.region());
if (AwsArnUtils.looksLikeArn(roleRef)) {
AwsArnUtils.Arn parsed;
try {
parsed = AwsArnUtils.parse(roleRef);
} catch (IllegalArgumentException e) {
LOG.debugv(e, "Glue job role {0} is not a valid ARN", roleRef);
// Under enforcement the authorizer words the refusal.
return enforcement ? roleRef : null;
}
boolean namedRole = "iam".equals(parsed.service()) && parsed.resource().startsWith("role/")
&& !parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1).isBlank();
if (!namedRole) {
return enforcement ? roleRef : null;
}
if (!run.accountId().equals(parsed.accountId())) {
throw new IllegalArgumentException("Cross-account job role " + roleRef + " is not allowed.");
}
if (enforcement && !partition.equals(parsed.partition())) {
throw new IllegalArgumentException("The role " + roleRef + " belongs to another partition.");
}
return roleRef;
}
int slash = roleRef.lastIndexOf('/');
String roleName = slash >= 0 ? roleRef.substring(slash + 1) : roleRef;
if (roleName.isBlank()) {
if (enforcement) {
throw new IllegalArgumentException("The role " + roleRef + " has no role name.");
}
return null;
}
String expectedArn = AwsArnUtils.Arn.global(partition, "iam", run.accountId(), "role/" + roleRef).toString();
if (iamService != null) {
Optional<IamRole> found = iamService.findRole(run.accountId(), roleName);
if (slash >= 0) {
found = found.filter(role -> IamService.roleArnMatches(expectedArn, role));
}
if (found.isPresent()) {
return found.get().getArn();
}
}
return expectedArn;
}
private void requireUsableRole(Run run, String roleArn) {
String jobArn = AwsArnUtils.Arn.of("glue", run.region(), run.accountId(), "job/" + run.jobName()).toString();
Optional<String> refusal = roleAuthorizer.refusal(roleArn, run.accountId(), ServicePrincipals.of("glue"),
jobArn, List.of());
if (refusal.isPresent()) {
throw new IllegalArgumentException(refusal.get());
}
}
private boolean isIamEnforcementEnabled() {
return config.services() != null && config.services().iam() != null
&& config.services().iam().enforcementEnabled();
}
private boolean timedOut(Instant deadline) {
return deadline != null && !clock.instant().isBefore(deadline);
}
private Outcome timedOutOutcome(Run run) {
LOG.infov("Glue job run {0} of {1} passed its timeout of {2}", run.runId(), run.jobName(), run.timeout());
return Outcome.outOfTime();
}
private Map<String, String> labels(Run run) {
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(
SERVICE, run.runId(), run.accountId(), run.region()));
// The deployment that started the container, which removeLeftoverContainers() goes by.
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
return labels;
}
private String launchImage(Run run) {
String image = containerBuilder.resolveImage(run.image());
return lifecycleManager.resolveImageForLaunch(image, ImagePullBehavior.DEFAULT, null).imageId();
}
private void requireReadable(Run run, S3Uri script) {
try {
RequestScopes.runAs(run.accountId(), run.region(),
() -> s3Service.headObject(script.bucket(), script.key()));
} catch (AwsException e) {
throw new IllegalArgumentException(
"Could not read the script " + run.scriptLocation() + ": " + e.getMessage(), e);
}
}
/** Puts the script in the created container, read from Floci's S3 as the run's account. */
private void putScript(Run run, S3Uri script, String scriptPath, String containerId, BooleanSupplier stopped) {
if (stopped.getAsBoolean()) {
return;
}
try {
// Extracted at the root, the entry is the file's path without its leading slash.
RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, "/", scriptPath, out -> {
try (S3Service.ObjectRead read = RequestScopes.callAs(run.accountId(), run.region(),
() -> s3Service.openObject(script.bucket(), script.key(), null));
TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
TarArchiveEntry entry = new TarArchiveEntry(scriptPath.substring(1));
entry.setSize(read.object().getSize());
entry.setMode(0644);
tar.putArchiveEntry(entry);
transferUntilStopped(read.body(), tar, stopped);
tar.closeArchiveEntry();
}
});
} catch (RuntimeException e) {
// A copy the stop ended, or one whose container a reset removed.
if (stopped.getAsBoolean()) {
return;
}
throw e;
}
}
private static void transferUntilStopped(InputStream in, OutputStream out, BooleanSupplier stopped)
throws IOException {
byte[] buffer = new byte[SCRIPT_BUFFER_BYTES];
for (int read = in.read(buffer); read >= 0; read = in.read(buffer)) {
if (stopped.getAsBoolean()) {
throw new IOException("the job run was stopped");
}
out.write(buffer, 0, read);
}
}
private Outcome awaitEnd(String containerId, Run run, ContainerLaunches.Launch launch, Progress progress,
Instant deadline) throws InterruptedException {
int failedLooks = 0;
while (!launch.stopRequested() && !progress.cancelled()) {
if (timedOut(deadline)) {
return timedOutOutcome(run);
}
InspectContainerResponse.ContainerState state;
try {
state = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getState();
failedLooks = 0;
} catch (RuntimeException e) {
// One refused look is not the end of a healthy script.
if (++failedLooks >= MAX_FAILED_LOOKS) {
throw e;
}
LOG.warnv("Could not look at the container of Glue job run {0}: {1}", run.runId(), e.getMessage());
Thread.sleep(pollInterval.toMillis());
continue;
}
if (timedOut(deadline)) {
return timedOutOutcome(run);
}
if (!Boolean.TRUE.equals(state.getRunning())) {
if (launch.stopRequested() || progress.cancelled()) {
return Outcome.halted();
}
Long exitCode = state.getExitCodeLong();
return Outcome.exitedWith(exitCode != null ? exitCode.intValue() : -1);
}
Thread.sleep(pollInterval.toMillis());
}
return Outcome.halted();
}
}
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.RegionScopedStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -11,6 +13,7 @@ import io.floci.aws.services.glue.model.ExecutionProperty;
import io.floci.aws.services.glue.model.Job;
import io.floci.aws.services.glue.model.JobRun;
import io.floci.aws.services.glue.model.JobRunBookkeeping;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -20,37 +23,56 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
/**
* Glue job runs. No script executes: a run follows Glue's state machine and its response shape,
* Glue job runs. By default no script executes: a run follows Glue's state machine and its response shape,
* and settles lazily when read. With the default {@code job-run-duration-seconds} of 0 a run is
* SUCCEEDED as soon as it starts; a positive duration keeps it RUNNING until that much time has
* passed, which is what makes BatchStopJobRun and MaxConcurrentRuns observable.
*
* <p>With {@code runner-mode} {@code docker}, a Spark ({@code glueetl}) job whose script is in S3 runs that
* script in a container instead: the run is RUNNING until the script ends, and then SUCCEEDED or FAILED by
* its exit code, TIMEOUT at the job's timeout, or STOPPED by BatchStopJobRun. The script's end, the timeout
* and a stop compete for one terminal transition: whichever settles the run first wins, the others are ignored.
*
* <p>Every public method is synchronized: the store has no atomic compare and set, so admitting a
* run (count the live runs, check the limit, write the run), stopping one, settling one and
* removing a deleted job's runs must not interleave.
*/
@ApplicationScoped
public class GlueJobRunService {
public class GlueJobRunService implements Resettable {
private static final Logger LOG = Logger.getLogger(GlueJobRunService.class);
static final String STATE_WAITING = "WAITING";
static final String STATE_RUNNING = "RUNNING";
static final String STATE_SUCCEEDED = "SUCCEEDED";
static final String STATE_STOPPED = "STOPPED";
static final String STATE_TIMEOUT = "TIMEOUT";
static final String STATE_FAILED = "FAILED";
private static final Set<String> TERMINAL_STATES =
Set.of(STATE_SUCCEEDED, STATE_STOPPED, "FAILED", STATE_TIMEOUT, "ERROR", "EXPIRED");
Set.of(STATE_SUCCEEDED, STATE_STOPPED, STATE_FAILED, STATE_TIMEOUT, "ERROR", "EXPIRED");
// ExecutionProperty.MaxConcurrentRuns defaults to 1 when a job does not set it.
private static final int DEFAULT_MAX_CONCURRENT_RUNS = 1;
private static final int MAX_JOB_RUNS_PAGE_SIZE = 200;
private static final String LOG_GROUP_NAME = "/aws-glue/jobs";
private static final String RUNNER_DOCKER = "docker";
private static final String SPARK_COMMAND = "glueetl";
private static final String MODE_STREAMING = "STREAMING";
private static final String JOB_LANGUAGE_ARGUMENT = "--job-language";
private static final String SCALA = "scala";
private final StorageBackend<String, JobRun> runStore;
// Per run: the order in which Floci saw it finish (a conditional trigger's position; unlike
@@ -60,18 +82,44 @@ public class GlueJobRunService {
private final GlueService glueService;
private final int runDurationSeconds;
private final Clock clock;
private final RegionResolver regionResolver;
// Null in the immediate runner mode, where no script executes.
private final GlueScriptRunner scriptRunner;
private final Executor runExecutor;
private final String image;
private final String dockerNetwork;
// Script runs a thread is running, read and written only inside this service's synchronized methods; one not
// here that has not ended was left by a restart.
private final Set<String> executing = new HashSet<>();
// Script runs queued in WAITING in this process; one not here was left by a restart.
private final Set<String> waiting = new HashSet<>();
// Raised by each reset so an in-flight script thread from before it writes nothing back after the wipe.
private long generation;
@Inject
public GlueJobRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config,
RegionResolver regionResolver) {
RegionResolver regionResolver, DockerGlueScriptRunner dockerRunner) {
this(new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "job_runs.json", new TypeReference<>() {}),
new RegionScopedStorage<>(storageFactory, regionResolver,
"glue", "job_run_bookkeeping.json", new TypeReference<>() {}),
glueService, config.services().glue().jobRunDurationSeconds(), Clock.systemUTC());
glueService, config.services().glue().jobRunDurationSeconds(), Clock.systemUTC(), regionResolver,
RUNNER_DOCKER.equalsIgnoreCase(config.services().glue().runnerMode()) ? dockerRunner : null,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("glue-job-run-", 0).factory()),
config.services().glue().image(), config.services().glue().dockerNetwork().orElse(null));
// Before any run of this process starts: a container an earlier one left belongs to a run read as FAILED.
if (scriptRunner != null) {
scriptRunner.removeLeftoverContainers();
}
}
GlueJobRunService(StorageBackend<String, JobRun> runStore, StorageBackend<String, JobRunBookkeeping> bookkeepingStore,
GlueService glueService, int runDurationSeconds, Clock clock) {
this(runStore, bookkeepingStore, glueService, runDurationSeconds, clock, null, null, Runnable::run, null, null);
}
GlueJobRunService(StorageBackend<String, JobRun> runStore, StorageBackend<String, JobRunBookkeeping> bookkeepingStore,
GlueService glueService, int runDurationSeconds, Clock clock, RegionResolver regionResolver,
GlueScriptRunner scriptRunner, Executor runExecutor, String image, String dockerNetwork) {
if (runDurationSeconds < 0) {
throw new IllegalArgumentException(
"floci.services.glue.job-run-duration-seconds must not be negative: " + runDurationSeconds);
@@ -81,6 +129,18 @@ public class GlueJobRunService {
this.glueService = glueService;
this.runDurationSeconds = runDurationSeconds;
this.clock = clock;
this.regionResolver = regionResolver;
this.scriptRunner = scriptRunner;
this.runExecutor = runExecutor;
this.image = image;
this.dockerNetwork = dockerNetwork;
}
@PreDestroy
void shutdown() {
if (runExecutor instanceof ExecutorService executor) {
executor.shutdownNow();
}
}
/**
@@ -129,7 +189,6 @@ public class GlueJobRunService {
run.setJobRunQueuingEnabled(queuingEnabled);
run.setStartedOn(now);
run.setLastModifiedOn(now);
run.setJobRunState(STATE_RUNNING);
run.setArguments(overrides.getArguments());
run.setAllocatedCapacity(firstNonNull(overrides.getAllocatedCapacity(), job.getAllocatedCapacity()));
run.setTimeout(timeout);
@@ -144,11 +203,33 @@ public class GlueJobRunService {
run.setGlueVersion(job.getGlueVersion());
run.setLogGroupName(LOG_GROUP_NAME);
run.setExecutionTime(0);
Map<String, String> arguments = scriptArguments(job, run);
boolean eligible = scriptRunner != null && runsScript(job, arguments);
boolean script = false;
if (eligible) {
if (scriptRunner.isAvailable()) {
script = true;
} else {
LOG.warnv("Docker is not reachable; falling back to simulated Glue job run {0} for job {1}",
run.getId(), jobName);
}
}
boolean queuedWaiting = script && queuingEnabled && active >= maxConcurrentRuns(job);
run.setJobRunState(queuedWaiting ? STATE_WAITING : STATE_RUNNING);
runStore.put(run.getId(), run);
JobRunBookkeeping bookkeeping = new JobRunBookkeeping();
bookkeeping.setOriginRunId(originRunId != null ? originRunId : run.getId());
bookkeeping.setWorkflowRunId(workflowRunId);
bookkeeping.setScriptRun(script);
bookkeepingStore.put(run.getId(), bookkeeping);
if (queuedWaiting) {
waiting.add(run.getId());
LOG.infov("Queued Glue job run {0} for job {1} in WAITING", run.getId(), jobName);
return run;
}
if (script) {
launch(run, job, arguments);
}
LOG.infov("Started Glue job run {0} for job {1}", run.getId(), jobName);
return settle(run);
}
@@ -200,9 +281,16 @@ public class GlueJobRunService {
"Job run " + runId + " is not running; its state is " + run.getJobRunState()));
continue;
}
waiting.remove(runId);
complete(run, STATE_STOPPED, clock.instant(), null);
if (scriptRunner != null) {
scriptRunner.stop(runId);
}
stopped.add(new StoppedRun(jobName, runId));
}
if (!stopped.isEmpty() && scriptRunner != null) {
promoteWaitingRuns(jobName);
}
return new StopResult(stopped, errors);
}
@@ -266,15 +354,208 @@ public class GlueJobRunService {
/** Runs belong to their job: deleting the job removes them, as it does on AWS. */
public synchronized void deleteRuns(String jobName) {
for (JobRun run : runsOf(jobName)) {
waiting.remove(run.getId());
if (scriptRunner != null) {
scriptRunner.stop(run.getId());
}
runStore.delete(run.getId());
bookkeepingStore.delete(run.getId());
}
}
/**
* A reset has begun: runs' threads from before it write nothing more, so the storage wipe that follows
* leaves none of their runs behind. Container teardown has already stopped their containers.
*/
@Override
public synchronized void beforeReset() {
generation++;
executing.clear();
waiting.clear();
nextCompletionOrder = 0;
}
@Override
public void clear() {
// Runs and bookkeeping live in storage, which the reset has already wiped.
}
/** Whether the job is a Spark batch job whose script is in S3, which is what a container can run. */
private static boolean runsScript(Job job, Map<String, String> arguments) {
// The container runs a Python batch Spark script; streaming and Scala jobs keep the simulation.
return job.getCommand() != null && SPARK_COMMAND.equals(job.getCommand().getName())
&& !MODE_STREAMING.equalsIgnoreCase(job.getJobMode())
&& job.getCommand().getScriptLocation() != null
&& job.getCommand().getScriptLocation().startsWith("s3://")
&& !SCALA.equalsIgnoreCase(arguments.get(JOB_LANGUAGE_ARGUMENT));
}
/** The job's defaults, then the run's own, then non-overridable defaults, then the two the Glue library reads. */
private static Map<String, String> scriptArguments(Job job, JobRun run) {
Map<String, String> arguments = new LinkedHashMap<>();
if (job.getDefaultArguments() != null) {
arguments.putAll(job.getDefaultArguments());
}
if (run.getArguments() != null) {
arguments.putAll(run.getArguments());
}
if (job.getNonOverridableArguments() != null) {
arguments.putAll(job.getNonOverridableArguments());
}
arguments.put("--JOB_NAME", job.getName());
arguments.put("--JOB_RUN_ID", run.getId());
return arguments;
}
private void launch(JobRun run, Job job, Map<String, String> arguments) {
Duration timeout = run.getTimeout() == null ? Duration.ZERO : Duration.ofMinutes(run.getTimeout());
GlueScriptRunner.Run request = new GlueScriptRunner.Run(run.getId(), job.getName(),
regionResolver.getAccountId(), regionResolver.getRegion(), job.getRole(),
job.getCommand().getScriptLocation(), GlueScriptRunner.argumentList(arguments), image,
dockerNetwork, run.getStartedOn(), timeout);
executing.add(run.getId());
long launchedIn = generation;
try {
runExecutor.execute(() -> execute(request, launchedIn));
} catch (RejectedExecutionException e) {
// Floci is shutting down.
executing.remove(run.getId());
complete(run, STATE_FAILED, clock.instant(), "Floci is shutting down");
}
}
private void execute(GlueScriptRunner.Run request, long launchedIn) {
GlueScriptRunner.Outcome outcome = null;
try {
// This thread is in no request, so the run's account and Region are set for the store it reads.
outcome = scriptRunner.run(request, () -> RequestScopes.callAs(request.accountId(), request.region(),
() -> cancelled(request.runId(), launchedIn)));
} catch (Throwable t) {
LOG.warnv(t, "Glue job run {0} could not run", request.runId());
String message = t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName();
outcome = GlueScriptRunner.Outcome.couldNotStart(message);
if (t instanceof Error err) {
throw err;
}
} finally {
GlueScriptRunner.Outcome ended = outcome != null
? outcome
: GlueScriptRunner.Outcome.couldNotStart("Job run execution failed unexpectedly");
// Floci's shutdown interrupts this thread; its flag would fail the store's write, and it ends here anyway.
Thread.interrupted();
RequestScopes.runAs(request.accountId(), request.region(),
() -> ended(request.runId(), ended, launchedIn));
}
}
/** Whether the run is over or gone, as after BatchStopJobRun, deleting its job, or a reset. */
private synchronized boolean cancelled(String runId, long launchedIn) {
return launchedIn != generation || runStore.get(runId).map(GlueJobRunService::isTerminal).orElse(true);
}
/** The script's container ended: settles the run, unless a stop, reset, or deleting its job settled it first. */
private synchronized void ended(String runId, GlueScriptRunner.Outcome outcome, long launchedIn) {
if (launchedIn != generation) {
return;
}
executing.remove(runId);
JobRun run = runStore.get(runId).orElse(null);
if (run == null || isTerminal(run)) {
return;
}
Instant now = clock.instant();
if (outcome.stopped()) {
// BatchStopJobRun settles its run before it stops the script, so a run still live here was stopped by a
// reset or Floci's shutdown: not by the caller.
complete(run, STATE_FAILED, now, "Floci stopped the job run before its script ended");
} else if (outcome.timedOut()) {
complete(run, STATE_TIMEOUT, now, "Job run exceeded the timeout of " + run.getTimeout() + " minutes");
} else if (outcome.failure() != null) {
complete(run, STATE_FAILED, now, outcome.failure());
} else if (outcome.exitCode() != null && outcome.exitCode() == 0) {
complete(run, STATE_SUCCEEDED, now, null);
} else {
complete(run, STATE_FAILED, now, "The job script exited with code " + outcome.exitCode());
}
promoteWaitingRuns(run.getJobName());
}
private void promoteWaitingRuns(String jobName) {
if (scriptRunner == null) {
return;
}
Job job;
try {
job = glueService.getJob(jobName);
} catch (AwsException e) {
// The job was deleted while its run was ending.
return;
}
List<JobRun> runs = runsOf(jobName);
long running = 0;
List<JobRun> queued = new ArrayList<>();
for (JobRun candidate : runs) {
settle(candidate);
if (STATE_RUNNING.equals(candidate.getJobRunState())) {
running++;
} else if (STATE_WAITING.equals(candidate.getJobRunState())) {
queued.add(candidate);
}
}
if (queued.isEmpty()) {
return;
}
queued.sort(Comparator.comparing(JobRun::getStartedOn).thenComparing(JobRun::getId));
int limit = maxConcurrentRuns(job);
for (JobRun next : queued) {
if (running >= limit) {
break;
}
waiting.remove(next.getId());
Instant now = clock.instant();
next.setJobRunState(STATE_RUNNING);
next.setStartedOn(now);
next.setLastModifiedOn(now);
Map<String, String> arguments = scriptArguments(job, next);
if (!runsScript(job, arguments)) {
JobRunBookkeeping entry = bookkeepingOf(next.getId());
entry.setScriptRun(false);
bookkeepingStore.put(next.getId(), entry);
runStore.put(next.getId(), next);
settle(next);
if (!isTerminal(next)) {
running++;
}
continue;
}
runStore.put(next.getId(), next);
launch(next, job, arguments);
if (isTerminal(next)) {
// RejectedExecutionException means Floci is shutting down.
break;
}
running++;
LOG.infov("Promoted queued Glue job run {0} for job {1} to RUNNING", next.getId(), jobName);
}
}
private JobRun settle(JobRun run) {
if (isTerminal(run)) {
return run;
}
if (bookkeepingOf(run.getId()).isScriptRun()) {
if (STATE_WAITING.equals(run.getJobRunState())) {
if (!waiting.contains(run.getId())) {
complete(run, STATE_FAILED, clock.instant(), "Floci restarted while the job run was waiting");
}
return run;
}
// The script's end settles the run, not a clock; one no thread runs was left by a restart.
if (!executing.contains(run.getId())) {
complete(run, STATE_FAILED, clock.instant(), "Floci restarted while the job run was running");
}
return run;
}
Instant startedOn = run.getStartedOn();
long timeoutSeconds = run.getTimeout() == null ? Long.MAX_VALUE : run.getTimeout() * 60L;
if (runDurationSeconds >= timeoutSeconds) {
@@ -0,0 +1,83 @@
package io.floci.aws.services.glue;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Runs the script of a Glue Spark job to its end, in the {@code docker} runner mode. {@link GlueJobRunService}
* holds the run's state and calls this off the request thread; {@link DockerGlueScriptRunner} is the Docker
* implementation, and a test supplies its own.
*/
public interface GlueScriptRunner {
/** Whether the runner's execution backend (such as the Docker daemon) is reachable right now. */
default boolean isAvailable() {
return true;
}
/**
* Runs {@code run} and returns how it ended. Blocks until then, so the caller runs it off the request
* thread. A run {@code progress} reports as cancelled before its container starts never starts it.
*/
Outcome run(Run run, Progress progress);
/** Stops the run's container, now or as soon as it starts, so {@link #run} returns {@link Outcome#halted}. */
void stop(String runId);
/**
* Removes the containers of runs an earlier Floci process left running, which no thread follows any more.
* The service calls it before any run of its own can start.
*/
void removeLeftoverContainers();
/**
* What a run needs: its id and its job's name; its account and Region; the job's role, whose credentials the
* script gets; the S3 location of the script; the script's arguments, in the order they go on its command
* line ({@code --name value} pairs, {@code --JOB_NAME} among them); the image and Docker network to run it in
* (a null network is the global default); when the run started; and how long it may run ({@link Duration#ZERO}
* for no limit).
*/
record Run(String runId, String jobName, String accountId, String region, String role, String scriptLocation,
List<String> arguments, String image, String dockerNetwork, Instant startedOn, Duration timeout) {
}
/** What a run tells the service, and asks it, while it goes. */
interface Progress {
/** Whether the run was cancelled, or is gone, as after a reset: its container must not start. */
boolean cancelled();
}
/** How a run ended: its script's exit code, or that it ran out of time, was stopped, or could not start. */
record Outcome(Integer exitCode, boolean timedOut, boolean stopped, String failure) {
public static Outcome exitedWith(int exitCode) {
return new Outcome(exitCode, false, false, null);
}
public static Outcome outOfTime() {
return new Outcome(null, true, false, null);
}
public static Outcome halted() {
return new Outcome(null, false, true, null);
}
public static Outcome couldNotStart(String failure) {
return new Outcome(null, false, false, failure);
}
}
/** The command line {@code arguments} make, as a map is read: {@code --name value} for each entry. */
static List<String> argumentList(Map<String, String> arguments) {
List<String> list = new ArrayList<>();
arguments.forEach((name, value) -> {
list.add(name);
list.add(value == null ? "" : value);
});
return list;
}
}
@@ -17,6 +17,7 @@ public class JobRunBookkeeping {
private long completionOrder;
private String originRunId;
private String workflowRunId;
private boolean scriptRun;
@JsonProperty(value = "triggeredRuns", access = JsonProperty.Access.WRITE_ONLY)
private int legacyTriggeredRuns;
@@ -32,6 +33,10 @@ public class JobRunBookkeeping {
public String getOriginRunId() { return originRunId; }
public void setOriginRunId(String originRunId) { this.originRunId = originRunId; }
/** Whether a container runs the run's script, so that no clock settles it. */
public boolean isScriptRun() { return scriptRun; }
public void setScriptRun(boolean scriptRun) { this.scriptRun = scriptRun; }
public String getWorkflowRunId() { return workflowRunId; }
public void setWorkflowRunId(String workflowRunId) { this.workflowRunId = workflowRunId; }
}
+3
View File
@@ -761,6 +761,9 @@ floci:
enabled: true
job-run-duration-seconds: 0 # 0 = job runs succeed as soon as they start
crawler-run-duration-seconds: 0 # 0 = crawls finish as soon as they start
runner-mode: immediate # docker = run a glueetl job's script in a container of the image below
image: public.ecr.aws/glue/aws-glue-libs:5
# docker-network: floci_default
ses:
enabled: true
# smtp-host: mailpit # SMTP server for email relay (empty = store only)
@@ -0,0 +1,584 @@
package io.floci.aws.services.glue;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.S3Uri;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.services.iam.model.SessionCreds;
import io.floci.aws.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import io.floci.aws.testing.MutableClock;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class DockerGlueScriptRunnerTest {
private static final String ENDPOINT = "http://floci:4566";
private static final String ROLE = "arn:aws:iam::000000000000:role/glue";
private static final String SCRIPT = "s3://glue-demo/scripts/job.py";
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
private final S3Service s3 = mock(S3Service.class);
private final ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
private final LambdaExecutionRoleCredentials roleCredentials = mock(LambdaExecutionRoleCredentials.class);
private final GlueScriptRunner.Progress progress = mock(GlueScriptRunner.Progress.class);
private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
private final MutableClock clock = new MutableClock();
@Test
void putsTheScriptAndItsArgumentsAfterFlocisSparkSettings() {
List<String> command = DockerGlueScriptRunner.commandLine("/home/hadoop/workspace/job.py",
ENDPOINT, "us-east-1", "000000000000", List.of("--bucket", "glue-demo", "--JOB_NAME", "etl"));
int script = command.indexOf("/home/hadoop/workspace/job.py");
assertEquals(List.of("--bucket", "glue-demo", "--JOB_NAME", "etl"), command.subList(script + 1, command.size()));
assertTrue(command.contains("spark.hadoop.fs.s3a.endpoint=http://floci:4566"));
assertTrue(command.contains("spark.hadoop.fs.s3a.endpoint.region=us-east-1"));
assertTrue(command.contains("spark.hadoop.fs.s3a.path.style.access=true"));
assertTrue(command.contains("spark.hadoop.fs.s3a.connection.ssl.enabled=false"));
assertTrue(command.contains("spark.hadoop.fs.s3a.committer.magic.track.commits.in.memory.enabled=true"));
assertTrue(command.contains("spark.hadoop.fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem"));
assertTrue(command.contains("spark.hadoop.aws.glue.endpoint=http://floci:4566"));
assertTrue(command.contains("spark.hadoop.hive.metastore.glue.catalogid=000000000000"));
assertTrue(command.contains("spark.hadoop.aws.region=us-east-1"));
}
@Test
void enablesSslForAnHttpsEndpoint() {
List<String> command = DockerGlueScriptRunner.commandLine("/job.py", "https://floci:4566",
"us-east-1", "000000000000", List.of());
assertTrue(command.contains("spark.hadoop.fs.s3a.connection.ssl.enabled=true"));
}
@Test
void keepsAPythonScriptsNameAndNamesAnyOtherScript() {
assertEquals("job.py", DockerGlueScriptRunner.scriptName(S3Uri.parse("s3://b/scripts/job.py")));
assertEquals("script.py", DockerGlueScriptRunner.scriptName(S3Uri.parse("s3://b/scripts/job")));
assertEquals("script.py", DockerGlueScriptRunner.scriptName(S3Uri.parse("s3://b/job.sh")));
}
@Test
void turnsArgumentsIntoNameValuePairsInOrder() {
Map<String, String> arguments = new LinkedHashMap<>();
arguments.put("--a", "1");
arguments.put("--flag", null);
assertEquals(List.of("--a", "1", "--flag", ""), GlueScriptRunner.argumentList(arguments));
}
@Test
void anExitOfZeroEndsTheRunAndTheContainerIsRemoved() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(docker.copyArchiveToContainerCmd("script")).thenReturn(copy);
Map<String, String> copied = copiedIn(copy);
inS3("glue-demo", "scripts/job.py", "print('hi')");
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertEquals(0, outcome.exitCode());
assertFalse(outcome.stopped());
assertFalse(outcome.timedOut());
// Extracted at the container's root, where the Glue image keeps its workspace.
assertEquals(Map.of("home/hadoop/workspace/job.py", "print('hi')"), copied);
verify(spec).withEntrypoint(List.of("spark-submit"));
verify(spec).withCmd(argThat((List<String> cmd) -> cmd.contains("/home/hadoop/workspace/job.py")
&& cmd.getLast().equals("jr_1") && cmd.contains("--JOB_NAME")));
verify(lifecycle).startCreated(eq("script"), any());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void aNonZeroExitIsTheScriptsExitCode() {
DockerGlueScriptRunner runner = runner(container("script", false, 3L));
inS3("glue-demo", "scripts/job.py", "raise SystemExit(3)");
assertEquals(3, runner.run(request(Duration.ZERO), progress).exitCode());
}
@Test
void theJobRolesCredentialsReachTheScriptAndAreGivenBackWhenItEnds() {
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
when(roleCredentials.forRole(ROLE, "000000000000", "jr_1")).thenReturn(Optional.of(session));
inS3("glue-demo", "scripts/job.py", "pass");
runner.run(request(Duration.ZERO), progress);
verify(awsEnv).sdkBaselineEnv("us-east-1", Optional.empty(), Optional.of(session), "000000000000");
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
}
@Test
void aScriptThatCannotBeReadFailsTheRunBeforeAnyContainerExists() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
when(s3.headObject("glue-demo", "scripts/job.py"))
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertTrue(outcome.failure().contains("Could not read the script " + SCRIPT));
verify(lifecycle, never()).create(any());
}
@Test
void aRunCancelledBeforeItStartsNeverCreatesAContainer() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
when(progress.cancelled()).thenReturn(true);
assertTrue(runner.run(request(Duration.ZERO), progress).stopped());
verify(lifecycle, never()).create(any());
}
@Test
void aStopWhileTheImageIsPulledNeverStartsTheScript() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
inS3("glue-demo", "scripts/job.py", "pass");
when(lifecycle.create(any())).thenAnswer(pulling -> {
runner.stop("jr_1");
return "script";
});
assertTrue(runner.run(request(Duration.ZERO), progress).stopped());
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void aStopWhileTheScriptRunsEndsTheRunAndRemovesTheContainer() {
DockerGlueScriptRunner runner = runner(container("script", true, null));
inS3("glue-demo", "scripts/job.py", "while True: pass");
when(docker.inspectContainerCmd("script").exec().getState().getRunning()).thenAnswer(look -> {
runner.stop("jr_1");
return true;
});
assertTrue(runner.run(request(Duration.ZERO), progress).stopped());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void aScriptPastItsTimeoutEndsTheRunAndRemovesTheContainer() {
DockerGlueScriptRunner runner = runner(container("script", true, null));
inS3("glue-demo", "scripts/job.py", "while True: pass");
when(docker.inspectContainerCmd("script").exec().getState().getRunning()).thenAnswer(look -> {
clock.advance(Duration.ofMinutes(31));
return true;
});
assertTrue(runner.run(request(Duration.ofMinutes(30)), progress).timedOut());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void aRunWithoutATimeoutIsNeverTimedOut() {
DockerGlueScriptRunner runner = runner(container("script", true, null));
inS3("glue-demo", "scripts/job.py", "while True: pass");
AtomicInteger looks = new AtomicInteger();
when(docker.inspectContainerCmd("script").exec().getState().getRunning()).thenAnswer(look -> {
clock.advance(Duration.ofDays(30));
// Ends on the second look, as the container exits.
return looks.incrementAndGet() < 2;
});
when(docker.inspectContainerCmd("script").exec().getState().getExitCodeLong()).thenReturn(0L);
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertFalse(outcome.timedOut());
assertNull(outcome.failure());
}
@Test
void theTimeoutCountsFromTheRunsStartSoAnImagePullIsPartOfIt() {
DockerGlueScriptRunner runner = runner(container("script", true, null));
inS3("glue-demo", "scripts/job.py", "pass");
when(lifecycle.create(any())).thenAnswer(pulling -> {
clock.advance(Duration.ofMinutes(31));
return "script";
});
assertTrue(runner.run(request(Duration.ofMinutes(30)), progress).timedOut());
}
@Test
void aSingleRefusedLookAtTheContainerDoesNotEndTheRun() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
inS3("glue-demo", "scripts/job.py", "pass");
AtomicInteger looks = new AtomicInteger();
when(docker.inspectContainerCmd("script")).thenAnswer(look -> {
if (looks.incrementAndGet() == 1) {
throw new IllegalStateException("daemon busy");
}
return mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS);
});
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertNull(outcome.failure());
assertTrue(looks.get() >= 2);
}
@Test
void containerLooksThatKeepFailingFailTheRunAndRemoveTheContainer() {
DockerGlueScriptRunner runner = runner(container("script", true, null));
inS3("glue-demo", "scripts/job.py", "pass");
when(docker.inspectContainerCmd("script")).thenThrow(new IllegalStateException("daemon gone"));
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertEquals("daemon gone", outcome.failure());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void aContainerThatCannotBeCreatedFailsTheRunAndStillReleasesItsCredentials() {
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
when(roleCredentials.forRole(ROLE, "000000000000", "jr_1")).thenReturn(Optional.of(session));
inS3("glue-demo", "scripts/job.py", "pass");
when(lifecycle.create(any())).thenThrow(new IllegalStateException("no space left on device"));
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertEquals("no space left on device", outcome.failure());
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
}
@Test
void timeoutCountsFromRecordedStartedOnEvenBeforeWorkerBegins() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
Instant startedOn = clock.instant();
clock.advance(Duration.ofMinutes(31));
GlueScriptRunner.Outcome outcome = runner.run(request(startedOn, Duration.ofMinutes(30)), progress);
assertTrue(outcome.timedOut());
verify(lifecycle, never()).create(any());
}
@Test
void timeoutDuringPreparationDoesNotStartTheContainer() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
inS3("glue-demo", "scripts/job.py", "pass");
when(lifecycle.create(any())).thenAnswer(pulling -> {
clock.advance(Duration.ofMinutes(31));
return "script";
});
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ofMinutes(30)), progress);
assertTrue(outcome.timedOut());
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void timeoutAtInspectionReturnsTimedOutEvenIfContainerAlsoStopped() {
DockerGlueScriptRunner runner = runner(container("script", true, 0L));
inS3("glue-demo", "scripts/job.py", "pass");
InspectContainerResponse response = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
when(response.getState().getRunning()).thenReturn(false);
when(response.getState().getExitCodeLong()).thenReturn(0L);
when(docker.inspectContainerCmd("script").exec()).thenAnswer(look -> {
clock.advance(Duration.ofMinutes(31));
return response;
});
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ofMinutes(30)), progress);
assertTrue(outcome.timedOut());
}
@Test
void resolvesRoleNameViaIamServiceForScriptCredentials() {
IamService iamService = mock(IamService.class);
ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class);
String resolvedArn = "arn:aws:iam::000000000000:role/service-role/glue-role";
IamRole role = new IamRole("role-id", "glue-role", "/service-role/", resolvedArn, "{}");
when(iamService.findRole("000000000000", "glue-role")).thenReturn(Optional.of(role));
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
when(roleCredentials.forRole(resolvedArn, "000000000000", "jr_1")).thenReturn(Optional.of(session));
DockerGlueScriptRunner runner = runner("script", iamService, authorizer);
container("script", false, 0L);
inS3("glue-demo", "scripts/job.py", "pass");
GlueScriptRunner.Outcome outcome = runner.run(request("glue-role", clock.instant(), Duration.ZERO), progress);
assertEquals(0, outcome.exitCode());
verify(awsEnv).sdkBaselineEnv("us-east-1", Optional.empty(), Optional.of(session), "000000000000");
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
}
@Test
void rejectsCrossAccountRoleArnBeforeCreatingContainer() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
GlueScriptRunner.Outcome outcome = runner.run(
request("arn:aws:iam::999999999999:role/admin", clock.instant(), Duration.ZERO), progress);
assertTrue(outcome.failure().contains("Cross-account"));
verify(lifecycle, never()).create(any());
}
@Test
void enforcementRejectsRoleThatDoesNotTrustGlue() {
when(config.services().iam().enforcementEnabled()).thenReturn(true);
IamService iamService = mock(IamService.class);
ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class);
IamRole role = new IamRole("role-id", "glue", "/", ROLE, "{}");
when(iamService.findRole("000000000000", "glue")).thenReturn(Optional.of(role));
when(authorizer.refusal(ROLE, "000000000000", "glue.amazonaws.com",
"arn:aws:glue:us-east-1:000000000000:job/etl", List.of()))
.thenReturn(Optional.of("The role " + ROLE + " does not trust glue.amazonaws.com."));
DockerGlueScriptRunner runner = runner("script", iamService, authorizer);
container("script", false, 0L);
GlueScriptRunner.Outcome outcome = runner.run(request(ROLE, clock.instant(), Duration.ZERO), progress);
assertTrue(outcome.failure().contains("does not trust"));
verify(lifecycle, never()).create(any());
}
@Test
void enforcementAllowsRoleThatTrustsGlue() {
when(config.services().iam().enforcementEnabled()).thenReturn(true);
IamService iamService = mock(IamService.class);
ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class);
IamRole role = new IamRole("role-id", "glue", "/", ROLE, "{\"Statement\":[]}");
when(iamService.findRole("000000000000", "glue")).thenReturn(Optional.of(role));
when(authorizer.refusal(ROLE, "000000000000", "glue.amazonaws.com",
"arn:aws:glue:us-east-1:000000000000:job/etl", List.of())).thenReturn(Optional.empty());
SessionCreds session = new SessionCreds("ASIAGLUE", "secret", "token");
when(roleCredentials.forRole(ROLE, "000000000000", "jr_1")).thenReturn(Optional.of(session));
DockerGlueScriptRunner runner = runner("script", iamService, authorizer);
container("script", false, 0L);
inS3("glue-demo", "scripts/job.py", "pass");
GlueScriptRunner.Outcome outcome = runner.run(request(ROLE, clock.instant(), Duration.ZERO), progress);
assertEquals(0, outcome.exitCode());
verify(roleCredentials).unregister("000000000000", "ASIAGLUE");
}
@Test
void customRegionKeepsDeploymentPartitionForRoleName() {
RegionResolver chinaDeployment = new RegionResolver("cn-north-1", "000000000000", "aws-cn");
DockerGlueScriptRunner runner = runner("script", mock(IamService.class), mock(ServiceRoleAuthorizer.class),
chinaDeployment);
container("script", false, 0L);
inS3("glue-demo", "scripts/job.py", "pass");
runner.run(request("glue", "xx-custom-1", clock.instant(), Duration.ZERO), progress);
verify(roleCredentials).forRole("arn:aws-cn:iam::000000000000:role/glue", "000000000000", "jr_1");
}
@Test
void enforcementRejectsRoleArnOutsideCustomRegionPartition() {
when(config.services().iam().enforcementEnabled()).thenReturn(true);
RegionResolver chinaDeployment = new RegionResolver("cn-north-1", "000000000000", "aws-cn");
DockerGlueScriptRunner runner = runner("script", mock(IamService.class), mock(ServiceRoleAuthorizer.class),
chinaDeployment);
container("script", false, 0L);
GlueScriptRunner.Outcome outcome = runner.run(request(ROLE, "xx-custom-1", clock.instant(), Duration.ZERO),
progress);
assertTrue(outcome.failure().contains("another partition"));
verify(lifecycle, never()).create(any());
}
@Test
void stopDuringScriptUploadAbortsStreamAndRemovesContainer() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(docker.copyArchiveToContainerCmd("script")).thenReturn(copy);
when(copy.withTarInputStream(any())).thenAnswer(streaming -> {
InputStream stream = streaming.getArgument(0);
try {
stream.transferTo(OutputStream.nullOutputStream());
} catch (IOException ignored) {
// The stopped writer closes the pipe once it sees the stop.
}
return copy;
});
byte[] content = "print('x')\n".getBytes(StandardCharsets.UTF_8);
S3Object object = new S3Object("glue-demo", "scripts/job.py", content, "application/octet-stream");
InputStream stoppingStream = new InputStream() {
@Override
public int read() {
runner.stop("jr_1");
return -1;
}
@Override
public int read(byte[] b, int off, int len) {
runner.stop("jr_1");
b[off] = 'x';
return 1;
}
};
when(s3.openObject("glue-demo", "scripts/job.py", null))
.thenReturn(new S3Service.ObjectRead(object, stoppingStream));
GlueScriptRunner.Outcome outcome = runner.run(request(Duration.ZERO), progress);
assertTrue(outcome.stopped());
verify(lifecycle, never()).startCreated(anyString(), any());
verify(lifecycle).stopAndRemove("script", null, 0);
}
@Test
void removeLeftoverContainersContinuesWhenOneContainerRemovalFails() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
String owner = ContainerStorageHelper.ownerIdentity(config);
Map<String, String> labels = Map.of(
ContainerStorageHelper.SERVICE_LABEL, DockerGlueScriptRunner.SERVICE,
ContainerStorageHelper.OWNER_LABEL, owner);
Container first = mock(Container.class);
when(first.getId()).thenReturn("c1");
when(first.getLabels()).thenReturn(labels);
Container second = mock(Container.class);
when(second.getId()).thenReturn("c2");
when(second.getLabels()).thenReturn(labels);
when(docker.listContainersCmd().withShowAll(true).withLabelFilter(anyMap()).exec())
.thenReturn(List.of(first, second));
doThrow(new IllegalStateException("daemon busy")).when(lifecycle).removeIfExistsStrict("c1", true);
runner.removeLeftoverContainers();
verify(lifecycle).removeIfExistsStrict("c1", true);
verify(lifecycle).removeIfExistsStrict("c2", true);
}
@Test
void isAvailableReflectsDockerDaemonReachability() {
DockerGlueScriptRunner runner = runner(container("script", false, 0L));
assertTrue(runner.isAvailable());
when(docker.pingCmd().exec()).thenThrow(new IllegalStateException("daemon unreachable"));
assertFalse(runner.isAvailable());
}
private GlueScriptRunner.Run request(Duration timeout) {
return request(clock.instant(), timeout);
}
private GlueScriptRunner.Run request(Instant startedOn, Duration timeout) {
return request(ROLE, startedOn, timeout);
}
private GlueScriptRunner.Run request(String role, Instant startedOn, Duration timeout) {
return request(role, "us-east-1", startedOn, timeout);
}
private GlueScriptRunner.Run request(String role, String region, Instant startedOn, Duration timeout) {
return new GlueScriptRunner.Run("jr_1", "etl", "000000000000", region, role, SCRIPT,
List.of("--JOB_NAME", "etl", "--JOB_RUN_ID", "jr_1"), "glue-image:5", null, startedOn, timeout);
}
// A runner whose script container is "id", running or not, with an exit code once it is not.
private DockerGlueScriptRunner runner(String id) {
return runner(id, null, null);
}
private DockerGlueScriptRunner runner(String id, IamService iamService, ServiceRoleAuthorizer authorizer) {
return runner(id, iamService, authorizer, new RegionResolver("us-east-1", "000000000000"));
}
private DockerGlueScriptRunner runner(String id, IamService iamService, ServiceRoleAuthorizer authorizer,
RegionResolver regionResolver) {
ContainerBuilder builder = mock(ContainerBuilder.class);
when(builder.newContainer(anyString())).thenReturn(spec);
when(builder.resolveImage(anyString())).thenAnswer(image -> image.getArgument(0));
when(builder.resolveDockerNetwork(any())).thenReturn(Optional.empty());
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.create(any())).thenReturn(id);
when(lifecycle.resolveImageForLaunch(anyString(), eq(ImagePullBehavior.DEFAULT), isNull()))
.thenAnswer(pull -> new LaunchImage(pull.getArgument(0), null));
when(awsEnv.flociEndpoint()).thenReturn(ENDPOINT);
return new DockerGlueScriptRunner(builder, lifecycle, logStreamer, awsEnv, roleCredentials, iamService, authorizer,
regionResolver, s3, config, clock, Duration.ZERO);
}
private String container(String id, boolean running, Long exitCode) {
when(docker.inspectContainerCmd(id).exec().getState().getRunning()).thenReturn(running);
when(docker.inspectContainerCmd(id).exec().getState().getExitCodeLong()).thenReturn(exitCode);
return id;
}
// What each tar copied into the container holds, by entry, read as the daemon reads it.
private static Map<String, String> copiedIn(CopyArchiveToContainerCmd copy) {
Map<String, String> copied = new LinkedHashMap<>();
when(copy.withTarInputStream(any())).thenAnswer(streaming -> {
InputStream stream = streaming.getArgument(0);
TarArchiveInputStream tar = new TarArchiveInputStream(stream);
for (TarArchiveEntry entry = tar.getNextEntry(); entry != null; entry = tar.getNextEntry()) {
copied.put(entry.getName(), new String(tar.readAllBytes(), StandardCharsets.UTF_8));
}
stream.transferTo(OutputStream.nullOutputStream());
return copy;
});
return copied;
}
// An object in Floci's S3, which each read opens afresh.
private void inS3(String bucket, String key, String content) {
S3Object object = new S3Object(bucket, key, content.getBytes(StandardCharsets.UTF_8),
"application/octet-stream");
when(s3.openObject(bucket, key, null))
.thenAnswer(read -> new S3Service.ObjectRead(object, new ByteArrayInputStream(object.getData())));
}
}
@@ -1,8 +1,10 @@
package io.floci.aws.services.glue;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -12,6 +14,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class GlueJobRunIntegrationTest {
@@ -19,6 +22,9 @@ class GlueJobRunIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ROLE = "arn:aws:iam::000000000000:role/my-role";
@Inject
EmulatorConfig config;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -59,4 +65,10 @@ class GlueJobRunIntegrationTest {
.statusCode(400)
.body("__type", equalTo("EntityNotFoundException"));
}
@Test
void scriptsAreNotRunUnlessTheRunnerModeIsDocker() {
assertEquals("immediate", config.services().glue().runnerMode());
assertEquals("public.ecr.aws/glue/aws-glue-libs:5", config.services().glue().image());
}
}
@@ -0,0 +1,145 @@
package io.floci.aws.services.glue;
import io.floci.aws.testing.GlueRequests;
import io.floci.aws.testing.IndependentServiceSettingsProfile;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/**
* Job runs in the {@code docker} runner mode, over the wire, with the container replaced by a runner that
* reports how it ended: what a run keeps of its account and Region on the thread that runs its script.
*/
@QuarkusTest
@TestProfile(IndependentServiceSettingsProfile.class)
class GlueScriptRunIntegrationTest {
private record CreatedJob(String region, String name) {
}
private static final String ACCOUNT_ID = "000000000000";
private static final String ROLE = "arn:aws:iam::" + ACCOUNT_ID + ":role/my-role";
private static final String SCRIPT = "s3://glue-demo/scripts/job.py";
@InjectMock
DockerGlueScriptRunner runner;
private final List<Boolean> cancelledSeen = new CopyOnWriteArrayList<>();
private final List<CreatedJob> createdJobs = new CopyOnWriteArrayList<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void runnerEndsWithExitZero() {
cancelledSeen.clear();
when(runner.isAvailable()).thenReturn(true);
when(runner.run(any(), any())).thenAnswer(invocation -> {
GlueScriptRunner.Progress progress = invocation.getArgument(1);
cancelledSeen.add(progress.cancelled());
return GlueScriptRunner.Outcome.exitedWith(0);
});
}
@AfterEach
void deleteCreatedJobs() {
for (CreatedJob job : createdJobs) {
call(job.region(), "DeleteJob", "{ \"JobName\": \"" + job.name() + "\" }").statusCode(200);
}
createdJobs.clear();
}
private static ValidatableResponse call(String region, String action, String body) {
return GlueRequests.call(action, ACCOUNT_ID, region, body);
}
private static String state(String region, String jobName, String runId) {
return call(region, "GetJobRun", "{ \"JobName\": \"" + jobName + "\", \"RunId\": \"" + runId + "\" }")
.statusCode(200).extract().path("JobRun.JobRunState");
}
private static String awaitEnd(String region, String jobName, String runId) throws InterruptedException {
long deadline = System.nanoTime() + Duration.ofSeconds(1).toNanos();
String state = state(region, jobName, runId);
while ("RUNNING".equals(state) && System.nanoTime() < deadline) {
Thread.sleep(10);
state = state(region, jobName, runId);
}
return state;
}
private String startRun(String region, String command) {
String jobName = "script-job-" + UUID.randomUUID().toString().substring(0, 8);
call(region, "CreateJob", """
{ "Name": "%s", "Role": "%s",
"Command": { "Name": "%s", "ScriptLocation": "%s" } }
""".formatted(jobName, ROLE, command, SCRIPT)).statusCode(200);
createdJobs.add(new CreatedJob(region, jobName));
return jobName;
}
@Test
void aSparkJobsScriptRunsAndItsExitSettlesTheRunInTheDefaultRegion() throws InterruptedException {
String jobName = startRun("us-east-1", "glueetl");
String runId = call("us-east-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
.statusCode(200).extract().path("JobRunId");
assertThat(awaitEnd("us-east-1", jobName, runId), equalTo("SUCCEEDED"));
assertThat(cancelledSeen, equalTo(List.of(false)));
}
@Test
void aRunInAnotherRegionIsNotTakenForCancelledOnTheThreadThatRunsItsScript() throws InterruptedException {
String jobName = startRun("eu-west-1", "glueetl");
String runId = call("eu-west-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
.statusCode(200).extract().path("JobRunId");
assertThat(awaitEnd("eu-west-1", jobName, runId), equalTo("SUCCEEDED"));
assertThat(cancelledSeen, equalTo(List.of(false)));
call("eu-west-1", "GetJobRuns", "{ \"JobName\": \"" + jobName + "\" }")
.statusCode(200)
.body("JobRuns.Id", hasItem(runId));
}
@Test
void aPythonShellJobKeepsTheSimulationAndNeverReachesTheRunner() {
String jobName = startRun("us-east-1", "pythonshell");
String runId = call("us-east-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
.statusCode(200).extract().path("JobRunId");
assertThat(state("us-east-1", jobName, runId), equalTo("SUCCEEDED"));
assertThat(cancelledSeen, equalTo(List.of()));
}
@Test
void fallsBackToSimulationWhenDockerIsUnavailable() {
when(runner.isAvailable()).thenReturn(false);
String jobName = startRun("us-east-1", "glueetl");
String runId = call("us-east-1", "StartJobRun", "{ \"JobName\": \"" + jobName + "\" }")
.statusCode(200).extract().path("JobRunId");
assertThat(state("us-east-1", jobName, runId), equalTo("SUCCEEDED"));
assertThat(cancelledSeen, equalTo(List.of()));
}
}
@@ -0,0 +1,528 @@
package io.floci.aws.services.glue;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.glue.model.Job;
import io.floci.aws.services.glue.model.JobCommand;
import io.floci.aws.services.glue.model.JobRun;
import io.floci.aws.services.glue.model.JobRunBookkeeping;
import io.floci.aws.services.glue.schemaregistry.GlueSchemaRegistryService;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService;
import io.floci.aws.testing.InMemoryStorageFactory;
import io.floci.aws.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Glue job runs in the docker runner mode: a script's end, a timeout and a stop settle the run. */
class GlueScriptRunTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/glue";
private static final String SCRIPT = "s3://glue-demo/scripts/job.py";
private GlueService glueService;
private RegionResolver regionResolver;
private MutableClock clock;
private InMemoryStorage<String, JobRun> runStore;
private InMemoryStorage<String, JobRunBookkeeping> bookkeeping;
private FakeRunner runner;
private final List<Runnable> queued = new ArrayList<>();
private GlueJobRunService service;
@BeforeEach
void setUp() {
regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
StorageFactory storageFactory = new InMemoryStorageFactory(ACCOUNT_ID);
glueService = new GlueService(storageFactory, new GlueSchemaRegistryService(storageFactory, regionResolver),
regionResolver, new ResourceGroupsTaggingService(storageFactory),
new KmsService(storageFactory, regionResolver));
clock = new MutableClock();
runStore = new InMemoryStorage<>();
bookkeeping = new InMemoryStorage<>();
runner = new FakeRunner();
service = newService();
}
private GlueJobRunService newService() {
Executor held = queued::add;
return new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock, regionResolver, runner, held,
"glue-image:5", "glue-net");
}
private void createJob(String name, String command, String script, Map<String, String> defaults, Integer timeout) {
Job job = new Job();
job.setName(name);
job.setRole(ROLE);
JobCommand jobCommand = new JobCommand();
jobCommand.setName(command);
jobCommand.setScriptLocation(script);
job.setCommand(jobCommand);
job.setGlueVersion("5.0");
job.setWorkerType("G.1X");
job.setNumberOfWorkers(2);
job.setDefaultArguments(defaults);
job.setTimeout(timeout);
glueService.createJob(job, null, REGION);
}
private void runQueued() {
List<Runnable> tasks = new ArrayList<>(queued);
queued.clear();
tasks.forEach(Runnable::run);
}
private String state(String job, String runId) {
return service.getJobRun(job, runId).getJobRunState();
}
@Test
void runsTheScriptWithTheJobsRoleAndTheMergedArguments() {
createJob("etl", "glueetl", SCRIPT, Map.of("--bucket", "glue-demo", "--mode", "default"), 30);
JobRun overrides = new JobRun();
overrides.setArguments(Map.of("--mode", "run"));
JobRun run = service.startJobRun("etl", null, overrides);
runQueued();
GlueScriptRunner.Run request = runner.requests.getFirst();
assertEquals(run.getId(), request.runId());
assertEquals(ROLE, request.role());
assertEquals(SCRIPT, request.scriptLocation());
assertEquals("glue-image:5", request.image());
assertEquals("glue-net", request.dockerNetwork());
assertEquals(Duration.ofMinutes(30), request.timeout());
assertEquals(ACCOUNT_ID, request.accountId());
assertEquals(REGION, request.region());
Map<String, String> arguments = pairs(request.arguments());
assertEquals("glue-demo", arguments.get("--bucket"));
assertEquals("run", arguments.get("--mode"));
assertEquals("etl", arguments.get("--JOB_NAME"));
assertEquals(run.getId(), arguments.get("--JOB_RUN_ID"));
}
@Test
void staysRunningUntilTheScriptEnds() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
clock.advance(Duration.ofHours(1));
assertEquals("RUNNING", state("etl", run.getId()));
runQueued();
assertEquals("SUCCEEDED", state("etl", run.getId()));
}
@Test
void failsTheRunWithTheScriptsExitCode() {
createJob("etl", "glueetl", SCRIPT, null, null);
runner.outcome = GlueScriptRunner.Outcome.exitedWith(3);
JobRun run = service.startJobRun("etl", null, new JobRun());
runQueued();
JobRun ended = service.getJobRun("etl", run.getId());
assertEquals("FAILED", ended.getJobRunState());
assertTrue(ended.getErrorMessage().contains("code 3"));
}
@Test
void failsTheRunWhenTheScriptCouldNotStart() {
createJob("etl", "glueetl", SCRIPT, null, null);
runner.outcome = GlueScriptRunner.Outcome.couldNotStart("Could not read the script");
JobRun run = service.startJobRun("etl", null, new JobRun());
runQueued();
JobRun ended = service.getJobRun("etl", run.getId());
assertEquals("FAILED", ended.getJobRunState());
assertEquals("Could not read the script", ended.getErrorMessage());
}
@Test
void timesTheRunOutWhenTheRunnerSaysItRanOutOfTime() {
createJob("etl", "glueetl", SCRIPT, null, 5);
runner.outcome = GlueScriptRunner.Outcome.outOfTime();
JobRun run = service.startJobRun("etl", null, new JobRun());
runQueued();
JobRun ended = service.getJobRun("etl", run.getId());
assertEquals("TIMEOUT", ended.getJobRunState());
assertTrue(ended.getErrorMessage().contains("5 minutes"));
}
@Test
void stopsTheRunAndTheScriptsContainer() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
GlueJobRunService.StopResult result = service.batchStopJobRun("etl", List.of(run.getId()));
assertEquals(1, result.stopped().size());
assertEquals("STOPPED", state("etl", run.getId()));
assertEquals(List.of(run.getId()), runner.stopped);
}
@Test
void aScriptThatEndsAfterAStopLeavesTheRunStopped() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
service.batchStopJobRun("etl", List.of(run.getId()));
runQueued();
assertEquals("STOPPED", state("etl", run.getId()));
}
@Test
void doesNotStartTheScriptOfARunThatWasStoppedFirst() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
service.batchStopJobRun("etl", List.of(run.getId()));
runner.cancelledSeen = null;
runQueued();
assertEquals(Boolean.TRUE, runner.cancelledSeen);
}
@Test
void failsARunAnEarlierProcessLeftRunning() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
GlueJobRunService restarted = new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock,
regionResolver, runner, queued::add, "glue-image:5", null);
JobRun read = restarted.getJobRun("etl", run.getId());
assertEquals("FAILED", read.getJobRunState());
}
@Test
void leavesOtherJobsToTheSimulation() {
createJob("shell", "pythonshell", SCRIPT, null, null);
createJob("local", "glueetl", "/tmp/job.py", null, null);
JobRun shell = service.startJobRun("shell", null, new JobRun());
JobRun local = service.startJobRun("local", null, new JobRun());
assertEquals("SUCCEEDED", shell.getJobRunState());
assertEquals("SUCCEEDED", local.getJobRunState());
assertTrue(queued.isEmpty());
assertNull(runner.cancelledSeen);
}
@Test
void aRunOverridesTheJobsTimeoutForTheScript() {
createJob("etl", "glueetl", SCRIPT, null, 30);
JobRun overrides = new JobRun();
overrides.setTimeout(7);
service.startJobRun("etl", null, overrides);
runQueued();
assertEquals(Duration.ofMinutes(7), runner.requests.getFirst().timeout());
}
@Test
void aJobWithoutATimeoutRunsItsScriptUnderTheDefaultCreateJobGives() {
createJob("etl", "glueetl", SCRIPT, null, null);
service.startJobRun("etl", null, new JobRun());
runQueued();
assertEquals(Duration.ofMinutes(glueService.getJob("etl").getTimeout()), runner.requests.getFirst().timeout());
}
@Test
void aRunnerThatThrowsFailsTheRunWithItsMessage() {
createJob("etl", "glueetl", SCRIPT, null, null);
runner.failure = new IllegalStateException("docker is down");
JobRun run = service.startJobRun("etl", null, new JobRun());
runQueued();
JobRun ended = service.getJobRun("etl", run.getId());
assertEquals("FAILED", ended.getJobRunState());
assertEquals("docker is down", ended.getErrorMessage());
}
@Test
void aRunTheExecutorRefusesFailsAtOnce() {
createJob("etl", "glueetl", SCRIPT, null, null);
Executor refusing = task -> {
throw new RejectedExecutionException("shut down");
};
GlueJobRunService stopping = new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock,
regionResolver, runner, refusing, "glue-image:5", null);
JobRun run = stopping.startJobRun("etl", null, new JobRun());
assertEquals("FAILED", run.getJobRunState());
assertEquals("Floci is shutting down", run.getErrorMessage());
}
@Test
void aRunningScriptCountsAgainstMaxConcurrentRuns() {
createJob("etl", "glueetl", SCRIPT, null, null);
service.startJobRun("etl", null, new JobRun());
assertFalse(service.hasCapacity("etl"));
AwsException refused = assertThrows(AwsException.class, () -> service.startJobRun("etl", null, new JobRun()));
assertEquals("ConcurrentRunsExceededException", refused.getErrorCode());
runQueued();
assertTrue(service.hasCapacity("etl"));
}
@Test
void aRunsEndComesAfterTheLastPositionATriggerHasSeen() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
assertTrue(service.completionsAfter("etl", null).isEmpty());
runQueued();
List<GlueRunCompletion> completions = service.completionsAfter("etl", null);
assertEquals(1, completions.size());
assertEquals("SUCCEEDED", completions.getFirst().state());
assertTrue(service.completionsAfter("etl", completions.getFirst().position()).isEmpty());
assertEquals("SUCCEEDED", state("etl", run.getId()));
}
@Test
void deletingTheJobStopsItsScriptAndALateEndChangesNothing() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
service.deleteRuns("etl");
runQueued();
assertEquals(List.of(run.getId()), runner.stopped);
assertEquals(Boolean.TRUE, runner.cancelledSeen);
assertTrue(runStore.get(run.getId()).isEmpty());
}
@Test
void aStoppedRunIsNotStoppedTwiceAndKeepsItsFirstEnd() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
service.batchStopJobRun("etl", List.of(run.getId()));
GlueJobRunService.StopResult again = service.batchStopJobRun("etl", List.of(run.getId()));
assertEquals(1, again.errors().size());
assertEquals(List.of(run.getId()), runner.stopped);
}
@Test
void aScalaJobKeepsTheSimulationBecauseItsScriptIsNotPython() {
createJob("scala", "glueetl", SCRIPT, Map.of("--job-language", "scala"), null);
JobRun run = service.startJobRun("scala", null, new JobRun());
assertEquals("SUCCEEDED", run.getJobRunState());
assertTrue(queued.isEmpty());
}
@Test
void aRunsOwnJobLanguageCanMakeItScalaToo() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun overrides = new JobRun();
overrides.setArguments(Map.of("--job-language", "Scala"));
service.startJobRun("etl", null, overrides);
assertTrue(queued.isEmpty());
}
@Test
void aRunStoppedByAResetOrShutdownRatherThanTheCallerFails() {
createJob("etl", "glueetl", SCRIPT, null, null);
runner.outcome = GlueScriptRunner.Outcome.halted();
JobRun run = service.startJobRun("etl", null, new JobRun());
runQueued();
JobRun ended = service.getJobRun("etl", run.getId());
assertEquals("FAILED", ended.getJobRunState());
assertEquals("Floci stopped the job run before its script ended", ended.getErrorMessage());
}
@Test
void aStreamingJobKeepsTheSimulationEvenWithGlueEtlAndS3Script() {
Job job = new Job();
job.setName("stream");
job.setRole(ROLE);
JobCommand command = new JobCommand();
command.setName("glueetl");
command.setScriptLocation(SCRIPT);
job.setCommand(command);
job.setJobMode("STREAMING");
glueService.createJob(job, null, REGION);
JobRun run = service.startJobRun("stream", null, new JobRun());
assertEquals("SUCCEEDED", run.getJobRunState());
assertTrue(queued.isEmpty());
assertTrue(runner.requests.isEmpty());
}
@Test
void aResetIgnoresAnInFlightScriptRunOutcome() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun run = service.startJobRun("etl", null, new JobRun());
runner.onRun = () -> {
service.beforeReset();
runStore.clear();
bookkeeping.clear();
};
runQueued();
assertTrue(runStore.get(run.getId()).isEmpty());
assertTrue(bookkeeping.get(run.getId()).isEmpty());
}
@Test
void aRunnerErrorStillEndsTheRunFailedAndFreesCapacity() {
createJob("etl", "glueetl", SCRIPT, null, null);
runner.error = new AssertionError("unexpected linkage error");
JobRun run = service.startJobRun("etl", null, new JobRun());
assertThrows(AssertionError.class, this::runQueued);
JobRun ended = service.getJobRun("etl", run.getId());
assertEquals("FAILED", ended.getJobRunState());
assertEquals("unexpected linkage error", ended.getErrorMessage());
assertTrue(service.hasCapacity("etl"));
}
@Test
void queuedRunsWaitInWaitingUntilAConcurrencySlotFrees() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun queuing = new JobRun();
queuing.setJobRunQueuingEnabled(true);
JobRun first = service.startJobRun("etl", null, queuing);
JobRun second = service.startJobRun("etl", null, queuing);
JobRun third = service.startJobRun("etl", null, queuing);
assertEquals("RUNNING", first.getJobRunState());
assertEquals("WAITING", state("etl", second.getId()));
assertEquals("WAITING", state("etl", third.getId()));
assertEquals(1, queued.size());
// Finishing the first run launches only the second, keeping the third in WAITING.
runQueued();
assertEquals("SUCCEEDED", state("etl", first.getId()));
assertEquals("RUNNING", state("etl", second.getId()));
assertEquals("WAITING", state("etl", third.getId()));
assertEquals(1, queued.size());
// Stopping the second run frees the slot and launches the third.
service.batchStopJobRun("etl", List.of(second.getId()));
assertEquals("STOPPED", state("etl", second.getId()));
assertEquals("RUNNING", state("etl", third.getId()));
assertEquals(2, queued.size());
runQueued();
assertEquals("STOPPED", state("etl", second.getId()));
assertEquals("SUCCEEDED", state("etl", third.getId()));
}
@Test
void aWaitingRunLeftByAnEarlierProcessFailsWhenReadAfterRestart() {
createJob("etl", "glueetl", SCRIPT, null, null);
JobRun queuing = new JobRun();
queuing.setJobRunQueuingEnabled(true);
service.startJobRun("etl", null, queuing);
JobRun waitingRun = service.startJobRun("etl", null, queuing);
assertEquals("WAITING", waitingRun.getJobRunState());
GlueJobRunService restarted = new GlueJobRunService(runStore, bookkeeping, glueService, 0, clock,
regionResolver, runner, queued::add, "glue-image:5", null);
JobRun read = restarted.getJobRun("etl", waitingRun.getId());
assertEquals("FAILED", read.getJobRunState());
}
@Test
void fallsBackToSimulationWhenRunnerIsUnavailable() {
createJob("etl", "glueetl", SCRIPT, null, null);
runner.available = false;
JobRun run = service.startJobRun("etl", null, new JobRun());
assertEquals("SUCCEEDED", run.getJobRunState());
assertTrue(queued.isEmpty());
assertTrue(runner.requests.isEmpty());
}
private static Map<String, String> pairs(List<String> arguments) {
Map<String, String> map = new LinkedHashMap<>();
for (int i = 0; i + 1 < arguments.size(); i += 2) {
map.put(arguments.get(i), arguments.get(i + 1));
}
return map;
}
private static final class FakeRunner implements GlueScriptRunner {
final List<Run> requests = new ArrayList<>();
final List<String> stopped = new ArrayList<>();
GlueScriptRunner.Outcome outcome = Outcome.exitedWith(0);
boolean available = true;
Boolean cancelledSeen;
RuntimeException failure;
Error error;
Runnable onRun;
@Override
public boolean isAvailable() {
return available;
}
@Override
public Outcome run(Run run, Progress progress) {
requests.add(run);
if (onRun != null) {
onRun.run();
}
if (error != null) {
throw error;
}
if (failure != null) {
throw failure;
}
cancelledSeen = progress.cancelled();
return cancelledSeen ? Outcome.halted() : outcome;
}
@Override
public void stop(String runId) {
stopped.add(runId);
}
@Override
public void removeLeftoverContainers() {
}
}
}
@@ -0,0 +1,32 @@
package io.floci.aws.services.glue;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.glue.model.JobRunBookkeeping;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JobRunBookkeepingTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void aScriptRunSurvivesStorage() throws Exception {
JobRunBookkeeping bookkeeping = new JobRunBookkeeping();
bookkeeping.setScriptRun(true);
JobRunBookkeeping read = mapper.readValue(mapper.writeValueAsString(bookkeeping), JobRunBookkeeping.class);
assertTrue(read.isScriptRun());
}
@Test
void bookkeepingStoredBeforeScriptRunsExistReadsAsNoScriptRun() throws Exception {
String stored = "{\"completionOrder\":4,\"originRunId\":\"jr_1\",\"workflowRunId\":null}";
JobRunBookkeeping read = mapper.readValue(stored, JobRunBookkeeping.class);
assertFalse(read.isScriptRun());
}
}
@@ -77,6 +77,9 @@ import java.util.Map;
* forwards to its targets, and {@code floci.services.elbv2.backend-keep-alive=false} opens a
* fresh connection to the target for every request it forwards.
* {@code ElbV2BackendNoKeepAliveIntegrationTest} relies on both.</li>
* <li>{@code floci.services.glue.runner-mode=docker} runs a Spark job's script through the Docker
* runner rather than simulating the run. {@code GlueScriptRunIntegrationTest} relies on it, with
* the container replaced by a mock runner.</li>
* </ul>
*
* <p>Each override is inert for the other classes. Each one is read by a single service: the
@@ -84,7 +87,7 @@ import java.util.Map;
* Neptune cluster creation, Route53 VPC association and authorization, CloudFront origin fetches,
* Cognito app client validation, the Scheduler dispatcher, the RDS Data API and Aurora auto-pause,
* Firehose delivery, the Lambda runtime image resolver, the IoT MQTT broker, EC2, SageMaker
* training jobs, Bedrock Runtime, ElastiCache, Service Quotas and the ELBv2 data plane, which
* training jobs, Bedrock Runtime, ElastiCache, Service Quotas, Glue job runs and the ELBv2 data plane, which
* only acts once a class creates a listener or registers a target. Each class is the only one here
* that calls its service, so no override reaches another class. Strict claiming is read for every
* request, but only changes the answer to an RPC-signaled request no protocol claims, which only
@@ -134,7 +137,8 @@ public class IndependentServiceSettingsProfile implements QuarkusTestProfile {
Map.entry("floci.protocols.strict-claiming", "true"),
Map.entry("floci.services.servicequotas.standard-on-demand-vcpus", "7"),
Map.entry("floci.services.elbv2.mock", "false"),
Map.entry("floci.services.elbv2.backend-keep-alive", "false")));
Map.entry("floci.services.elbv2.backend-keep-alive", "false"),
Map.entry("floci.services.glue.runner-mode", "docker")));
overrides.putAll(new YamlConfigSource("runtime-images", """
floci:
services: