mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(glue): run Spark job scripts in a container (#8568)
This commit is contained in:
1 parent
379ac190c3
commit
a06be2d292
13 files changed
+2182
-9
No files matched your search
@@ -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; }
|
||||
}
|
||||
Reference in new issue
Block a user