Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#13555][#13566][#13567][#13587] feat(core): Let job executors decide how to handle job resources through JobContext (#13563)

Jerry Shao371ac4187061
diff --git a/api/src/main/java/org/apache/gravitino/job/JobHandle.java b/api/src/main/java/org/apache/gravitino/job/JobHandle.java
index b6fc536aaf..b957770b60 100644
--- a/api/src/main/java/org/apache/gravitino/job/JobHandle.java
+++ b/api/src/main/java/org/apache/gravitino/job/JobHandle.java
@@ -113,7 +113,7 @@ public interface JobHandle {
/**
* Get the resolved job template that was actually submitted for execution, with placeholders
- * replaced and referenced files downloaded.
+ * replaced. Its executable, scripts, jars, files and archives are the URIs from the template.
*
* @return the runtime job template, or null for jobs run before this field was introduced
*/
diff --git a/api/src/main/java/org/apache/gravitino/job/ShellJobTemplate.java b/api/src/main/java/org/apache/gravitino/job/ShellJobTemplate.java
index 57edcca61c..69b5b30f93 100644
--- a/api/src/main/java/org/apache/gravitino/job/ShellJobTemplate.java
+++ b/api/src/main/java/org/apache/gravitino/job/ShellJobTemplate.java
@@ -31,6 +31,11 @@ import java.util.Objects;
* put in the place where Gravitino server can access them. Current Gravitino can support scripts in
* the local file system, or on the web server (e.g., HTTP, HTTPS, FTP). Distributed file systems
* like HDFS or S3 will be supported in the future.
+ *
+ * <p>Besides a file, the executable of a shell job template can be a command name with no path,
+ * such as {@code python} or {@code bash}. Such a command is not fetched, it is looked up in the
+ * environment the job runs in. The local job executor looks it up on the {@code PATH} of the
+ * Gravitino server process.
*/
public class ShellJobTemplate extends JobTemplate {
diff --git a/clients/client-python/gravitino/api/job/job_handle.py b/clients/client-python/gravitino/api/job/job_handle.py
index 39473e6c4b..abe265615d 100644
--- a/clients/client-python/gravitino/api/job/job_handle.py
+++ b/clients/client-python/gravitino/api/job/job_handle.py
@@ -76,8 +76,8 @@ class JobHandle(ABC):
def runtime_job_template(self) -> Optional[JobTemplate]:
"""Returns the resolved job template that was actually submitted for execution, with
- placeholders replaced and referenced files downloaded, or ``None`` for jobs run before
- this field was introduced.
+ placeholders replaced and its resources kept as the URIs from the template, or ``None``
+ for jobs run before this field was introduced.
"""
raise NotImplementedError("runtime_job_template is not implemented")
diff --git a/common/src/main/java/org/apache/gravitino/dto/job/JobDTO.java b/common/src/main/java/org/apache/gravitino/dto/job/JobDTO.java
index 05745e39ad..c67d577ecb 100644
--- a/common/src/main/java/org/apache/gravitino/dto/job/JobDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/job/JobDTO.java
@@ -99,8 +99,8 @@ public class JobDTO {
* @param finishedAt The time when the job finished execution, or null if the job has not finished
* execution yet.
* @param runtimeJobTemplate The resolved job template that was actually submitted for execution,
- * with placeholders replaced and referenced files downloaded, or null for jobs run before
- * this field was introduced.
+ * with placeholders replaced and its resources kept as the URIs from the template, or null
+ * for jobs run before this field was introduced.
* @param stdout The captured standard output of the job, as a list of lines, or null if output
* was not requested.
* @param stderr The captured standard error output of the job, as a list of lines, or null if
diff --git a/common/src/main/java/org/apache/gravitino/utils/FileFetcher.java b/common/src/main/java/org/apache/gravitino/utils/FileFetcher.java
index 7a64b4e78f..6ddf3ad577 100644
--- a/common/src/main/java/org/apache/gravitino/utils/FileFetcher.java
+++ b/common/src/main/java/org/apache/gravitino/utils/FileFetcher.java
@@ -156,9 +156,10 @@ public final class FileFetcher {
}
Path destPath = destFile.toPath().toAbsolutePath().normalize();
- // Skip if the symlink already points to the correct target.
- if (Files.isSymbolicLink(destPath)
- && Files.readSymbolicLink(destPath).normalize().equals(srcPath)) {
+ // Skip if the destination already is the source file: a symlink to it, or the file itself when
+ // a file already fetched into the directory is fetched again. Replacing the file itself would
+ // turn it into a symlink to itself.
+ if (Files.exists(destPath) && Files.isSameFile(srcPath, destPath)) {
return;
}
// Replace via a temporary symlink + rename to minimize the window where the destination path
diff --git a/common/src/test/java/org/apache/gravitino/utils/TestFileFetcher.java b/common/src/test/java/org/apache/gravitino/utils/TestFileFetcher.java
index 34397512a1..aabaea5de1 100644
--- a/common/src/test/java/org/apache/gravitino/utils/TestFileFetcher.java
+++ b/common/src/test/java/org/apache/gravitino/utils/TestFileFetcher.java
@@ -78,6 +78,25 @@ public class TestFileFetcher {
srcFile.toPath().normalize(), Files.readSymbolicLink(destFile.toPath()).normalize());
}
+ @Test
+ public void testFetchLocalFileOntoItselfKeepsFile() throws Exception {
+ File file = new File(tempDir, "run.sh");
+ Files.writeString(file.toPath(), "echo hi");
+
+ // Fetching a file into the place where it already is must not replace it with a symlink.
+ FileFetcher.get().fetchFileFromUri(file.toURI().toString(), file, 10, null);
+ Assertions.assertFalse(Files.isSymbolicLink(file.toPath()));
+ Assertions.assertEquals("echo hi", Files.readString(file.toPath()));
+
+ // Nor fetching a symlink created by an earlier fetch onto itself.
+ File srcFile = new File(tempDir, "source");
+ Files.writeString(srcFile.toPath(), "source content");
+ File destFile = new File(tempDir, "dest");
+ FileFetcher.get().fetchFileFromUri(srcFile.toURI().toString(), destFile, 10, null);
+ FileFetcher.get().fetchFileFromUri(destFile.toURI().toString(), destFile, 10, null);
+ Assertions.assertEquals("source content", Files.readString(destFile.toPath()));
+ }
+
@Test
public void testOpaqueFileUriWithNullPathShouldFail() {
// An opaque file URI (no authority/path) must fail with a clear IOException, not a raw NPE.
diff --git a/core/src/main/java/org/apache/gravitino/connector/job/JobContext.java b/core/src/main/java/org/apache/gravitino/connector/job/JobContext.java
new file mode 100644
index 0000000000..daacdf3d70
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/connector/job/JobContext.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.connector.job;
+
+import com.google.common.base.Preconditions;
+import java.io.File;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.job.JobTemplate;
+
+/**
+ * The context of a job run, which Gravitino passes to the job executor together with the runtime
+ * job template when it submits the job.
+ */
+@DeveloperApi
+public final class JobContext {
+
+ private final long jobId;
+
+ private final String metalake;
+
+ private final File stagingDir;
+
+ /**
+ * Creates the context of a job run.
+ *
+ * @param jobId the Gravitino job id
+ * @param metalake the metalake the job belongs to
+ * @param stagingDir the staging directory of the job
+ */
+ public JobContext(long jobId, String metalake, File stagingDir) {
+ Preconditions.checkArgument(StringUtils.isNotBlank(metalake), "metalake must not be blank");
+ Preconditions.checkArgument(stagingDir != null, "stagingDir must not be null");
+ this.jobId = jobId;
+ this.metalake = metalake;
+ this.stagingDir = stagingDir;
+ }
+
+ /**
+ * Returns the Gravitino job id, which is unique across all metalakes. It is not the job execution
+ * id that the job executor returns from {@link JobExecutor#submitJob(JobContext, JobTemplate)}.
+ *
+ * @return the Gravitino job id
+ */
+ public long jobId() {
+ return jobId;
+ }
+
+ /**
+ * Returns the metalake the job belongs to.
+ *
+ * @return the metalake name
+ */
+ public String metalake() {
+ return metalake;
+ }
+
+ /**
+ * Returns a directory on the Gravitino server dedicated to this job, where a job executor can
+ * localize the job's resources, for example with {@link JobResourceUtils#localizeJobTemplate}.
+ * Gravitino creates it before submitting the job, removes it right away if the job fails to be
+ * submitted, and otherwise cleans it up some time after the job finishes ({@code
+ * gravitino.job.stagingDirKeepTimeInMs}).
+ *
+ * @return the staging directory of the job
+ */
+ public File stagingDir() {
+ return stagingDir;
+ }
+
+ @Override
+ public String toString() {
+ return "JobContext{jobId="
+ + jobId
+ + ", metalake="
+ + metalake
+ + ", stagingDir="
+ + stagingDir
+ + "}";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java b/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java
index 88dcbd4a57..32fd9d6783 100644
--- a/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java
+++ b/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java
@@ -45,19 +45,49 @@ public interface JobExecutor extends Closeable {
void initialize(Map<String, String> configs);
/**
- * Submit a job with the given name and job template to the external job runner.
+ * Submit a job to the external job runner.
*
* <p>The returned job identifier is unique in the external job runner, and can be used to track
* the job status or cancel it later.
*
- * <p>The placeholders in the job template has already been replaced with the actual values before
- * calling this method. So the implementors can directly use this job template to submit the job
- * to the external job runner.
+ * <p>The placeholders in the job template have already been replaced with the actual values, but
+ * its resources, that is its executable, scripts, jars, files and archives, are still the URIs
+ * given in the template. The job executor decides how to handle them: fetch them to the Gravitino
+ * server, for example with {@link JobResourceUtils#localizeJobTemplate} into {@link
+ * JobContext#stagingDir()}, or pass the URIs on to the external job runner.
*
- * @param jobTemplate The job template containing the job configuration and parameters.
+ * <p>The default implementation localizes the job template into {@link JobContext#stagingDir()}
+ * and delegates to {@link #submitJob(JobTemplate)}, so a job executor that implements only that
+ * method keeps receiving local paths.
+ *
+ * @param context The context of the job run.
+ * @param jobTemplate The runtime job template, whose resources are URIs.
* @return A unique identifier for the submitted job.
*/
- String submitJob(JobTemplate jobTemplate);
+ default String submitJob(JobContext context, JobTemplate jobTemplate) {
+ return submitJob(JobResourceUtils.localizeJobTemplate(jobTemplate, context.stagingDir()));
+ }
+
+ /**
+ * Submit a job whose resources have already been fetched to the Gravitino server.
+ *
+ * <p>Gravitino calls {@link #submitJob(JobContext, JobTemplate)}, whose default implementation
+ * localizes the job template and calls this method. A job executor must implement one of the two
+ * methods.
+ *
+ * @param jobTemplate The runtime job template, whose resources are paths of local files.
+ * @return A unique identifier for the submitted job.
+ * @throws UnsupportedOperationException if the job executor implements {@link
+ * #submitJob(JobContext, JobTemplate)} instead.
+ * @deprecated Implement {@link #submitJob(JobContext, JobTemplate)} instead, which lets the job
+ * executor decide how to handle the job resources. This method will be removed in a future
+ * release.
+ */
+ @Deprecated
+ default String submitJob(JobTemplate jobTemplate) {
+ throw new UnsupportedOperationException(
+ getClass().getName() + " doesn't support submitJob(JobTemplate)");
+ }
/**
* Get a snapshot of the job's execution state by its unique identifier, including its status and
diff --git a/core/src/main/java/org/apache/gravitino/connector/job/JobResourceUtils.java b/core/src/main/java/org/apache/gravitino/connector/job/JobResourceUtils.java
new file mode 100644
index 0000000000..751912b83e
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/connector/job/JobResourceUtils.java
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.connector.job;
+
+import com.google.common.base.Preconditions;
+import java.io.File;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.job.JobTemplate;
+import org.apache.gravitino.job.ShellJobTemplate;
+import org.apache.gravitino.job.SparkJobTemplate;
+import org.apache.gravitino.utils.FileFetcher;
+
+/**
+ * Utilities to fetch the resources of a runtime job template, that is its executable, scripts,
+ * jars, files and archives, into a local directory. Job executors that run jobs on the Gravitino
+ * server use {@link #localizeJobTemplate} to get a job template whose resources are local files
+ * before launching a job.
+ */
+@DeveloperApi
+public final class JobResourceUtils {
+
+ /** The connect and read timeout in milliseconds used to fetch a remote file. */
+ public static final int DEFAULT_FETCH_TIMEOUT_IN_MS = 30 * 1000;
+
+ private JobResourceUtils() {}
+
+ /**
+ * Localizes a runtime job template: fetches all its resources into a directory, and returns a
+ * copy of the job template whose resources point to the fetched local files. The other fields of
+ * the job template are kept as they are.
+ *
+ * @param jobTemplate the runtime job template, whose resources are the URIs to fetch
+ * @param dir the directory to fetch the resources into
+ * @return the localized job template, whose resources are the paths of the fetched local files
+ * @throws IllegalArgumentException if a resource has no file name, two different resources have
+ * the same file name, or a script has the file name of a command-name executable. Nothing is
+ * fetched in these cases.
+ * @throws RuntimeException if a resource cannot be fetched
+ */
+ public static JobTemplate localizeJobTemplate(JobTemplate jobTemplate, File dir) {
+ checkFileNames(jobTemplate);
+
+ if (jobTemplate instanceof ShellJobTemplate) {
+ ShellJobTemplate shellJobTemplate = (ShellJobTemplate) jobTemplate;
+ // A command name is looked up in the environment the job runs in, not fetched.
+ String executable =
+ isCommandName(shellJobTemplate.executable())
+ ? shellJobTemplate.executable()
+ : fetchFile(shellJobTemplate.executable(), dir, DEFAULT_FETCH_TIMEOUT_IN_MS);
+ return ShellJobTemplate.builder()
+ .withName(shellJobTemplate.name())
+ .withComment(shellJobTemplate.comment())
+ .withExecutable(executable)
+ .withArguments(shellJobTemplate.arguments())
+ .withEnvironments(shellJobTemplate.environments())
+ .withCustomFields(shellJobTemplate.customFields())
+ .withScripts(fetchFiles(shellJobTemplate.scripts(), dir, DEFAULT_FETCH_TIMEOUT_IN_MS))
+ .build();
+ }
+
+ if (jobTemplate instanceof SparkJobTemplate) {
+ SparkJobTemplate sparkJobTemplate = (SparkJobTemplate) jobTemplate;
+ return SparkJobTemplate.builder()
+ .withName(sparkJobTemplate.name())
+ .withComment(sparkJobTemplate.comment())
+ .withExecutable(
+ fetchFile(sparkJobTemplate.executable(), dir, DEFAULT_FETCH_TIMEOUT_IN_MS))
+ .withArguments(sparkJobTemplate.arguments())
+ .withEnvironments(sparkJobTemplate.environments())
+ .withCustomFields(sparkJobTemplate.customFields())
+ .withClassName(sparkJobTemplate.className())
+ .withJars(fetchFiles(sparkJobTemplate.jars(), dir, DEFAULT_FETCH_TIMEOUT_IN_MS))
+ .withFiles(fetchFiles(sparkJobTemplate.files(), dir, DEFAULT_FETCH_TIMEOUT_IN_MS))
+ .withArchives(fetchFiles(sparkJobTemplate.archives(), dir, DEFAULT_FETCH_TIMEOUT_IN_MS))
+ .withConfigs(sparkJobTemplate.configs())
+ .build();
+ }
+
+ throw new IllegalArgumentException("Unsupported job type: " + jobTemplate.jobType());
+ }
+
+ /**
+ * Whether the executable of a shell job template is a command name, such as {@code python}: a
+ * name with no scheme and no path separator, which is looked up in the environment the job runs
+ * in, for example on the {@code PATH} of the process that launches it, instead of a file to
+ * fetch.
+ *
+ * @param executable the executable of a shell job template
+ * @return true if the executable is a command name
+ */
+ public static boolean isCommandName(String executable) {
+ if (StringUtils.isBlank(executable)
+ || executable.equals(".")
+ || executable.equals("..")
+ || executable.indexOf('/') >= 0
+ || executable.indexOf(File.separatorChar) >= 0) {
+ return false;
+ }
+ try {
+ return new URI(executable).getScheme() == null;
+ } catch (URISyntaxException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Fetches the files of the given URIs into a directory.
+ *
+ * @param uris the URIs of the files
+ * @param dir the directory to fetch the resources into
+ * @param timeoutInMs the connect and read timeout in milliseconds for a remote file
+ * @return the paths of the fetched local files, in the order of the URIs
+ * @throws RuntimeException if a file cannot be fetched
+ */
+ public static List<String> fetchFiles(List<String> uris, File dir, int timeoutInMs) {
+ return uris.stream().map(uri -> fetchFile(uri, dir, timeoutInMs)).collect(Collectors.toList());
+ }
+
+ /**
+ * Fetches the file of the given URI into a directory, keeping its file name.
+ *
+ * @param uri the URI of the file, a URI without scheme is a local path
+ * @param dir the directory to fetch the file into
+ * @param timeoutInMs the connect and read timeout in milliseconds for a remote file
+ * @return the path of the fetched local file
+ * @throws IllegalArgumentException if the URI has no file name
+ * @throws RuntimeException if the file cannot be fetched
+ */
+ public static String fetchFile(String uri, File dir, int timeoutInMs) {
+ File destFile = new File(dir, fileNameOf(uri));
+ try {
+ return FileFetcher.get()
+ .fetchFileFromUri(
+ uri,
+ destFile,
+ timeoutInMs,
+ null /* hadoopConf: job file URIs never use the hdfs scheme */);
+ } catch (Exception e) {
+ throw new RuntimeException(String.format("Failed to fetch file from URI %s", uri), e);
+ }
+ }
+
+ /**
+ * Checks the file names the resources of a job template get in the directory they are fetched
+ * into, before anything is fetched: every resource is stored under the file name of its URI, so
+ * two resources with the same file name would silently overwrite each other.
+ */
+ private static void checkFileNames(JobTemplate jobTemplate) {
+ List<String> uris = new ArrayList<>();
+ String commandName = null;
+ if (jobTemplate instanceof ShellJobTemplate) {
+ ShellJobTemplate shellJobTemplate = (ShellJobTemplate) jobTemplate;
+ if (isCommandName(shellJobTemplate.executable())) {
+ commandName = shellJobTemplate.executable();
+ } else {
+ uris.add(shellJobTemplate.executable());
+ }
+ uris.addAll(shellJobTemplate.scripts());
+ } else if (jobTemplate instanceof SparkJobTemplate) {
+ SparkJobTemplate sparkJobTemplate = (SparkJobTemplate) jobTemplate;
+ uris.add(sparkJobTemplate.executable());
+ uris.addAll(sparkJobTemplate.jars());
+ uris.addAll(sparkJobTemplate.files());
+ uris.addAll(sparkJobTemplate.archives());
+ }
+
+ Map<String, String> uriByFileName = new HashMap<>();
+ for (String uri : uris) {
+ String fileName = fileNameOf(uri);
+ // The command is run from the PATH, so a fetched file of the same name is never the one
+ // that runs, although the template looks like it should be.
+ Preconditions.checkArgument(
+ !fileName.equals(commandName),
+ "The executable %s of job template %s is a command name, which is not fetched but looked "
+ + "up where the job runs, while the resource %s with the same file name is fetched. "
+ + "To run the fetched file, use its URI or absolute path as the executable",
+ commandName,
+ jobTemplate.name(),
+ uri);
+
+ String previousUri = uriByFileName.putIfAbsent(fileName, uri);
+ Preconditions.checkArgument(
+ previousUri == null || previousUri.equals(uri),
+ "The resources %s and %s of job template %s have the same file name %s, and would "
+ + "overwrite each other when they are fetched. Give them different file names",
+ previousUri,
+ uri,
+ jobTemplate.name(),
+ fileName);
+ }
+ }
+
+ /** Returns the file name a resource gets when it is fetched: the last segment of its path. */
+ private static String fileNameOf(String uri) {
+ String path;
+ try {
+ path = new URI(uri).getPath();
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException(String.format("The resource URI %s is invalid", uri), e);
+ }
+
+ String fileName = path == null ? null : new File(path).getName();
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(fileName),
+ "The resource URI %s has no file name, it must point to a file",
+ uri);
+ return fileName;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java b/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java
index 46b5c35554..821a5d3395 100644
--- a/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java
+++ b/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java
@@ -28,6 +28,7 @@ import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
+import org.apache.gravitino.connector.job.JobContext;
import org.apache.gravitino.connector.job.JobExecutor;
import org.apache.gravitino.job.local.LocalJobExecutor;
import org.apache.gravitino.job.local.LocalJobExecutorConfigs;
@@ -115,5 +116,43 @@ public class JobExecutorFactory {
+ "Gravitino uses to track the jobs. It was likely built against an older version of "
+ "Gravitino, rebuild it against this version and implement the method.",
jobExecutorClass.getName());
+
+ // Both submit methods have a default implementation, one delegating to the other, so a job
+ // executor must implement at least one of them.
+ Preconditions.checkArgument(
+ implementsMethod(jobExecutorClass, "submitJob", JobContext.class, JobTemplate.class)
+ || implementsMethod(jobExecutorClass, "submitJob", JobTemplate.class),
+ "Job executor %s implements neither JobExecutor#submitJob(JobContext, JobTemplate) nor "
+ + "JobExecutor#submitJob(JobTemplate), implement one of them to submit jobs.",
+ jobExecutorClass.getName());
+
+ // LocalJobExecutor submits jobs through submitJob(JobContext, JobTemplate) and never calls the
+ // deprecated submitJob(JobTemplate), so a subclass that overrides only the latter would have
+ // its override silently skipped.
+ Preconditions.checkArgument(
+ !LocalJobExecutor.class.isAssignableFrom(jobExecutorClass)
+ || !implementsMethod(jobExecutorClass, "submitJob", JobTemplate.class)
+ || declaringClassOf(jobExecutorClass, "submitJob", JobContext.class, JobTemplate.class)
+ != LocalJobExecutor.class,
+ "Job executor %s extends LocalJobExecutor and overrides the deprecated "
+ + "JobExecutor#submitJob(JobTemplate), which LocalJobExecutor never calls. Override "
+ + "submitJob(JobContext, JobTemplate) instead.",
+ jobExecutorClass.getName());
+ }
+
+ private static boolean implementsMethod(
+ Class<?> jobExecutorClass, String name, Class<?>... parameterTypes) {
+ // An inherited default method of the interface is declared by the interface itself.
+ return declaringClassOf(jobExecutorClass, name, parameterTypes) != JobExecutor.class;
+ }
+
+ private static Class<?> declaringClassOf(
+ Class<?> jobExecutorClass, String name, Class<?>... parameterTypes) {
+ try {
+ return jobExecutorClass.getMethod(name, parameterTypes).getDeclaringClass();
+ } catch (NoSuchMethodException e) {
+ // Never happens for a JobExecutor, as the interface declares the method.
+ throw new IllegalArgumentException(e);
+ }
}
}
diff --git a/core/src/main/java/org/apache/gravitino/job/JobManager.java b/core/src/main/java/org/apache/gravitino/job/JobManager.java
index fb1c190b33..b789078389 100644
--- a/core/src/main/java/org/apache/gravitino/job/JobManager.java
+++ b/core/src/main/java/org/apache/gravitino/job/JobManager.java
@@ -54,6 +54,7 @@ import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.connector.job.JobContext;
import org.apache.gravitino.connector.job.JobExecutionInfo;
import org.apache.gravitino.connector.job.JobExecutor;
import org.apache.gravitino.dto.job.JobTemplateDTO;
@@ -516,11 +517,11 @@ public class JobManager implements JobOperationDispatcher {
e);
}
- // Create a JobTemplate by replacing the template parameters with the jobConf values, and
- // also downloading any necessary files from the URIs specified in the job template.
+ // Create a JobTemplate by replacing the template parameters with the jobConf values. Its
+ // resources are kept as URIs, the job executor decides how to handle them.
JobTemplate jobTemplate;
try {
- jobTemplate = jobTemplateResolver.resolve(jobConf, jobStagingDir);
+ jobTemplate = jobTemplateResolver.resolve(jobConf);
} catch (RuntimeException e) {
deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);
throw e;
@@ -548,7 +549,8 @@ public class JobManager implements JobOperationDispatcher {
// Submit the job template to the job executor
String jobExecutionId;
try {
- jobExecutionId = jobExecutor.submitJob(jobTemplate);
+ jobExecutionId =
+ jobExecutor.submitJob(new JobContext(jobId, metalake, jobStagingDir), jobTemplate);
} catch (IllegalArgumentException e) {
// The job executor rejects the job because it cannot be launched, for example, a required
// configuration is missing. Rethrow it as is so the caller gets the original reason.
@@ -557,7 +559,10 @@ public class JobManager implements JobOperationDispatcher {
} catch (Exception e) {
deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);
throw new RuntimeException(
- String.format("Failed to submit job template %s for execution", jobTemplate), e);
+ String.format(
+ "Failed to submit job %s of job template %s for execution: %s",
+ jobId, jobTemplateName, e.getMessage()),
+ e);
}
// Create a new JobEntity to represent the job
diff --git a/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java b/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java
index 158af7b9fa..3c2dc33d07 100644
--- a/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java
+++ b/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java
@@ -19,9 +19,6 @@
package org.apache.gravitino.job;
-import com.google.common.annotations.VisibleForTesting;
-import java.io.File;
-import java.net.URI;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
@@ -31,15 +28,16 @@ import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
+import org.apache.gravitino.connector.job.JobResourceUtils;
import org.apache.gravitino.meta.JobTemplateEntity;
-import org.apache.gravitino.utils.FileFetcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Resolves a job template into the runtime job template of a job run: the template with its
- * placeholders replaced with the job configuration, and its executable, scripts, jars, files and
- * archives fetched into the job's staging directory.
+ * placeholders replaced with the job configuration. The resources of the runtime job template, that
+ * is its executable, scripts, jars, files and archives, are kept as URIs; fetch them with {@link
+ * JobResourceUtils} where needed.
*
* <p>Creating a resolver parses and validates the template's placeholders, so a resolver always
* holds a valid template, and the placeholders are parsed only once per job run. To only validate a
@@ -49,8 +47,6 @@ public final class JobTemplateResolver {
private static final Logger LOG = LoggerFactory.getLogger(JobTemplateResolver.class);
- private static final int FETCH_TIMEOUT_IN_MS = 30 * 1000; // 30 seconds
-
private final JobTemplateEntity jobTemplateEntity;
// The parameters of the template, each mapped to its default value, or to an empty optional if
@@ -114,96 +110,61 @@ public final class JobTemplateResolver {
}
/**
- * Resolves the template into the runtime job template of a job run.
+ * Resolves the template into the runtime job template of a job run. It fetches nothing, the
+ * resources of the runtime job template are the resolved URIs.
*
* @param jobConf the job configuration, may be null
- * @param stagingDir the staging directory of the job, where the files are fetched to
* @return the runtime job template
* @throws IllegalArgumentException if a required parameter has no value, or the resolved
* environments, custom fields or configs contain duplicate keys
- * @throws RuntimeException if a file cannot be fetched
*/
- public JobTemplate resolve(@Nullable Map<String, String> jobConf, File stagingDir) {
+ public JobTemplate resolve(@Nullable Map<String, String> jobConf) {
String name = jobTemplateEntity.name();
String comment = jobTemplateEntity.comment();
JobTemplateEntity.TemplateContent content = jobTemplateEntity.templateContent();
Map<String, String> conf = jobConf == null ? Collections.emptyMap() : jobConf;
- // Check every parameter before fetching any file, so a missing value fails without downloading
- // anything and reports all the missing parameters at once.
+ // Check every parameter first, so all the missing parameters are reported at once.
checkRequiredParameters(conf);
Function<String, String> resolver =
value -> JobTemplatePlaceholderUtils.replacePlaceholders(value, conf, parameters);
- // Resolve everything before fetching anything, so a template that resolves to duplicate keys
- // is rejected without downloading a file first.
- String executableUri = resolver.apply(content.executable());
+ String executable = resolver.apply(content.executable());
List<String> args = resolveList(content.arguments(), resolver);
Map<String, String> environments = resolveMap(content.environments(), resolver, "environments");
Map<String, String> customFields = resolveMap(content.customFields(), resolver, "customFields");
if (content.jobType() == JobTemplate.JobType.SHELL) {
- List<String> scriptUris = resolveList(content.scripts(), resolver);
-
return ShellJobTemplate.builder()
.withName(name)
.withComment(comment)
- .withExecutable(fetchFileFromUri(executableUri, stagingDir, FETCH_TIMEOUT_IN_MS))
+ .withExecutable(executable)
.withArguments(args)
.withEnvironments(environments)
.withCustomFields(customFields)
- .withScripts(fetchFilesFromUri(scriptUris, stagingDir, FETCH_TIMEOUT_IN_MS))
+ .withScripts(resolveList(content.scripts(), resolver))
.build();
}
if (content.jobType() == JobTemplate.JobType.SPARK) {
- String className = resolver.apply(content.className());
- List<String> jarUris = resolveList(content.jars(), resolver);
- List<String> fileUris = resolveList(content.files(), resolver);
- List<String> archiveUris = resolveList(content.archives(), resolver);
- Map<String, String> configs = resolveMap(content.configs(), resolver, "configs");
-
return SparkJobTemplate.builder()
.withName(name)
.withComment(comment)
- .withExecutable(fetchFileFromUri(executableUri, stagingDir, FETCH_TIMEOUT_IN_MS))
+ .withExecutable(executable)
.withArguments(args)
.withEnvironments(environments)
.withCustomFields(customFields)
- .withClassName(className)
- .withJars(fetchFilesFromUri(jarUris, stagingDir, FETCH_TIMEOUT_IN_MS))
- .withFiles(fetchFilesFromUri(fileUris, stagingDir, FETCH_TIMEOUT_IN_MS))
- .withArchives(fetchFilesFromUri(archiveUris, stagingDir, FETCH_TIMEOUT_IN_MS))
- .withConfigs(configs)
+ .withClassName(resolver.apply(content.className()))
+ .withJars(resolveList(content.jars(), resolver))
+ .withFiles(resolveList(content.files(), resolver))
+ .withArchives(resolveList(content.archives(), resolver))
+ .withConfigs(resolveMap(content.configs(), resolver, "configs"))
.build();
}
throw new IllegalArgumentException("Unsupported job type: " + content.jobType());
}
- @VisibleForTesting
- static List<String> fetchFilesFromUri(List<String> uris, File stagingDir, int timeoutInMs) {
- return uris.stream()
- .map(uri -> fetchFileFromUri(uri, stagingDir, timeoutInMs))
- .collect(Collectors.toList());
- }
-
- @VisibleForTesting
- static String fetchFileFromUri(String uri, File stagingDir, int timeoutInMs) {
- try {
- URI fileUri = new URI(uri);
- File destFile = new File(stagingDir, new File(fileUri.getPath()).getName());
- return FileFetcher.get()
- .fetchFileFromUri(
- uri,
- destFile,
- timeoutInMs,
- null /* hadoopConf: job file URIs never use the hdfs scheme */);
- } catch (Exception e) {
- throw new RuntimeException(String.format("Failed to fetch file from URI %s", uri), e);
- }
- }
-
private void checkRequiredParameters(Map<String, String> jobConf) {
Set<String> missing = JobTemplatePlaceholderUtils.findMissingParameters(parameters, jobConf);
if (!missing.isEmpty()) {
diff --git a/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java b/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java
index 9c42bad643..1b1a7cf37d 100644
--- a/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java
+++ b/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java
@@ -38,6 +38,7 @@ import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
+import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
@@ -68,9 +69,10 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.tuple.Pair;
+import org.apache.gravitino.connector.job.JobContext;
import org.apache.gravitino.connector.job.JobExecutionInfo;
import org.apache.gravitino.connector.job.JobExecutor;
+import org.apache.gravitino.connector.job.JobResourceUtils;
import org.apache.gravitino.exceptions.NoSuchJobException;
import org.apache.gravitino.job.JobHandle;
import org.apache.gravitino.job.JobTemplate;
@@ -93,6 +95,19 @@ import org.slf4j.LoggerFactory;
*/
public class LocalJobExecutor implements JobExecutor {
+ /** A submitted job waiting to run, with the directory it runs in. */
+ private static final class QueuedJob {
+ private final String jobId;
+ private final JobTemplate jobTemplate;
+ private final File workingDir;
+
+ private QueuedJob(String jobId, JobTemplate jobTemplate, File workingDir) {
+ this.jobId = jobId;
+ this.jobTemplate = jobTemplate;
+ this.workingDir = workingDir;
+ }
+ }
+
private static final Logger LOG = LoggerFactory.getLogger(LocalJobExecutor.class);
private static final String LOCAL_JOB_PREFIX = "local-job-";
@@ -133,7 +148,7 @@ public class LocalJobExecutor implements JobExecutor {
private Map<String, String> configs;
- private BlockingQueue<Pair<String, JobTemplate>> waitingQueue;
+ private BlockingQueue<QueuedJob> waitingQueue;
private ExecutorService jobExecutorService;
@@ -310,27 +325,34 @@ public class LocalJobExecutor implements JobExecutor {
}
@Override
- public String submitJob(JobTemplate jobTemplate) {
- // Validate the job can be launched before queueing it, so that a misconfiguration is reported
- // to the caller directly instead of only failing the job asynchronously in the worker thread.
+ public String submitJob(JobContext context, JobTemplate jobTemplate) {
+ // Validate the job can be launched before fetching its resources and queueing it, so that a
+ // misconfiguration is reported to the caller directly instead of only failing the job
+ // asynchronously in the worker thread.
if (jobTemplate instanceof SparkJobTemplate) {
SparkProcessBuilder.resolveSparkSubmit(configs);
}
+ // The job runs in its staging directory, next to its localized resources.
+ File workingDir = context.stagingDir();
+ JobTemplate localizedJobTemplate =
+ JobResourceUtils.localizeJobTemplate(jobTemplate, workingDir);
+
String newJobId = ownedJobIdPrefix + UUID.randomUUID();
- Pair<String, JobTemplate> jobPair = Pair.of(newJobId, jobTemplate);
+ QueuedJob queuedJob = new QueuedJob(newJobId, localizedJobTemplate, workingDir);
synchronized (lock) {
- // Add the job template to the waiting queue
- if (!waitingQueue.offer(jobPair)) {
- throw new IllegalStateException("Waiting queue is full, cannot submit job: " + jobTemplate);
+ // Add the job to the waiting queue
+ if (!waitingQueue.offer(queuedJob)) {
+ throw new IllegalStateException(
+ "Waiting queue is full, cannot submit job: " + localizedJobTemplate);
}
jobInfos.put(newJobId, JobExecutionInfo.of(JobHandle.Status.QUEUED));
}
// Written only once the job is accepted, so a rejected submission leaves no index behind.
- writeOutputIndex(newJobId, jobTemplate);
+ writeOutputIndex(newJobId, workingDir);
return newJobId;
}
@@ -368,7 +390,7 @@ public class LocalJobExecutor implements JobExecutor {
// If the job is queued.
if (info.status() == JobHandle.Status.QUEUED) {
- waitingQueue.removeIf(p -> p.getLeft().equals(jobId));
+ waitingQueue.removeIf(queuedJob -> queuedJob.jobId.equals(jobId));
finishJob(jobId, JobHandle.Status.CANCELLED);
LOG.info("Job {} is cancelled from the waiting queue", jobId);
return;
@@ -449,11 +471,9 @@ public class LocalJobExecutor implements JobExecutor {
jobInfos.clear();
}
- public void runJob(Pair<String, JobTemplate> jobPair) {
+ private void runJob(QueuedJob queuedJob) {
+ String jobId = queuedJob.jobId;
try {
- String jobId = jobPair.getLeft();
- JobTemplate jobTemplate = jobPair.getRight();
-
Process process;
synchronized (lock) {
// This happens when the job is cancelled before it starts.
@@ -463,7 +483,8 @@ public class LocalJobExecutor implements JobExecutor {
return;
}
- LocalProcessBuilder processBuilder = LocalProcessBuilder.create(jobTemplate, configs);
+ LocalProcessBuilder processBuilder =
+ LocalProcessBuilder.create(queuedJob.jobTemplate, queuedJob.workingDir, configs);
process = processBuilder.start();
runningProcesses.put(jobId, process);
jobInfos.put(jobId, info.started(Instant.now()));
@@ -494,23 +515,23 @@ public class LocalJobExecutor implements JobExecutor {
LOG.error("Error while executing job", e);
// If an error occurs, we should mark the job as failed
synchronized (lock) {
- finishJob(jobPair.getLeft(), JobHandle.Status.FAILED);
+ finishJob(jobId, JobHandle.Status.FAILED);
}
}
- runningProcesses.remove(jobPair.getLeft());
+ runningProcesses.remove(jobId);
}
public void pollJob() {
while (!finished) {
try {
- Pair<String, JobTemplate> jobPair = waitingQueue.poll(3000, TimeUnit.MILLISECONDS);
- if (jobPair == null) {
+ QueuedJob queuedJob = waitingQueue.poll(3000, TimeUnit.MILLISECONDS);
+ if (queuedJob == null) {
// If no job is available, continue to the next iteration
continue;
}
- jobExecutorService.submit(() -> runJob(jobPair));
+ jobExecutorService.submit(() -> runJob(queuedJob));
} catch (InterruptedException e) {
LOG.warn("Polling job interrupted");
@@ -629,15 +650,11 @@ public class LocalJobExecutor implements JobExecutor {
return true;
}
- private void writeOutputIndex(String jobId, JobTemplate jobTemplate) {
+ private void writeOutputIndex(String jobId, File jobWorkingDir) {
// The job is already queued, so any failure here must not fail the submission: the caller
// would then clean up the staging directory of a job that still runs.
try {
- Path workingDir =
- LocalProcessBuilder.resolveWorkingDirectory(jobTemplate)
- .toPath()
- .toAbsolutePath()
- .normalize();
+ Path workingDir = jobWorkingDir.toPath().toAbsolutePath().normalize();
if (!workingDir.startsWith(stagingRoot) || workingDir.equals(stagingRoot)) {
LOG.warn(
"The working directory {} of job {} is not under the job staging directory {}, so "
diff --git a/core/src/main/java/org/apache/gravitino/job/local/LocalProcessBuilder.java b/core/src/main/java/org/apache/gravitino/job/local/LocalProcessBuilder.java
index f3c7f6228e..7001781d90 100644
--- a/core/src/main/java/org/apache/gravitino/job/local/LocalProcessBuilder.java
+++ b/core/src/main/java/org/apache/gravitino/job/local/LocalProcessBuilder.java
@@ -36,29 +36,29 @@ public abstract class LocalProcessBuilder {
protected final File workingDirectory;
- protected LocalProcessBuilder(JobTemplate jobTemplate, Map<String, String> configs) {
+ protected LocalProcessBuilder(
+ JobTemplate jobTemplate, File workingDirectory, Map<String, String> configs) {
this.jobTemplate = jobTemplate;
- this.workingDirectory = resolveWorkingDirectory(jobTemplate);
+ this.workingDirectory = workingDirectory;
}
+ public abstract Process start();
+
/**
- * Resolves the working directory for a job template. The executable is expected to be in the
- * working directory, so the working directory can be derived from the executable's path.
+ * Creates the process builder of a job.
*
- * @param jobTemplate the job template to resolve the working directory for
- * @return the working directory for the job template
+ * @param jobTemplate the localized job template of the job
+ * @param workingDirectory the working directory of the job process, where the job's resources are
+ * localized and its output is written
+ * @param configs the local job executor configurations
+ * @return the process builder of the job
*/
- public static File resolveWorkingDirectory(JobTemplate jobTemplate) {
- return new File(jobTemplate.executable()).getAbsoluteFile().getParentFile();
- }
-
- public abstract Process start();
-
- public static LocalProcessBuilder create(JobTemplate jobTemplate, Map<String, String> configs) {
+ public static LocalProcessBuilder create(
+ JobTemplate jobTemplate, File workingDirectory, Map<String, String> configs) {
if (jobTemplate instanceof ShellJobTemplate) {
- return new ShellProcessBuilder((ShellJobTemplate) jobTemplate, configs);
+ return new ShellProcessBuilder((ShellJobTemplate) jobTemplate, workingDirectory, configs);
} else if (jobTemplate instanceof SparkJobTemplate) {
- return new SparkProcessBuilder((SparkJobTemplate) jobTemplate, configs);
+ return new SparkProcessBuilder((SparkJobTemplate) jobTemplate, workingDirectory, configs);
} else {
throw new IllegalArgumentException(
"Unsupported job template type: " + jobTemplate.getClass().getName());
diff --git a/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java b/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java
index b8ae065fbf..2096c7bf0f 100644
--- a/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java
+++ b/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java
@@ -24,6 +24,7 @@ import com.google.common.collect.Lists;
import java.io.File;
import java.util.List;
import java.util.Map;
+import org.apache.gravitino.connector.job.JobResourceUtils;
import org.apache.gravitino.job.ShellJobTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,16 +33,21 @@ public class ShellProcessBuilder extends LocalProcessBuilder {
private static final Logger LOG = LoggerFactory.getLogger(ShellProcessBuilder.class);
- protected ShellProcessBuilder(ShellJobTemplate shellJobTemplate, Map<String, String> configs) {
- super(shellJobTemplate, configs);
+ protected ShellProcessBuilder(
+ ShellJobTemplate shellJobTemplate, File workingDirectory, Map<String, String> configs) {
+ super(shellJobTemplate, workingDirectory, configs);
}
@Override
public Process start() {
ShellJobTemplate shellJobTemplate = (ShellJobTemplate) jobTemplate;
- File executableFile = new File(shellJobTemplate.executable());
- if (!executableFile.canExecute()) {
- executableFile.setExecutable(true);
+ // A command name is resolved on the PATH by the operating system, it isn't a file in the
+ // working directory.
+ if (!JobResourceUtils.isCommandName(shellJobTemplate.executable())) {
+ File executableFile = new File(shellJobTemplate.executable());
+ if (!executableFile.canExecute()) {
+ executableFile.setExecutable(true);
+ }
}
List<String> commandList = Lists.newArrayList(shellJobTemplate.executable());
diff --git a/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java b/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java
index 7d717b1dc8..c789b26ed0 100644
--- a/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java
+++ b/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java
@@ -50,8 +50,9 @@ public class SparkProcessBuilder extends LocalProcessBuilder {
private final String sparkSubmit;
- protected SparkProcessBuilder(SparkJobTemplate sparkJobTemplate, Map<String, String> configs) {
- super(sparkJobTemplate, configs);
+ protected SparkProcessBuilder(
+ SparkJobTemplate sparkJobTemplate, File workingDirectory, Map<String, String> configs) {
+ super(sparkJobTemplate, workingDirectory, configs);
this.sparkSubmit = resolveSparkSubmit(configs);
}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/info/JobInfo.java b/core/src/main/java/org/apache/gravitino/listener/api/info/JobInfo.java
index d5e68b1f08..5771324269 100644
--- a/core/src/main/java/org/apache/gravitino/listener/api/info/JobInfo.java
+++ b/core/src/main/java/org/apache/gravitino/listener/api/info/JobInfo.java
@@ -183,7 +183,7 @@ public final class JobInfo {
/**
* Returns the resolved job template that was actually submitted for execution, with placeholders
- * replaced and referenced files downloaded.
+ * replaced. Its executable, scripts, jars, files and archives are the URIs from the template.
*
* @return the runtime job template, or null for jobs run before this field was introduced
*/
diff --git a/core/src/main/java/org/apache/gravitino/meta/JobEntity.java b/core/src/main/java/org/apache/gravitino/meta/JobEntity.java
index 6c73983e01..0f135ae509 100644
--- a/core/src/main/java/org/apache/gravitino/meta/JobEntity.java
+++ b/core/src/main/java/org/apache/gravitino/meta/JobEntity.java
@@ -68,8 +68,8 @@ public class JobEntity implements Entity, Auditable, HasIdentifier {
"runtime_job_template",
String.class,
"The resolved job template that was actually submitted for execution, serialized as "
- + "JSON, with placeholders replaced and referenced files downloaded. Null for jobs "
- + "run before this field was introduced.");
+ + "JSON, with placeholders replaced and the resources kept as the URIs from the "
+ + "template. Null for jobs run before this field was introduced.");
private Long id;
private String jobExecutionId;
@@ -167,7 +167,7 @@ public class JobEntity implements Entity, Auditable, HasIdentifier {
/**
* Returns the resolved job template that was actually submitted for execution, serialized as JSON
- * (placeholders replaced, referenced files downloaded).
+ * (placeholders replaced, resources kept as the URIs from the template).
*
* @return the serialized runtime job template, or {@code null} for jobs run before this field was
* introduced
diff --git a/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutionInfo.java b/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutionInfo.java
index 6692090b33..87e5af6759 100644
--- a/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutionInfo.java
+++ b/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutionInfo.java
@@ -118,7 +118,7 @@ public class TestJobExecutionInfo {
public void initialize(Map<String, String> configs) {}
@Override
- public String submitJob(JobTemplate jobTemplate) {
+ public String submitJob(JobContext context, JobTemplate jobTemplate) {
return "job-1";
}
diff --git a/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.java b/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.java
new file mode 100644
index 0000000000..c967eacb33
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.java
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.connector.job;
+
+import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+import org.apache.gravitino.exceptions.NoSuchJobException;
+import org.apache.gravitino.job.JobTemplate;
+import org.apache.gravitino.job.ShellJobTemplate;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+public class TestJobExecutor {
+
+ private abstract static class BaseJobExecutor implements JobExecutor {
+
+ @Override
+ public void initialize(Map<String, String> configs) {}
+
+ @Override
+ public JobExecutionInfo getJobExecutionInfo(String jobId) throws NoSuchJobException {
+ throw new NoSuchJobException("No job found with ID: %s", jobId);
+ }
+
+ @Override
+ public void cancelJob(String jobId) throws NoSuchJobException {
+ throw new NoSuchJobException("No job found with ID: %s", jobId);
+ }
+
+ @Override
+ public void close() {}
+ }
+
+ /** Implements only the deprecated submit method that receives local paths. */
+ @SuppressWarnings("deprecation")
+ private static class LocalPathJobExecutor extends BaseJobExecutor {
+
+ private JobTemplate submitted;
+
+ @Override
+ public String submitJob(JobTemplate jobTemplate) {
+ submitted = jobTemplate;
+ return "execution-1";
+ }
+ }
+
+ /** Implements only the submit method that receives the URIs, and returns the executable. */
+ private static class UriJobExecutor extends BaseJobExecutor {
+
+ @Override
+ public String submitJob(JobContext context, JobTemplate jobTemplate) {
+ return jobTemplate.executable();
+ }
+ }
+
+ @TempDir private Path tempDir;
+
+ @Test
+ public void testSubmitJobWithContextLocalizesAndDelegates() throws IOException {
+ File script = Files.createFile(tempDir.resolve("run.sh")).toFile();
+ File stagingDir = Files.createDirectory(tempDir.resolve("staging")).toFile();
+ ShellJobTemplate template =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withExecutable(script.toURI().toString())
+ .withArguments(Lists.newArrayList("arg"))
+ .build();
+
+ LocalPathJobExecutor executor = new LocalPathJobExecutor();
+ String executionId = executor.submitJob(new JobContext(1L, "metalake", stagingDir), template);
+
+ Assertions.assertEquals("execution-1", executionId);
+ // The job executor that only implements submitJob(JobTemplate) gets local paths in the
+ // staging directory, as before.
+ Assertions.assertEquals(
+ new File(stagingDir, script.getName()).getAbsolutePath(), executor.submitted.executable());
+ Assertions.assertEquals(template.arguments(), executor.submitted.arguments());
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ public void testSubmitJobWithoutContextIsUnsupportedByDefault() {
+ JobExecutor executor = new UriJobExecutor();
+ ShellJobTemplate template =
+ ShellJobTemplate.builder().withName("shell_job").withExecutable("/bin/echo").build();
+
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> executor.submitJob(template));
+ Assertions.assertEquals(
+ "/bin/echo",
+ executor.submitJob(new JobContext(1L, "metalake", tempDir.toFile()), template));
+ }
+
+ @Test
+ public void testJobContextRejectsBlankMetalake() {
+ File stagingDir = tempDir.toFile();
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new JobContext(1L, null, stagingDir));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new JobContext(1L, " ", stagingDir));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new JobContext(1L, "m", null));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/connector/job/TestJobResourceUtils.java b/core/src/test/java/org/apache/gravitino/connector/job/TestJobResourceUtils.java
new file mode 100644
index 0000000000..fb003d6bc1
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/connector/job/TestJobResourceUtils.java
@@ -0,0 +1,403 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.connector.job;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.sun.net.httpserver.HttpServer;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.commons.io.FileUtils;
+import org.apache.gravitino.job.JobTemplate;
+import org.apache.gravitino.job.ShellJobTemplate;
+import org.apache.gravitino.job.SparkJobTemplate;
+import org.apache.gravitino.utils.FileFetcher;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestJobResourceUtils {
+
+ private static File tempDir;
+ private File tempStagingDir;
+
+ @BeforeAll
+ public static void setUpClass() throws IOException {
+ tempDir = Files.createTempDirectory("job-resource-test").toFile();
+ }
+
+ @AfterAll
+ public static void tearDownClass() throws IOException {
+ if (tempDir != null && tempDir.exists()) {
+ FileUtils.deleteDirectory(tempDir);
+ tempDir = null;
+ }
+ }
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ tempStagingDir = Files.createTempDirectory(tempDir.toPath(), "staging").toFile();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ if (tempStagingDir != null && tempStagingDir.exists()) {
+ FileUtils.deleteDirectory(tempStagingDir);
+ tempStagingDir = null;
+ }
+ }
+
+ @Test
+ public void testLocalizeShellJobTemplate() throws IOException {
+ File executable = Files.createTempFile(tempDir.toPath(), "run", ".sh").toFile();
+ File script = Files.createTempFile(tempDir.toPath(), "lib", ".sh").toFile();
+ ShellJobTemplate template =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withComment("comment")
+ .withExecutable(executable.toURI().toString())
+ .withArguments(Lists.newArrayList("--date", "2026-09-28"))
+ .withEnvironments(ImmutableMap.of("KEY", "VALUE"))
+ .withCustomFields(ImmutableMap.of("field", "value"))
+ .withScripts(Lists.newArrayList(script.toURI().toString()))
+ .build();
+
+ ShellJobTemplate result =
+ (ShellJobTemplate) JobResourceUtils.localizeJobTemplate(template, tempStagingDir);
+
+ Assertions.assertEquals(
+ new File(tempStagingDir, executable.getName()).getAbsolutePath(), result.executable());
+ Assertions.assertEquals(
+ Lists.newArrayList(new File(tempStagingDir, script.getName()).getAbsolutePath()),
+ result.scripts());
+ Assertions.assertEquals(template.name(), result.name());
+ Assertions.assertEquals(template.comment(), result.comment());
+ Assertions.assertEquals(template.arguments(), result.arguments());
+ Assertions.assertEquals(template.environments(), result.environments());
+ Assertions.assertEquals(template.customFields(), result.customFields());
+ }
+
+ @Test
+ public void testLocalizeJobTemplateTwiceIntoSameDir() throws IOException {
+ File executable = Files.createTempFile(tempDir.toPath(), "run", ".sh").toFile();
+ Files.writeString(executable.toPath(), "echo hi");
+ ShellJobTemplate template =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withExecutable(executable.toURI().toString())
+ .build();
+
+ // A job executor may localize a job template that was already localized into the same
+ // directory, for example a subclass calling its parent's submitJob.
+ JobTemplate localized = JobResourceUtils.localizeJobTemplate(template, tempStagingDir);
+ JobTemplate localizedAgain = JobResourceUtils.localizeJobTemplate(localized, tempStagingDir);
+
+ Assertions.assertEquals(localized.executable(), localizedAgain.executable());
+ Assertions.assertEquals(
+ "echo hi", Files.readString(new File(localizedAgain.executable()).toPath()));
+ }
+
+ @Test
+ public void testIsCommandName() {
+ for (String command : List.of("python", "bash", "python3.11", "spark-submit", "run.sh")) {
+ Assertions.assertTrue(JobResourceUtils.isCommandName(command), command);
+ }
+ for (String notCommand :
+ Arrays.asList(
+ null,
+ "",
+ " ",
+ ".",
+ "..",
+ "/bin/bash",
+ "./run.sh",
+ "jobs/run.sh",
+ "file:///bin/bash",
+ "https://repo.example.com/run.sh",
+ "hdfs://nn/run.sh",
+ "my command")) {
+ Assertions.assertFalse(JobResourceUtils.isCommandName(notCommand), notCommand);
+ }
+ }
+
+ @Test
+ public void testLocalizeShellJobTemplateKeepsCommandName() throws IOException {
+ File script = Files.createTempFile(tempDir.toPath(), "job", ".py").toFile();
+ ShellJobTemplate template =
+ ShellJobTemplate.builder()
+ .withName("python_job")
+ .withExecutable("python")
+ .withArguments(Lists.newArrayList(script.getName()))
+ .withScripts(Lists.newArrayList(script.toURI().toString()))
+ .build();
+
+ ShellJobTemplate result =
+ (ShellJobTemplate) JobResourceUtils.localizeJobTemplate(template, tempStagingDir);
+
+ // The command is run from the PATH, only the script is fetched.
+ Assertions.assertEquals("python", result.executable());
+ Assertions.assertEquals(
+ Lists.newArrayList(new File(tempStagingDir, script.getName()).getAbsolutePath()),
+ result.scripts());
+ Assertions.assertArrayEquals(new String[] {script.getName()}, tempStagingDir.list());
+ }
+
+ @Test
+ public void testLocalizeRejectsResourcesWithSameFileName() throws IOException {
+ File dirA = Files.createTempDirectory(tempDir.toPath(), "a").toFile();
+ File dirB = Files.createTempDirectory(tempDir.toPath(), "b").toFile();
+ File executable = new File(dirA, "run.sh");
+ File script = new File(dirB, "run.sh");
+ Assertions.assertTrue(executable.createNewFile());
+ Assertions.assertTrue(script.createNewFile());
+
+ // Different resources with the same file name would overwrite each other.
+ ShellJobTemplate shellTemplate =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withExecutable(executable.getAbsolutePath())
+ .withScripts(Lists.newArrayList(script.getAbsolutePath()))
+ .build();
+ IllegalArgumentException e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> JobResourceUtils.localizeJobTemplate(shellTemplate, tempStagingDir));
+ Assertions.assertTrue(e.getMessage().contains("same file name run.sh"), e.getMessage());
+
+ SparkJobTemplate sparkTemplate =
+ SparkJobTemplate.builder()
+ .withName("spark_job")
+ .withExecutable("https://a.example.com/jobs/app.jar")
+ .withClassName("org.example.App")
+ .withFiles(Lists.newArrayList("https://b.example.com/conf/app.jar"))
+ .build();
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> JobResourceUtils.localizeJobTemplate(sparkTemplate, tempStagingDir));
+
+ // Nothing is fetched when the job template is rejected.
+ Assertions.assertArrayEquals(new String[0], tempStagingDir.list());
+
+ // The same resource listed twice is not a conflict.
+ ShellJobTemplate repeated =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withExecutable(executable.getAbsolutePath())
+ .withScripts(Lists.newArrayList(executable.getAbsolutePath()))
+ .build();
+ Assertions.assertDoesNotThrow(
+ () -> JobResourceUtils.localizeJobTemplate(repeated, tempStagingDir));
+ }
+
+ @Test
+ public void testLocalizeRejectsScriptNamedLikeCommandNameExecutable() throws IOException {
+ File script = new File(Files.createTempDirectory(tempDir.toPath(), "src").toFile(), "run.sh");
+ Assertions.assertTrue(script.createNewFile());
+ // "run.sh" is a command name, so the fetched run.sh would not be the one that runs.
+ ShellJobTemplate template =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withExecutable("run.sh")
+ .withScripts(Lists.newArrayList(script.toURI().toString()))
+ .build();
+
+ IllegalArgumentException e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> JobResourceUtils.localizeJobTemplate(template, tempStagingDir));
+ Assertions.assertTrue(e.getMessage().contains("command name"), e.getMessage());
+ Assertions.assertArrayEquals(new String[0], tempStagingDir.list());
+ }
+
+ @Test
+ public void testFetchFileRejectsUriWithoutFileName() {
+ for (String uri :
+ Arrays.asList("http://repo.example.com", "http://repo.example.com/", "file:relative")) {
+ IllegalArgumentException e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> JobResourceUtils.fetchFile(uri, tempStagingDir, 1000),
+ uri);
+ Assertions.assertTrue(e.getMessage().contains("no file name"), e.getMessage());
+ }
+ // The staging directory itself is never the fetch destination.
+ Assertions.assertTrue(tempStagingDir.isDirectory());
+ Assertions.assertArrayEquals(new String[0], tempStagingDir.list());
+ }
+
+ @Test
+ public void testLocalizeSparkJobTemplate() throws IOException {
+ File executable = Files.createTempFile(tempDir.toPath(), "app", ".jar").toFile();
+ File jar = Files.createTempFile(tempDir.toPath(), "lib", ".jar").toFile();
+ File file = Files.createTempFile(tempDir.toPath(), "conf", ".properties").toFile();
+ File archive = Files.createTempFile(tempDir.toPath(), "deps", ".zip").toFile();
+ SparkJobTemplate template =
+ SparkJobTemplate.builder()
+ .withName("spark_job")
+ .withExecutable(executable.toURI().toString())
+ .withClassName("org.example.App")
+ .withArguments(Lists.newArrayList("arg"))
+ .withJars(Lists.newArrayList(jar.toURI().toString()))
+ .withFiles(Lists.newArrayList(file.toURI().toString()))
+ .withArchives(Lists.newArrayList(archive.toURI().toString()))
+ .withConfigs(ImmutableMap.of("spark.executor.instances", "2"))
+ .build();
+
+ SparkJobTemplate result =
+ (SparkJobTemplate) JobResourceUtils.localizeJobTemplate(template, tempStagingDir);
+
+ Assertions.assertEquals(
+ new File(tempStagingDir, executable.getName()).getAbsolutePath(), result.executable());
+ Assertions.assertEquals(
+ Lists.newArrayList(new File(tempStagingDir, jar.getName()).getAbsolutePath()),
+ result.jars());
+ Assertions.assertEquals(
+ Lists.newArrayList(new File(tempStagingDir, file.getName()).getAbsolutePath()),
+ result.files());
+ Assertions.assertEquals(
+ Lists.newArrayList(new File(tempStagingDir, archive.getName()).getAbsolutePath()),
+ result.archives());
+ Assertions.assertEquals(template.className(), result.className());
+ Assertions.assertEquals(template.arguments(), result.arguments());
+ Assertions.assertEquals(template.configs(), result.configs());
+ }
+
+ @Test
+ public void testFetchFile() throws IOException {
+ File testFile1 = Files.createTempFile(tempDir.toPath(), "testFile1", ".txt").toFile();
+ String result =
+ JobResourceUtils.fetchFile(testFile1.toURI().toString(), tempStagingDir, 30 * 1000);
+ File resultFile = new File(result);
+ Assertions.assertEquals(testFile1.getName(), resultFile.getName());
+
+ File testFile2 = Files.createTempFile(tempDir.toPath(), "testFile2", ".txt").toFile();
+ File testFile3 = Files.createTempFile(tempDir.toPath(), "testFile3", ".txt").toFile();
+
+ List<String> expectedUris =
+ Lists.newArrayList(testFile2.toURI().toString(), testFile3.toURI().toString());
+ List<String> resultUris = JobResourceUtils.fetchFiles(expectedUris, tempStagingDir, 30 * 1000);
+
+ Assertions.assertEquals(2, resultUris.size());
+ List<String> resultFileNames =
+ resultUris.stream().map(uri -> new File(uri).getName()).collect(Collectors.toList());
+ Assertions.assertTrue(resultFileNames.contains(testFile2.getName()));
+ Assertions.assertTrue(resultFileNames.contains(testFile3.getName()));
+ }
+
+ @Test
+ public void testFetchFileWithMissingLocalFileShouldFail() throws IOException {
+ File stagingDir = tempStagingDir;
+
+ Path missingFilePath =
+ Path.of(System.getProperty("java.io.tmpdir"), "missing-job-file-" + UUID.randomUUID());
+ String uri = missingFilePath.toUri().toString();
+
+ Assertions.assertThrows(
+ RuntimeException.class, () -> JobResourceUtils.fetchFile(uri, stagingDir, 1000));
+ }
+
+ @Test
+ public void testFetchFileSsrfBlocked() {
+ File stagingDir = tempStagingDir;
+ FileFetcher.get().initialize(true);
+
+ // Loopback address
+ RuntimeException e1 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> JobResourceUtils.fetchFile("http://127.0.0.1:8090/configs", stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e1);
+
+ // AWS / GCP / Azure cloud-metadata endpoint (link-local 169.254.x.x)
+ RuntimeException e2 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ JobResourceUtils.fetchFile(
+ "http://169.254.169.254/latest/meta-data/", stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e2);
+
+ // RFC-1918 private range
+ RuntimeException e3 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> JobResourceUtils.fetchFile("http://192.168.1.1/run.sh", stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e3);
+
+ // Alibaba Cloud / Oracle Cloud metadata endpoint
+ RuntimeException e4 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> JobResourceUtils.fetchFile("http://100.100.100.200/run.sh", stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e4);
+ }
+
+ @Test
+ public void testFetchFileShouldAllowLocalhostWhenBlockingDisabled() throws Exception {
+ File stagingDir = tempStagingDir;
+ HttpServer server = createLoopbackHttpServer("job artifact");
+
+ try {
+ server.start();
+ int port = server.getAddress().getPort();
+ FileFetcher.get().initialize(false);
+
+ String fetchedFile =
+ JobResourceUtils.fetchFile(
+ String.format("http://127.0.0.1:%d/artifact.jar", port), stagingDir, 1000);
+
+ Assertions.assertEquals("job artifact", Files.readString(Path.of(fetchedFile)));
+ } finally {
+ FileFetcher.get().initialize(true);
+ server.stop(0);
+ }
+ }
+
+ private static HttpServer createLoopbackHttpServer(String response) throws IOException {
+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/artifact.jar",
+ exchange -> {
+ byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(200, bytes.length);
+ try (OutputStream outputStream = exchange.getResponseBody()) {
+ outputStream.write(bytes);
+ }
+ });
+ return server;
+ }
+
+ private static void assertRemoteUriBlockedMessage(RuntimeException exception) {
+ Assertions.assertTrue(exception.getCause().getMessage().contains("Gravitino server side"));
+ Assertions.assertTrue(
+ exception.getCause().getMessage().contains(FileFetcher.BLOCK_UNSAFE_REMOTE_URI_CONFIG));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobExecutorFactory.java b/core/src/test/java/org/apache/gravitino/job/TestJobExecutorFactory.java
index d767723c8b..ff2bfee6c7 100644
--- a/core/src/test/java/org/apache/gravitino/job/TestJobExecutorFactory.java
+++ b/core/src/test/java/org/apache/gravitino/job/TestJobExecutorFactory.java
@@ -31,6 +31,7 @@ import javax.tools.ToolProvider;
import org.apache.commons.io.FileUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
+import org.apache.gravitino.connector.job.JobContext;
import org.apache.gravitino.connector.job.JobExecutionInfo;
import org.apache.gravitino.connector.job.JobExecutor;
import org.apache.gravitino.exceptions.NoSuchJobException;
@@ -162,16 +163,68 @@ public class TestJobExecutorFactory {
() -> JobExecutorFactory.checkJobExecutorClass(String.class));
}
+ @Test
+ public void testJobExecutorBuiltAgainstPreviousSpiStillSubmitsJobs() throws Exception {
+ // A job executor plugin built before submitJob(JobContext, JobTemplate) was added implements
+ // the then-abstract submitJob(JobTemplate). It must still be accepted, and receive the jobs
+ // localized by the default submitJob(JobContext, JobTemplate).
+ Class<?> previousJobExecutorClass = compileAgainstPreviousSubmitSpi();
+ try {
+ Assertions.assertDoesNotThrow(
+ () -> JobExecutorFactory.checkJobExecutorClass(previousJobExecutorClass));
+
+ JobExecutor previousJobExecutor =
+ (JobExecutor) previousJobExecutorClass.getDeclaredConstructor().newInstance();
+ File script = new File(testDir, "run.sh");
+ Assertions.assertTrue(script.createNewFile());
+ File jobDir = new File(testDir, "job");
+ Assertions.assertTrue(jobDir.mkdirs());
+ JobTemplate jobTemplate =
+ ShellJobTemplate.builder()
+ .withName("shell_job")
+ .withExecutable(script.getAbsolutePath())
+ .build();
+
+ String executionId =
+ previousJobExecutor.submitJob(new JobContext(1L, "metalake", jobDir), jobTemplate);
+ Assertions.assertEquals(new File(jobDir, "run.sh").getAbsolutePath(), executionId);
+ } finally {
+ ((URLClassLoader) previousJobExecutorClass.getClassLoader()).close();
+ }
+ }
+
+ @Test
+ public void testRejectLocalJobExecutorSubclassOverridingDeprecatedSubmitJob() {
+ Assertions.assertDoesNotThrow(
+ () -> JobExecutorFactory.checkJobExecutorClass(CustomLocalJobExecutor.class));
+
+ IllegalArgumentException e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> JobExecutorFactory.checkJobExecutorClass(LegacyLocalJobExecutor.class));
+ Assertions.assertTrue(e.getMessage().contains("LocalJobExecutor"), e.getMessage());
+ }
+
+ @Test
+ public void testRejectJobExecutorWithoutSubmitJob() {
+ // Either submit method is enough: the old one through the default of the new one.
+ Assertions.assertDoesNotThrow(
+ () -> JobExecutorFactory.checkJobExecutorClass(RecordingJobExecutor.class));
+ Assertions.assertDoesNotThrow(
+ () -> JobExecutorFactory.checkJobExecutorClass(ContextJobExecutor.class));
+
+ IllegalArgumentException e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> JobExecutorFactory.checkJobExecutorClass(NoSubmitJobExecutor.class));
+ Assertions.assertTrue(e.getMessage().contains("submitJob"), e.getMessage());
+ }
+
// Compiles a job executor against the SPI as it was before getJobExecutionInfo was added, and
// loads it against the current SPI, like a plugin jar built for an older Gravitino version.
private Class<?> compileAgainstOldSpi() throws IOException {
- File sourceDir = new File(testDir, "old-spi-src");
- File classDir = new File(testDir, "old-spi-classes");
- Assertions.assertTrue(classDir.mkdirs());
-
- File oldSpi = new File(sourceDir, "org/apache/gravitino/connector/job/JobExecutor.java");
- FileUtils.writeStringToFile(
- oldSpi,
+ return compileAgainstSpi(
+ "old-spi",
String.join(
"\n",
"package org.apache.gravitino.connector.job;",
@@ -184,10 +237,7 @@ public class TestJobExecutorFactory {
" JobHandle.Status getJobStatus(String jobId);",
" void cancelJob(String jobId);",
"}"),
- StandardCharsets.UTF_8);
- File oldExecutor = new File(sourceDir, "com/example/OldJobExecutor.java");
- FileUtils.writeStringToFile(
- oldExecutor,
+ "OldJobExecutor",
String.join(
"\n",
"package com.example;",
@@ -203,8 +253,55 @@ public class TestJobExecutorFactory {
" }",
" public void cancelJob(String jobId) {}",
" public void close() {}",
+ "}"));
+ }
+
+ // Compiles a job executor against the SPI as it was before submitJob(JobContext, JobTemplate) was
+ // added, where submitJob(JobTemplate) was abstract. Its submitJob returns the executable it gets.
+ private Class<?> compileAgainstPreviousSubmitSpi() throws IOException {
+ return compileAgainstSpi(
+ "previous-submit-spi",
+ String.join(
+ "\n",
+ "package org.apache.gravitino.connector.job;",
+ "import java.util.Map;",
+ "import org.apache.gravitino.job.JobTemplate;",
+ "public interface JobExecutor extends java.io.Closeable {",
+ " void initialize(Map<String, String> configs);",
+ " String submitJob(JobTemplate jobTemplate);",
+ " JobExecutionInfo getJobExecutionInfo(String jobId);",
+ " void cancelJob(String jobId);",
"}"),
- StandardCharsets.UTF_8);
+ "PreviousJobExecutor",
+ String.join(
+ "\n",
+ "package com.example;",
+ "import java.util.Map;",
+ "import org.apache.gravitino.connector.job.JobExecutionInfo;",
+ "import org.apache.gravitino.connector.job.JobExecutor;",
+ "import org.apache.gravitino.job.JobTemplate;",
+ "public class PreviousJobExecutor implements JobExecutor {",
+ " public void initialize(Map<String, String> configs) {}",
+ " public String submitJob(JobTemplate jobTemplate) { return jobTemplate.executable(); }",
+ " public JobExecutionInfo getJobExecutionInfo(String jobId) { return null; }",
+ " public void cancelJob(String jobId) {}",
+ " public void close() {}",
+ "}"));
+ }
+
+ // Compiles the job executor com.example.<executorName> against the given SPI source, and loads it
+ // against the current SPI, like a plugin jar built for an older Gravitino version.
+ private Class<?> compileAgainstSpi(
+ String name, String spiSource, String executorName, String executorSource)
+ throws IOException {
+ File sourceDir = new File(testDir, name + "-src");
+ File classDir = new File(testDir, name + "-classes");
+ Assertions.assertTrue(classDir.mkdirs());
+
+ File spi = new File(sourceDir, "org/apache/gravitino/connector/job/JobExecutor.java");
+ FileUtils.writeStringToFile(spi, spiSource, StandardCharsets.UTF_8);
+ File executor = new File(sourceDir, "com/example/" + executorName + ".java");
+ FileUtils.writeStringToFile(executor, executorSource, StandardCharsets.UTF_8);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Assertions.assertNotNull(compiler, "The tests must run on a JDK");
@@ -217,8 +314,8 @@ public class TestJobExecutorFactory {
System.getProperty("java.class.path"),
"-d",
classDir.getAbsolutePath(),
- oldSpi.getAbsolutePath(),
- oldExecutor.getAbsolutePath());
+ spi.getAbsolutePath(),
+ executor.getAbsolutePath());
Assertions.assertEquals(0, result);
// Only the plugin class is loaded from the compiled classes: the class loader delegates to its
@@ -227,7 +324,7 @@ public class TestJobExecutorFactory {
new URLClassLoader(
new URL[] {classDir.toURI().toURL()}, TestJobExecutorFactory.class.getClassLoader());
try {
- return classLoader.loadClass("com.example.OldJobExecutor");
+ return classLoader.loadClass("com.example." + executorName);
} catch (ClassNotFoundException e) {
classLoader.close();
throw new IOException(e);
@@ -237,7 +334,19 @@ public class TestJobExecutorFactory {
/** A user's subclass of the local job executor, inheriting its initialization. */
public static class CustomLocalJobExecutor extends LocalJobExecutor {}
+ // Overrides the deprecated submit method, which LocalJobExecutor no longer calls.
+ @SuppressWarnings("deprecation")
+ public static class LegacyLocalJobExecutor extends LocalJobExecutor {
+ @Override
+ public String submitJob(JobTemplate jobTemplate) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
/** A job executor that only records the configurations it's initialized with. */
+ // Implements the deprecated submitJob(JobTemplate), like a job executor built for an earlier
+ // version of Gravitino.
+ @SuppressWarnings("deprecation")
public static class RecordingJobExecutor implements JobExecutor {
private Map<String, String> configs;
@@ -265,4 +374,31 @@ public class TestJobExecutorFactory {
@Override
public void close() {}
}
+
+ public static class ContextJobExecutor extends NoSubmitJobExecutor {
+
+ @Override
+ public String submitJob(JobContext context, JobTemplate jobTemplate) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public static class NoSubmitJobExecutor implements JobExecutor {
+
+ @Override
+ public void initialize(Map<String, String> configs) {}
+
+ @Override
+ public JobExecutionInfo getJobExecutionInfo(String jobId) throws NoSuchJobException {
+ throw new NoSuchJobException("No job found with ID: %s", jobId);
+ }
+
+ @Override
+ public void cancelJob(String jobId) throws NoSuchJobException {
+ throw new NoSuchJobException("No job found with ID: %s", jobId);
+ }
+
+ @Override
+ public void close() {}
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobManager.java b/core/src/test/java/org/apache/gravitino/job/TestJobManager.java
index 33ae423217..1d769c81cc 100644
--- a/core/src/test/java/org/apache/gravitino/job/TestJobManager.java
+++ b/core/src/test/java/org/apache/gravitino/job/TestJobManager.java
@@ -64,6 +64,7 @@ import org.apache.gravitino.EntityStore;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.connector.job.JobContext;
import org.apache.gravitino.connector.job.JobExecutionInfo;
import org.apache.gravitino.connector.job.JobExecutor;
import org.apache.gravitino.dto.job.JobTemplateDTO;
@@ -203,7 +204,7 @@ public class TestJobManager {
List.of(Entity.EntityType.METALAKE, Entity.EntityType.JOB_TEMPLATE)) {
Mockito.reset(entityStore, jobExecutor);
String executionId = "submitted_" + parent.name();
- when(jobExecutor.submitJob(any())).thenReturn(executionId);
+ when(jobExecutor.submitJob(any(), any())).thenReturn(executionId);
NoSuchEntityException missing = new NoSuchEntityException("Parent was deleted: %s", parent);
doThrow(missing).when(entityStore).put(any(JobEntity.class), eq(false));
@@ -212,7 +213,7 @@ public class TestJobManager {
NoSuchJobTemplateException.class,
() -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));
Assertions.assertSame(missing, failure.getCause());
- verify(jobExecutor, times(1)).submitJob(any());
+ verify(jobExecutor, times(1)).submitJob(any(), any());
verify(jobExecutor, never()).cancelJob(any());
verify(entityStore, times(1)).put(any(JobEntity.class), eq(false));
}
@@ -752,7 +753,7 @@ public class TestJobManager {
when(jobManager.getJobTemplate(metalake, shellJobTemplate.name())).thenReturn(shellJobTemplate);
String jobExecutionId = "job_execution_id_for_test";
- when(jobExecutor.submitJob(any())).thenReturn(jobExecutionId);
+ when(jobExecutor.submitJob(any(), any())).thenReturn(jobExecutionId);
doNothing().when(entityStore).put(any(JobEntity.class), anyBoolean());
@@ -773,7 +774,7 @@ public class TestJobManager {
Assertions.assertEquals("Job template does not exist", e.getMessage());
// Test when job executor fails
- doThrow(new RuntimeException("Job executor error")).when(jobExecutor).submitJob(any());
+ doThrow(new RuntimeException("Job executor error")).when(jobExecutor).submitJob(any(), any());
Assertions.assertThrows(
RuntimeException.class,
@@ -802,7 +803,7 @@ public class TestJobManager {
// The job executor may start the job right after it is submitted, so the queued time must be
// taken before the submission to never be later than the reported started time.
AtomicReference<Instant> submittedAt = new AtomicReference<>();
- when(jobExecutor.submitJob(any()))
+ when(jobExecutor.submitJob(any(), any()))
.thenAnswer(
invocation -> {
Thread.sleep(5);
@@ -831,7 +832,7 @@ public class TestJobManager {
new IllegalArgumentException(
"gravitino.jobExecutor.local.sparkHome or SPARK_HOME environment variable must"
+ " be set for Spark jobs");
- doThrow(rejection).when(jobExecutor).submitJob(any());
+ doThrow(rejection).when(jobExecutor).submitJob(any(), any());
// The rejection must reach the caller as is, so the REST layer reports the original reason
// with a 400 instead of wrapping it into a generic 500 error.
@@ -875,7 +876,7 @@ public class TestJobManager {
when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))
.thenReturn(jobTemplateEntity);
- when(jobExecutor.submitJob(any())).thenReturn("job_execution_id_for_test");
+ when(jobExecutor.submitJob(any(), any())).thenReturn("job_execution_id_for_test");
doNothing().when(entityStore).put(any(JobEntity.class), anyBoolean());
JobEntity jobEntity =
@@ -893,12 +894,22 @@ public class TestJobManager {
Assertions.assertEquals(Lists.newArrayList("Hello!"), runtimeJobTemplateDTO.arguments());
Assertions.assertEquals(jobTemplateEntity.name(), runtimeJobTemplateDTO.name());
Assertions.assertEquals(jobTemplateEntity.comment(), runtimeJobTemplateDTO.comment());
- // JobTemplateResolver#resolve() also resolves the executable by fetching it into the job's
- // staging directory, so it ends up as a local staging-dir path rather than the original
- // "/bin/echo" - just confirm it was actually resolved to something under that directory.
- Assertions.assertTrue(
- runtimeJobTemplateDTO.executable().endsWith("echo"),
- () -> "Unexpected resolved executable: " + runtimeJobTemplateDTO.executable());
+ // JobManager doesn't fetch the resources, the runtime template keeps the resolved URI.
+ Assertions.assertEquals("/bin/echo", runtimeJobTemplateDTO.executable());
+
+ // The job executor gets the context of the job run and the template with the URIs.
+ ArgumentCaptor<JobContext> contextCaptor = ArgumentCaptor.forClass(JobContext.class);
+ ArgumentCaptor<JobTemplate> templateCaptor = ArgumentCaptor.forClass(JobTemplate.class);
+ verify(jobExecutor).submitJob(contextCaptor.capture(), templateCaptor.capture());
+ JobContext context = contextCaptor.getValue();
+ Assertions.assertEquals(jobEntity.id(), context.jobId());
+ Assertions.assertEquals(metalake, context.metalake());
+ Assertions.assertTrue(context.stagingDir().isDirectory(), context::toString);
+ Assertions.assertEquals("/bin/echo", templateCaptor.getValue().executable());
+ Assertions.assertEquals(Lists.newArrayList("Hello!"), templateCaptor.getValue().arguments());
+ // Nothing is fetched into the staging directory on behalf of the job executor.
+ String[] staged = context.stagingDir().list();
+ Assertions.assertTrue(staged == null || staged.length == 0);
}
@Test
@@ -914,7 +925,7 @@ public class TestJobManager {
"--greeting", "{{greeting:-Hi}}", "--note", "{{note:-}}", "{{name}}"));
when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))
.thenReturn(jobTemplateEntity);
- when(jobExecutor.submitJob(any())).thenReturn("job_execution_id_for_test");
+ when(jobExecutor.submitJob(any(), any())).thenReturn("job_execution_id_for_test");
doNothing().when(entityStore).put(any(JobEntity.class), anyBoolean());
JobEntity jobEntity =
@@ -948,7 +959,7 @@ public class TestJobManager {
() -> jobManager.runJob(metalake, jobTemplateEntity.name(), Collections.emptyMap()));
Assertions.assertTrue(e.getMessage().contains("[a, b]"), e.getMessage());
- verify(jobExecutor, never()).submitJob(any());
+ verify(jobExecutor, never()).submitJob(any(), any());
verify(entityStore, never()).put(any(JobEntity.class), anyBoolean());
// Nothing was created for the job, not even the directory its staging directory would live in.
Assertions.assertFalse(jobManager.jobStagingDir(0L).getParentFile().exists());
@@ -960,6 +971,38 @@ public class TestJobManager {
.when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))
.thenAnswer(a -> null);
+ // Both environment keys resolve to the same key, which fails the resolution after the
+ // staging directory is created.
+ ShellJobTemplate shellJobTemplate =
+ ShellJobTemplate.builder()
+ .withName("shell_job_with_duplicate_keys")
+ .withExecutable("/bin/echo")
+ .withEnvironments(ImmutableMap.of("{{a}}", "1", "{{b}}", "2"))
+ .build();
+ JobTemplateEntity jobTemplateEntity = toJobTemplateEntity(shellJobTemplate);
+ when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))
+ .thenReturn(jobTemplateEntity);
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ jobManager.runJob(
+ metalake, jobTemplateEntity.name(), ImmutableMap.of("a", "SAME", "b", "SAME")));
+
+ verify(jobExecutor, never()).submitJob(any(), any());
+ // The staging directory was created, and removed again when the template failed to resolve.
+ File jobRunsDir = jobManager.jobStagingDir(0L).getParentFile();
+ Assertions.assertTrue(jobRunsDir.isDirectory(), "The job staging directory was never created");
+ Assertions.assertArrayEquals(new String[0], jobRunsDir.list());
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ public void testRunJobRemovesStagingDirWhenResourceFetchFails() throws IOException {
+ mockedMetalake
+ .when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))
+ .thenAnswer(a -> null);
+
ShellJobTemplate shellJobTemplate =
ShellJobTemplate.builder()
.withName("shell_job_with_missing_executable")
@@ -968,13 +1011,16 @@ public class TestJobManager {
JobTemplateEntity jobTemplateEntity = toJobTemplateEntity(shellJobTemplate);
when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))
.thenReturn(jobTemplateEntity);
+ // The default implementation localizes the job template into the staging directory, which
+ // fails for the missing executable, before the job reaches submitJob(JobTemplate).
+ when(jobExecutor.submitJob(any(), any())).thenCallRealMethod();
Assertions.assertThrows(
RuntimeException.class,
() -> jobManager.runJob(metalake, jobTemplateEntity.name(), Collections.emptyMap()));
- verify(jobExecutor, never()).submitJob(any());
- // The staging directory was created, and removed again when the template failed to resolve.
+ verify(jobExecutor, never()).submitJob(any(JobTemplate.class));
+ // The staging directory was created, and removed again when the job failed to be submitted.
File jobRunsDir = jobManager.jobStagingDir(0L).getParentFile();
Assertions.assertTrue(jobRunsDir.isDirectory(), "The job staging directory was never created");
Assertions.assertArrayEquals(new String[0], jobRunsDir.list());
@@ -1015,7 +1061,7 @@ public class TestJobManager {
JobTemplateEntity shellJobTemplate =
newShellJobTemplateEntity("shell_job", "A shell job template");
- when(jobExecutor.submitJob(any())).thenReturn("job_execution_id_for_test");
+ when(jobExecutor.submitJob(any(), any())).thenReturn("job_execution_id_for_test");
doNothing().when(entityStore).put(any(JobEntity.class), anyBoolean());
// Use a fixed job ID so that both runs resolve to the same staging directory.
@@ -1727,8 +1773,9 @@ public class TestJobManager {
try {
JobTemplate jobTemplate =
new JobTemplateResolver(newShellJobTemplateEntity("shell_job", "echo"))
- .resolve(Collections.emptyMap(), jobStagingDir);
- String executionId = ownerExecutor.submitJob(jobTemplate);
+ .resolve(Collections.emptyMap());
+ String executionId =
+ ownerExecutor.submitJob(new JobContext(1L, metalake, jobStagingDir), jobTemplate);
Awaitility.await()
.atMost(1, TimeUnit.MINUTES)
.until(() -> ownerExecutor.getJobStatus(executionId) == JobHandle.Status.SUCCEEDED);
diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.java b/core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.java
index 5ea282f795..d6fffd693f 100644
--- a/core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.java
+++ b/core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.java
@@ -20,93 +20,20 @@ package org.apache.gravitino.job;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
-import com.sun.net.httpserver.HttpServer;
-import java.io.File;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
-import java.util.UUID;
-import java.util.stream.Collectors;
-import org.apache.commons.io.FileUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.JobTemplateEntity;
-import org.apache.gravitino.utils.FileFetcher;
import org.apache.gravitino.utils.NamespaceUtil;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestJobTemplateResolver {
- private static File tempDir;
- private File tempStagingDir;
-
- @BeforeAll
- public static void setUpClass() throws IOException {
- // Create a temporary directory for testing
- tempDir = Files.createTempDirectory("job-template-test").toFile();
- }
-
- @AfterAll
- public static void tearDownClass() throws IOException {
- // Clean up the temporary directory after all tests
- if (tempDir != null && tempDir.exists()) {
- FileUtils.deleteDirectory(tempDir);
- tempDir = null;
- }
- }
-
- @BeforeEach
- public void setUp() throws IOException {
- // Create a temporary staging directory for each test
- tempStagingDir = Files.createTempDirectory(tempDir.toPath(), "staging").toFile();
- }
-
- @AfterEach
- public void tearDown() throws IOException {
- // Clean up the temporary staging directory after each test
- if (tempStagingDir != null && tempStagingDir.exists()) {
- FileUtils.deleteDirectory(tempStagingDir);
- tempStagingDir = null;
- }
- }
-
@Test
- public void testFetchFilesFromUir() throws IOException {
- File testFile1 = Files.createTempFile(tempDir.toPath(), "testFile1", ".txt").toFile();
- String result =
- JobTemplateResolver.fetchFileFromUri(
- testFile1.toURI().toString(), tempStagingDir, 30 * 1000);
- File resultFile = new File(result);
- Assertions.assertEquals(testFile1.getName(), resultFile.getName());
-
- File testFile2 = Files.createTempFile(tempDir.toPath(), "testFile2", ".txt").toFile();
- File testFile3 = Files.createTempFile(tempDir.toPath(), "testFile3", ".txt").toFile();
-
- List<String> expectedUris =
- Lists.newArrayList(testFile2.toURI().toString(), testFile3.toURI().toString());
- List<String> resultUris =
- JobTemplateResolver.fetchFilesFromUri(expectedUris, tempStagingDir, 30 * 1000);
-
- Assertions.assertEquals(2, resultUris.size());
- List<String> resultFileNames =
- resultUris.stream().map(uri -> new File(uri).getName()).collect(Collectors.toList());
- Assertions.assertTrue(resultFileNames.contains(testFile2.getName()));
- Assertions.assertTrue(resultFileNames.contains(testFile3.getName()));
- }
-
- @Test
- public void testCreateShellRuntimeJobTemplate() throws IOException {
- File testScript1 = Files.createTempFile(tempDir.toPath(), "testScript1", ".sh").toFile();
- File testScript2 = Files.createTempFile(tempDir.toPath(), "testScript2", ".sh").toFile();
+ public void testCreateShellRuntimeJobTemplate() {
+ String testScript1 = "https://repo.example.com/jobs/testScript1.sh";
+ String testScript2 = "https://repo.example.com/jobs/testScript2.sh";
ShellJobTemplate shellJobTemplate =
ShellJobTemplate.builder()
@@ -116,8 +43,7 @@ public class TestJobTemplateResolver {
.withArguments(Lists.newArrayList("arg1", "arg2", "{{arg3}}, {{arg4}}"))
.withEnvironments(ImmutableMap.of("ENV_VAR1", "{{val1}}", "ENV_VAR2", "{{val2}}"))
.withCustomFields(ImmutableMap.of("customField1", "{{customVal1}}"))
- .withScripts(
- Lists.newArrayList(testScript1.toURI().toString(), testScript2.toURI().toString()))
+ .withScripts(Lists.newArrayList(testScript1, testScript2))
.build();
JobTemplateEntity entity =
@@ -140,12 +66,11 @@ public class TestJobTemplateResolver {
"arg4", "value4",
"val1", "value1",
"val2", "value2",
- "customVal1", "customValue1"),
- tempStagingDir);
+ "customVal1", "customValue1"));
Assertions.assertEquals(shellJobTemplate.name(), result.name());
Assertions.assertEquals(shellJobTemplate.comment(), result.comment());
- Assertions.assertEquals("echo", new File(result.executable).getName());
+ Assertions.assertEquals("/bin/echo", result.executable());
Assertions.assertEquals(
Lists.newArrayList("arg1", "arg2", "value3, value4"), result.arguments());
Assertions.assertEquals(
@@ -153,19 +78,14 @@ public class TestJobTemplateResolver {
Assertions.assertEquals(ImmutableMap.of("customField1", "customValue1"), result.customFields());
Assertions.assertEquals(2, ((ShellJobTemplate) result).scripts().size());
- List<String> scriptNames =
- ((ShellJobTemplate) result)
- .scripts().stream()
- .map(script -> new File(script).getName())
- .collect(Collectors.toList());
- Assertions.assertTrue(scriptNames.contains(testScript1.getName()));
- Assertions.assertTrue(scriptNames.contains(testScript2.getName()));
+ Assertions.assertEquals(
+ Lists.newArrayList(testScript1, testScript2), ((ShellJobTemplate) result).scripts());
}
@Test
- public void testCreateShellRuntimeJobTemplateWithReplacementsInScripts() throws IOException {
- File testScript1 = Files.createTempFile(tempDir.toPath(), "testScript1", ".sh").toFile();
- File testScript2 = Files.createTempFile(tempDir.toPath(), "testScript2", ".sh").toFile();
+ public void testCreateShellRuntimeJobTemplateWithReplacementsInScripts() {
+ String testScript1 = "https://repo.example.com/jobs/testScript1.sh";
+ String testScript2 = "https://repo.example.com/jobs/testScript2.sh";
ShellJobTemplate shellJobTemplate =
ShellJobTemplate.builder()
@@ -177,8 +97,8 @@ public class TestJobTemplateResolver {
.withCustomFields(ImmutableMap.of("customField1", "{{customVal1}}"))
.withScripts(
Lists.newArrayList(
- testScript1.toURI().toString().replace("testScript1", "{{scriptName1}}"),
- testScript2.toURI().toString().replace("testScript2", "{{scriptName2}}")))
+ testScript1.replace("testScript1", "{{scriptName1}}"),
+ testScript2.replace("testScript2", "{{scriptName2}}")))
.build();
JobTemplateEntity entity =
@@ -203,43 +123,37 @@ public class TestJobTemplateResolver {
"val2", "value2",
"customVal1", "customValue1",
"scriptName1", "testScript1",
- "scriptName2", "testScript2"),
- tempStagingDir);
+ "scriptName2", "testScript2"));
- Assertions.assertEquals("echo", new File(result.executable).getName());
+ Assertions.assertEquals("/bin/echo", result.executable());
Assertions.assertEquals(2, ((ShellJobTemplate) result).scripts().size());
- List<String> scriptNames =
- ((ShellJobTemplate) result)
- .scripts().stream()
- .map(script -> new File(script).getName())
- .collect(Collectors.toList());
- Assertions.assertTrue(scriptNames.contains(testScript1.getName()));
- Assertions.assertTrue(scriptNames.contains(testScript2.getName()));
+ Assertions.assertEquals(
+ Lists.newArrayList(testScript1, testScript2), ((ShellJobTemplate) result).scripts());
}
@Test
- public void testCreateSparkRuntimeJobTemplate() throws IOException {
- File executable = Files.createTempFile(tempDir.toPath(), "testSparkJob", ".jar").toFile();
- File jar1 = Files.createTempFile(tempDir.toPath(), "testJar1", ".jar").toFile();
- File jar2 = Files.createTempFile(tempDir.toPath(), "testJar2", ".jar").toFile();
+ public void testCreateSparkRuntimeJobTemplate() {
+ String executable = "https://repo.example.com/jobs/testSparkJob.jar";
+ String jar1 = "https://repo.example.com/jobs/testJar1.jar";
+ String jar2 = "https://repo.example.com/jobs/testJar2.jar";
- File file1 = Files.createTempFile(tempDir.toPath(), "testFile1", ".txt").toFile();
- File file2 = Files.createTempFile(tempDir.toPath(), "testFile2", ".txt").toFile();
+ String file1 = "https://repo.example.com/jobs/testFile1.txt";
+ String file2 = "https://repo.example.com/jobs/testFile2.txt";
- File archive1 = Files.createTempFile(tempDir.toPath(), "testArchive1", ".zip").toFile();
+ String archive1 = "https://repo.example.com/jobs/testArchive1.zip";
SparkJobTemplate sparkJobTemplate =
SparkJobTemplate.builder()
.withName("testSparkJob")
.withComment("This is a test Spark job template")
- .withExecutable(executable.toURI().toString())
+ .withExecutable(executable)
.withClassName("org.apache.gravitino.TestSparkJob")
.withArguments(Lists.newArrayList("arg1", "arg2", "{{arg3}}"))
.withEnvironments(ImmutableMap.of("ENV_VAR1", "{{val1}}", "ENV_VAR2", "{{val2}}"))
.withCustomFields(ImmutableMap.of("customField1", "{{customVal1}}"))
- .withJars(Lists.newArrayList(jar1.toURI().toString(), jar2.toURI().toString()))
- .withFiles(Lists.newArrayList(file1.toURI().toString(), file2.toURI().toString()))
- .withArchives(Lists.newArrayList(archive1.toURI().toString()))
+ .withJars(Lists.newArrayList(jar1, jar2))
+ .withFiles(Lists.newArrayList(file1, file2))
+ .withArchives(Lists.newArrayList(archive1))
.withConfigs(
ImmutableMap.of(
"spark.executor.memory",
@@ -269,38 +183,24 @@ public class TestJobTemplateResolver {
"val2", "value2",
"customVal1", "customValue1",
"executor-mem", "4g",
- "driver-cores", "2"),
- tempStagingDir);
+ "driver-cores", "2"));
Assertions.assertEquals(sparkJobTemplate.name(), result.name());
Assertions.assertEquals(sparkJobTemplate.comment(), result.comment());
- Assertions.assertEquals(executable.getName(), new File(result.executable).getName());
+ Assertions.assertEquals(executable, result.executable());
Assertions.assertEquals(Lists.newArrayList("arg1", "arg2", "value3"), result.arguments());
Assertions.assertEquals(
ImmutableMap.of("ENV_VAR1", "value1", "ENV_VAR2", "value2"), result.environments());
Assertions.assertEquals(ImmutableMap.of("customField1", "customValue1"), result.customFields());
Assertions.assertEquals(2, ((SparkJobTemplate) result).jars().size());
- List<String> jarNames =
- ((SparkJobTemplate) result)
- .jars().stream().map(jar -> new File(jar).getName()).collect(Collectors.toList());
- Assertions.assertTrue(jarNames.contains(jar1.getName()));
- Assertions.assertTrue(jarNames.contains(jar2.getName()));
+ Assertions.assertEquals(Lists.newArrayList(jar1, jar2), ((SparkJobTemplate) result).jars());
Assertions.assertEquals(2, ((SparkJobTemplate) result).files().size());
- List<String> fileNames =
- ((SparkJobTemplate) result)
- .files().stream().map(file -> new File(file).getName()).collect(Collectors.toList());
- Assertions.assertTrue(fileNames.contains(file1.getName()));
- Assertions.assertTrue(fileNames.contains(file2.getName()));
+ Assertions.assertEquals(Lists.newArrayList(file1, file2), ((SparkJobTemplate) result).files());
Assertions.assertEquals(1, ((SparkJobTemplate) result).archives().size());
- List<String> archiveNames =
- ((SparkJobTemplate) result)
- .archives().stream()
- .map(archive -> new File(archive).getName())
- .collect(Collectors.toList());
- Assertions.assertTrue(archiveNames.contains(archive1.getName()));
+ Assertions.assertEquals(Lists.newArrayList(archive1), ((SparkJobTemplate) result).archives());
Assertions.assertEquals(
ImmutableMap.of("spark.executor.memory", "4g", "spark.driver.cores", "2"),
@@ -308,35 +208,32 @@ public class TestJobTemplateResolver {
}
@Test
- public void testCreateSparkRuntimeJobTemplateWithReplacements() throws IOException {
- File executable = Files.createTempFile(tempDir.toPath(), "testSparkJob", ".jar").toFile();
- File jar1 = Files.createTempFile(tempDir.toPath(), "testJar1", ".jar").toFile();
- File jar2 = Files.createTempFile(tempDir.toPath(), "testJar2", ".jar").toFile();
+ public void testCreateSparkRuntimeJobTemplateWithReplacements() {
+ String executable = "https://repo.example.com/jobs/testSparkJob.jar";
+ String jar1 = "https://repo.example.com/jobs/testJar1.jar";
+ String jar2 = "https://repo.example.com/jobs/testJar2.jar";
- File file1 = Files.createTempFile(tempDir.toPath(), "testFile1", ".txt").toFile();
- File file2 = Files.createTempFile(tempDir.toPath(), "testFile2", ".txt").toFile();
+ String file1 = "https://repo.example.com/jobs/testFile1.txt";
+ String file2 = "https://repo.example.com/jobs/testFile2.txt";
- File archive1 = Files.createTempFile(tempDir.toPath(), "testArchive1", ".zip").toFile();
+ String archive1 = "https://repo.example.com/jobs/testArchive1.zip";
SparkJobTemplate sparkJobTemplate =
SparkJobTemplate.builder()
.withName("testSparkJob")
.withComment("This is a test Spark job template")
- .withExecutable(executable.toURI().toString().replace("test", "{{env}}"))
+ .withExecutable(executable.replace("test", "{{env}}"))
.withClassName("org.apache.gravitino.TestSparkJob")
.withArguments(Lists.newArrayList("arg1", "arg2", "{{arg3}}"))
.withEnvironments(ImmutableMap.of("ENV_VAR1", "{{val1}}", "ENV_VAR2", "{{val2}}"))
.withCustomFields(ImmutableMap.of("customField1", "{{customVal1}}"))
.withJars(
Lists.newArrayList(
- jar1.toURI().toString().replace("test", "{{env}}"),
- jar2.toURI().toString().replace("test", "{{env}}")))
+ jar1.replace("test", "{{env}}"), jar2.replace("test", "{{env}}")))
.withFiles(
Lists.newArrayList(
- file1.toURI().toString().replace("test", "{{env}}"),
- file2.toURI().toString().replace("test", "{{env}}")))
- .withArchives(
- Lists.newArrayList(archive1.toURI().toString().replace("test", "{{env}}")))
+ file1.replace("test", "{{env}}"), file2.replace("test", "{{env}}")))
+ .withArchives(Lists.newArrayList(archive1.replace("test", "{{env}}")))
.withConfigs(
ImmutableMap.of(
"spark.executor.memory",
@@ -367,36 +264,22 @@ public class TestJobTemplateResolver {
"customVal1", "customValue1",
"executor-mem", "4g",
"driver-cores", "2",
- "env", "test"),
- tempStagingDir);
+ "env", "test"));
- Assertions.assertEquals(executable.getName(), new File(result.executable).getName());
+ Assertions.assertEquals(executable, result.executable());
Assertions.assertEquals(Lists.newArrayList("arg1", "arg2", "value3"), result.arguments());
Assertions.assertEquals(
ImmutableMap.of("ENV_VAR1", "value1", "ENV_VAR2", "value2"), result.environments());
Assertions.assertEquals(ImmutableMap.of("customField1", "customValue1"), result.customFields());
Assertions.assertEquals(2, ((SparkJobTemplate) result).jars().size());
- List<String> jarNames =
- ((SparkJobTemplate) result)
- .jars().stream().map(jar -> new File(jar).getName()).collect(Collectors.toList());
- Assertions.assertTrue(jarNames.contains(jar1.getName()));
- Assertions.assertTrue(jarNames.contains(jar2.getName()));
+ Assertions.assertEquals(Lists.newArrayList(jar1, jar2), ((SparkJobTemplate) result).jars());
Assertions.assertEquals(2, ((SparkJobTemplate) result).files().size());
- List<String> fileNames =
- ((SparkJobTemplate) result)
- .files().stream().map(file -> new File(file).getName()).collect(Collectors.toList());
- Assertions.assertTrue(fileNames.contains(file1.getName()));
- Assertions.assertTrue(fileNames.contains(file2.getName()));
+ Assertions.assertEquals(Lists.newArrayList(file1, file2), ((SparkJobTemplate) result).files());
Assertions.assertEquals(1, ((SparkJobTemplate) result).archives().size());
- List<String> archiveNames =
- ((SparkJobTemplate) result)
- .archives().stream()
- .map(archive -> new File(archive).getName())
- .collect(Collectors.toList());
- Assertions.assertTrue(archiveNames.contains(archive1.getName()));
+ Assertions.assertEquals(Lists.newArrayList(archive1), ((SparkJobTemplate) result).archives());
}
@Test
@@ -425,22 +308,40 @@ public class TestJobTemplateResolver {
shellTemplateEntity(
Lists.newArrayList("--table", "{{table}}", "--mode", "{{mode:-full}}", "{{note:-}}"));
- JobTemplate result =
- new JobTemplateResolver(entity).resolve(ImmutableMap.of("table", "t"), tempStagingDir);
+ JobTemplate result = new JobTemplateResolver(entity).resolve(ImmutableMap.of("table", "t"));
Assertions.assertEquals(
Lists.newArrayList("--table", "t", "--mode", "full", ""), result.arguments());
}
@Test
- public void testCreateFailsBeforeFetchingOnMissingParameters() {
+ public void testCreateFailsOnMissingParameters() {
JobTemplateEntity entity = shellTemplateEntity(Lists.newArrayList("{{table}}"));
- Assertions.assertThrows(
- IllegalArgumentException.class,
- () -> new JobTemplateResolver(entity).resolve(ImmutableMap.of(), tempStagingDir));
- // The executable is not fetched when a parameter is missing.
- String[] staged = tempStagingDir.list();
- Assertions.assertTrue(staged == null || staged.length == 0);
+ IllegalArgumentException e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new JobTemplateResolver(entity).resolve(ImmutableMap.of()));
+ Assertions.assertTrue(e.getMessage().contains("table"), e.getMessage());
+ }
+
+ @Test
+ public void testResolveKeepsResourceUris() {
+ SparkJobTemplate template =
+ SparkJobTemplate.builder()
+ .withName("spark_job")
+ .withExecutable("https://repo.example.com/{{version}}/app.jar")
+ .withClassName("org.example.App")
+ .withJars(Lists.newArrayList("s3a://bucket/lib-{{version}}.jar"))
+ .withFiles(Lists.newArrayList("hdfs://nn/conf/app.conf"))
+ .build();
+
+ SparkJobTemplate result =
+ (SparkJobTemplate)
+ new JobTemplateResolver(toEntity(template)).resolve(ImmutableMap.of("version", "1.0"));
+
+ Assertions.assertEquals("https://repo.example.com/1.0/app.jar", result.executable());
+ Assertions.assertEquals(Lists.newArrayList("s3a://bucket/lib-1.0.jar"), result.jars());
+ Assertions.assertEquals(Lists.newArrayList("hdfs://nn/conf/app.conf"), result.files());
}
@Test
@@ -457,103 +358,10 @@ public class TestJobTemplateResolver {
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
- new JobTemplateResolver(entity)
- .resolve(ImmutableMap.of("a", "SAME", "b", "SAME"), tempStagingDir));
+ new JobTemplateResolver(entity).resolve(ImmutableMap.of("a", "SAME", "b", "SAME")));
Assertions.assertTrue(e.getMessage().contains("SAME"), e.getMessage());
}
- private static HttpServer createLoopbackHttpServer(String response) throws IOException {
- HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
- server.createContext(
- "/artifact.jar",
- exchange -> {
- byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
- exchange.sendResponseHeaders(200, bytes.length);
- try (OutputStream outputStream = exchange.getResponseBody()) {
- outputStream.write(bytes);
- }
- });
- return server;
- }
-
- @Test
- public void testFetchFileFromUriWithMissingLocalFileShouldFail() throws IOException {
- File stagingDir = tempStagingDir;
-
- Path missingFilePath =
- Path.of(System.getProperty("java.io.tmpdir"), "missing-job-file-" + UUID.randomUUID());
- String uri = missingFilePath.toUri().toString();
-
- Assertions.assertThrows(
- RuntimeException.class, () -> JobTemplateResolver.fetchFileFromUri(uri, stagingDir, 1000));
- }
-
- @Test
- public void testFetchFileFromUriSsrfBlocked() {
- File stagingDir = tempStagingDir;
- FileFetcher.get().initialize(true);
-
- // Loopback address
- RuntimeException e1 =
- Assertions.assertThrows(
- RuntimeException.class,
- () ->
- JobTemplateResolver.fetchFileFromUri(
- "http://127.0.0.1:8090/configs", stagingDir, 1000));
- assertRemoteUriBlockedMessage(e1);
-
- // AWS / GCP / Azure cloud-metadata endpoint (link-local 169.254.x.x)
- RuntimeException e2 =
- Assertions.assertThrows(
- RuntimeException.class,
- () ->
- JobTemplateResolver.fetchFileFromUri(
- "http://169.254.169.254/latest/meta-data/", stagingDir, 1000));
- assertRemoteUriBlockedMessage(e2);
-
- // RFC-1918 private range
- RuntimeException e3 =
- Assertions.assertThrows(
- RuntimeException.class,
- () -> JobTemplateResolver.fetchFileFromUri("http://192.168.1.1/", stagingDir, 1000));
- assertRemoteUriBlockedMessage(e3);
-
- // Alibaba Cloud / Oracle Cloud metadata endpoint
- RuntimeException e4 =
- Assertions.assertThrows(
- RuntimeException.class,
- () ->
- JobTemplateResolver.fetchFileFromUri("http://100.100.100.200/", stagingDir, 1000));
- assertRemoteUriBlockedMessage(e4);
- }
-
- @Test
- public void testFetchFileFromUriShouldAllowLocalhostWhenBlockingDisabled() throws Exception {
- File stagingDir = tempStagingDir;
- HttpServer server = createLoopbackHttpServer("job artifact");
-
- try {
- server.start();
- int port = server.getAddress().getPort();
- FileFetcher.get().initialize(false);
-
- String fetchedFile =
- JobTemplateResolver.fetchFileFromUri(
- String.format("http://127.0.0.1:%d/artifact.jar", port), stagingDir, 1000);
-
- Assertions.assertEquals("job artifact", Files.readString(Path.of(fetchedFile)));
- } finally {
- FileFetcher.get().initialize(true);
- server.stop(0);
- }
- }
-
- private static void assertRemoteUriBlockedMessage(RuntimeException exception) {
- Assertions.assertTrue(exception.getCause().getMessage().contains("Gravitino server side"));
- Assertions.assertTrue(
- exception.getCause().getMessage().contains(FileFetcher.BLOCK_UNSAFE_REMOTE_URI_CONFIG));
- }
-
private static JobTemplateEntity shellTemplateEntity(List<String> arguments) {
return toEntity(
ShellJobTemplate.builder()
diff --git a/core/src/test/java/org/apache/gravitino/job/local/TestLocalJobExecutor.java b/core/src/test/java/org/apache/gravitino/job/local/TestLocalJobExecutor.java
index 0fd29d9d46..610c8a9bf6 100644
--- a/core/src/test/java/org/apache/gravitino/job/local/TestLocalJobExecutor.java
+++ b/core/src/test/java/org/apache/gravitino/job/local/TestLocalJobExecutor.java
@@ -41,8 +41,10 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.connector.job.JobContext;
import org.apache.gravitino.connector.job.JobExecutionInfo;
import org.apache.gravitino.connector.job.JobExecutor;
import org.apache.gravitino.exceptions.NoSuchJobException;
@@ -80,6 +82,8 @@ public class TestLocalJobExecutor {
private static JobExecutor jobExecutor;
+ private static final AtomicLong JOB_IDS = new AtomicLong();
+
private static JobTemplateEntity jobTemplateEntity;
private static File stagingRoot;
@@ -152,9 +156,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Assertions.assertNotNull(jobId);
Awaitility.await()
@@ -170,6 +174,58 @@ public class TestLocalJobExecutor {
Assertions.assertEquals(JobHandle.Status.SUCCEEDED, jobExecutor.getJobStatus(jobId));
}
+ @Test
+ public void testJobRunsInStagingDirOfJobContext() throws IOException {
+ // The template's executable and script live in the test resources, not in the job directory.
+ JobTemplate template = newRuntimeJobTemplate();
+ File sourceDir = new File(template.executable()).getParentFile();
+ File jobDir = new File(workingDir, "context-dir");
+ Assertions.assertTrue(jobDir.mkdirs());
+
+ String jobId = submit(jobExecutor, template, jobDir);
+ Awaitility.await()
+ .atMost(3, TimeUnit.MINUTES)
+ .until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
+
+ // The executor localizes the resources into the job directory and runs the job there.
+ Assertions.assertTrue(new File(jobDir, "test-job.sh").exists());
+ Assertions.assertTrue(new File(jobDir, "common.sh").exists());
+ Assertions.assertTrue(new File(jobDir, "output.log").exists());
+ Assertions.assertFalse(new File(sourceDir, "output.log").exists());
+ Assertions.assertTrue(
+ String.join("\n", jobExecutor.getJobStdout(jobId, 100, DEFAULT_TEST_MAX_BYTES))
+ .contains("value1"));
+ }
+
+ @Test
+ public void testRunCommandNameExecutable() throws IOException {
+ // The executable is a command on the PATH, and the script it runs is shipped as a script.
+ File sourceDir = new File(workingDir, "command-src");
+ Assertions.assertTrue(sourceDir.mkdirs());
+ File script = new File(sourceDir, "hello.sh");
+ Files.writeString(script.toPath(), "echo \"hello from $1\"\n");
+ File jobDir = new File(workingDir, "command-job");
+ Assertions.assertTrue(jobDir.mkdirs());
+ JobTemplate template =
+ ShellJobTemplate.builder()
+ .withName("command-job")
+ .withExecutable("bash")
+ .withArguments(Lists.newArrayList("hello.sh", "bash"))
+ .withScripts(Lists.newArrayList(script.getAbsolutePath()))
+ .build();
+
+ String jobId = submit(jobExecutor, template, jobDir);
+ Awaitility.await()
+ .atMost(1, TimeUnit.MINUTES)
+ .until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
+
+ Assertions.assertEquals(
+ Collections.singletonList("hello from bash"),
+ jobExecutor.getJobStdout(jobId, 100, DEFAULT_TEST_MAX_BYTES));
+ // Only the script is localized, there is no file named after the command.
+ Assertions.assertFalse(new File(jobDir, "bash").exists());
+ }
+
@Test
public void testJobOwnership() throws IOException {
LocalJobExecutor executor = (LocalJobExecutor) jobExecutor;
@@ -178,9 +234,8 @@ public class TestLocalJobExecutor {
JobTemplate template =
new JobTemplateResolver(jobTemplateEntity)
- .resolve(
- ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"), workingDir);
- String jobId = executor.submitJob(template);
+ .resolve(ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"));
+ String jobId = submit(executor, template, workingDir);
Assertions.assertTrue(
jobId.matches("local-job-" + executor.executorId() + "-[0-9a-f-]{36}"), jobId);
Assertions.assertTrue(executor.ownsJob(jobId));
@@ -210,9 +265,9 @@ public class TestLocalJobExecutor {
try {
executor.initialize(
withStagingDir(ImmutableMap.of(LocalJobExecutorConfigs.MAX_RUNNING_JOBS, "2")));
- String jobId1 = executor.submitJob(newSleepJobTemplate("sleep-1"));
- String jobId2 = executor.submitJob(newSleepJobTemplate("sleep-2"));
- String jobId3 = executor.submitJob(newSleepJobTemplate("sleep-3"));
+ String jobId1 = submitSleepJob(executor, "sleep-1");
+ String jobId2 = submitSleepJob(executor, "sleep-2");
+ String jobId3 = submitSleepJob(executor, "sleep-3");
// Up to maxRunningJobs jobs run at the same time, the others wait in the queue.
Awaitility.await()
@@ -239,9 +294,9 @@ public class TestLocalJobExecutor {
"arg2", "fail",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Assertions.assertNotNull(jobId);
Awaitility.await()
@@ -266,27 +321,33 @@ public class TestLocalJobExecutor {
ImmutableMap.of(LocalJobExecutorConfigs.SPARK_HOME, sparkHome.getAbsolutePath())));
try {
+ File sparkJar = new File(workingDir, "spark-demo.jar");
+ Assertions.assertTrue(sparkJar.createNewFile());
+ File jobDir = new File(workingDir, "spark-job");
+ Assertions.assertTrue(jobDir.mkdirs());
SparkJobTemplate template =
SparkJobTemplate.builder()
.withName("spark-job")
- .withExecutable(new File(workingDir, "spark-demo.jar").getAbsolutePath())
+ .withExecutable(sparkJar.getAbsolutePath())
.withClassName("com.example.MainClass")
.build();
// spark-submit does not exist, the job is rejected at submission instead of being queued.
int indexCountBeforeRejection = outputIndexFileCount();
IllegalArgumentException e =
- Assertions.assertThrows(IllegalArgumentException.class, () -> exec.submitJob(template));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> submit(exec, template, jobDir));
Assertions.assertTrue(e.getMessage().contains("spark-submit is not found or not executable"));
- // A rejected submission leaves no output index behind.
+ // A rejected submission leaves no output index behind, and fetches nothing.
Assertions.assertEquals(indexCountBeforeRejection, outputIndexFileCount());
+ Assertions.assertArrayEquals(new String[0], jobDir.list());
// Once spark-submit is available, the same job is accepted.
File sparkSubmit = new File(sparkHome, "bin/spark-submit");
FileUtils.writeStringToFile(sparkSubmit, "#!/bin/sh\nexit 0\n", "UTF-8");
Assertions.assertTrue(sparkSubmit.setExecutable(true));
- String jobId = exec.submitJob(template);
+ String jobId = submit(exec, template, jobDir);
Assertions.assertNotNull(jobId);
Awaitility.await()
.atMost(1, TimeUnit.MINUTES)
@@ -304,9 +365,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -352,9 +413,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -388,12 +449,10 @@ public class TestLocalJobExecutor {
// Submit two jobs to a single-threaded executor - the second one stays QUEUED until the
// first (which sleeps for a few seconds) finishes.
- JobTemplate templateA =
- new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDirA);
- JobTemplate templateB =
- new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDirB);
- exec.submitJob(templateA);
- String jobIdB = exec.submitJob(templateB);
+ JobTemplate templateA = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
+ JobTemplate templateB = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
+ submit(exec, templateA, workingDirA);
+ String jobIdB = submit(exec, templateB, workingDirB);
Assertions.assertEquals(JobHandle.Status.QUEUED, exec.getJobStatus(jobIdB));
Assertions.assertEquals(
@@ -419,9 +478,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -448,9 +507,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -478,9 +537,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -509,9 +568,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -541,9 +600,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -564,9 +623,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -590,9 +649,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -619,9 +678,9 @@ public class TestLocalJobExecutor {
"arg2", "success",
"var", "value3");
- JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);
+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf);
- String jobId = jobExecutor.submitJob(template);
+ String jobId = submit(jobExecutor, template, workingDir);
Assertions.assertNotNull(jobId);
// sleep a while to ensure the job is running.
Thread.sleep(1000);
@@ -666,10 +725,9 @@ public class TestLocalJobExecutor {
.withTemplateContent(trapContent)
.withAuditInfo(AuditInfo.EMPTY)
.build();
- JobTemplate template =
- new JobTemplateResolver(trapTemplate).resolve(ImmutableMap.of(), workingDir);
+ JobTemplate template = new JobTemplateResolver(trapTemplate).resolve(ImmutableMap.of());
- String jobId = executor.submitJob(template);
+ String jobId = submit(executor, template, workingDir);
awaitReadyMarker();
Assertions.assertEquals(JobHandle.Status.STARTED, executor.getJobStatus(jobId));
@@ -711,10 +769,9 @@ public class TestLocalJobExecutor {
.withTemplateContent(content)
.withAuditInfo(AuditInfo.EMPTY)
.build();
- JobTemplate template =
- new JobTemplateResolver(templateEntity).resolve(ImmutableMap.of(), workingDir);
+ JobTemplate template = new JobTemplateResolver(templateEntity).resolve(ImmutableMap.of());
- String jobId = executor.submitJob(template);
+ String jobId = submit(executor, template, workingDir);
awaitReadyMarker();
Assertions.assertEquals(JobHandle.Status.STARTED, executor.getJobStatus(jobId));
@@ -739,8 +796,8 @@ public class TestLocalJobExecutor {
"var", "value3");
JobTemplate successTemplate =
- new JobTemplateResolver(jobTemplateEntity).resolve(successJobConf, workingDir);
- String successJobId = jobExecutor.submitJob(successTemplate);
+ new JobTemplateResolver(jobTemplateEntity).resolve(successJobConf);
+ String successJobId = submit(jobExecutor, successTemplate, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(successJobId) == JobHandle.Status.SUCCEEDED);
@@ -758,9 +815,8 @@ public class TestLocalJobExecutor {
"arg2", "fail",
"var", "value3");
- JobTemplate failTemplate =
- new JobTemplateResolver(jobTemplateEntity).resolve(failJobConf, workingDir);
- String failJobId = jobExecutor.submitJob(failTemplate);
+ JobTemplate failTemplate = new JobTemplateResolver(jobTemplateEntity).resolve(failJobConf);
+ String failJobId = submit(jobExecutor, failTemplate, workingDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(failJobId) == JobHandle.Status.FAILED);
@@ -932,7 +988,7 @@ public class TestLocalJobExecutor {
// The status of a finished job is dropped from memory almost right away.
exec.initialize(
withStagingDir(ImmutableMap.of(LocalJobExecutorConfigs.JOB_STATUS_KEEP_TIME_MS, "10")));
- String jobId = exec.submitJob(newRuntimeJobTemplate(workingDir));
+ String jobId = submit(exec, newRuntimeJobTemplate(), workingDir);
// A queued or running job's status never expires, so a missing status means it finished.
Awaitility.await().atMost(3, TimeUnit.MINUTES).until(() -> !hasJobStatus(exec, jobId));
@@ -1245,13 +1301,18 @@ public class TestLocalJobExecutor {
.build();
}
- private static JobTemplate newRuntimeJobTemplate(File jobDir) {
+ private static JobTemplate newRuntimeJobTemplate() {
return new JobTemplateResolver(jobTemplateEntity)
- .resolve(ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"), jobDir);
+ .resolve(ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"));
+ }
+
+ private static String submit(JobExecutor executor, JobTemplate jobTemplate, File jobDir) {
+ return executor.submitJob(
+ new JobContext(JOB_IDS.incrementAndGet(), "test", jobDir), jobTemplate);
}
private static String runSucceededJob(File jobDir) {
- String jobId = jobExecutor.submitJob(newRuntimeJobTemplate(jobDir));
+ String jobId = submit(jobExecutor, newRuntimeJobTemplate(), jobDir);
Awaitility.await()
.atMost(3, TimeUnit.MINUTES)
.until(() -> jobExecutor.getJobStatus(jobId) == JobHandle.Status.SUCCEEDED);
@@ -1328,9 +1389,8 @@ public class TestLocalJobExecutor {
@Test
public void testJobExecutionInfoOfFinishedJobs() throws IOException {
Instant submittedAt = Instant.now();
- String succeededJobId =
- jobExecutor.submitJob(newScriptJobTemplate("succeed", "sleep 1\nexit 0"));
- String failedJobId = jobExecutor.submitJob(newScriptJobTemplate("fail", "sleep 1\nexit 1"));
+ String succeededJobId = submitScriptJob(jobExecutor, "succeed", "sleep 1\nexit 0");
+ String failedJobId = submitScriptJob(jobExecutor, "fail", "sleep 1\nexit 1");
Awaitility.await()
.atMost(1, TimeUnit.MINUTES)
@@ -1357,12 +1417,12 @@ public class TestLocalJobExecutor {
try {
executor.initialize(
withStagingDir(ImmutableMap.of(LocalJobExecutorConfigs.MAX_RUNNING_JOBS, "1")));
- String runningJobId = executor.submitJob(newSleepJobTemplate("sleep"));
+ String runningJobId = submitSleepJob(executor, "sleep");
Awaitility.await()
.atMost(1, TimeUnit.MINUTES)
.until(() -> executor.getJobStatus(runningJobId) == JobHandle.Status.STARTED);
// The other job waits in the queue, as only one job can run at a time.
- String queuedJobId = executor.submitJob(newScriptJobTemplate("queued", "exit 0"));
+ String queuedJobId = submitScriptJob(executor, "queued", "exit 0");
JobExecutionInfo started = executor.getJobExecutionInfo(runningJobId);
Assertions.assertNotNull(started.startedAt());
@@ -1402,11 +1462,11 @@ public class TestLocalJobExecutor {
"10",
LocalJobExecutorConfigs.MAX_RUNNING_JOBS,
"2")));
- String runningJobId = executor.submitJob(newSleepJobTemplate("sleep"));
+ String runningJobId = submitSleepJob(executor, "sleep");
Awaitility.await()
.atMost(1, TimeUnit.MINUTES)
.until(() -> executor.getJobStatus(runningJobId) == JobHandle.Status.STARTED);
- String finishedJobId = executor.submitJob(newScriptJobTemplate("finish", "exit 0"));
+ String finishedJobId = submitScriptJob(executor, "finish", "exit 0");
// The finished job is removed once it has been kept for the keep time, while the running job
// is kept however long it runs.
@@ -1419,26 +1479,32 @@ public class TestLocalJobExecutor {
}
}
- private JobTemplate newSleepJobTemplate(String name) throws IOException {
+ private String submitSleepJob(JobExecutor executor, String name) throws IOException {
// Exec the sleep, so that killing the job process also stops the sleep.
- return newScriptJobTemplate(name, "exec sleep 600");
+ return submitScriptJob(executor, name, "exec sleep 600");
}
- private JobTemplate newScriptJobTemplate(String name, String commands) throws IOException {
- // The job runs in the directory of its executable, so give each job its own directory.
- File jobDir = new File(workingDir, name);
- Assertions.assertTrue(jobDir.mkdirs());
- File script = new File(jobDir, "job.sh");
+ private String submitScriptJob(JobExecutor executor, String name, String commands)
+ throws IOException {
+ // The script lives outside of the job's directory, where the executor localizes it.
+ File sourceDir = new File(workingDir, name + "-src");
+ Assertions.assertTrue(sourceDir.mkdirs());
+ File script = new File(sourceDir, "job.sh");
Files.writeString(script.toPath(), "#!/bin/bash\n" + commands + "\n");
Assertions.assertTrue(script.setExecutable(true));
- return ShellJobTemplate.builder()
- .withName(name)
- .withExecutable(script.getAbsolutePath())
- .withArguments(Collections.emptyList())
- .withEnvironments(Collections.emptyMap())
- .withCustomFields(Collections.emptyMap())
- .withScripts(Collections.emptyList())
- .build();
+ // Each job runs in its own directory.
+ File jobDir = new File(workingDir, name);
+ Assertions.assertTrue(jobDir.mkdirs());
+ JobTemplate jobTemplate =
+ ShellJobTemplate.builder()
+ .withName(name)
+ .withExecutable(script.getAbsolutePath())
+ .withArguments(Collections.emptyList())
+ .withEnvironments(Collections.emptyMap())
+ .withCustomFields(Collections.emptyMap())
+ .withScripts(Collections.emptyList())
+ .build();
+ return submit(executor, jobTemplate, jobDir);
}
}
diff --git a/docs/development/custom-job-executor.md b/docs/development/custom-job-executor.md
index 28efdee10b..377929b7f3 100644
--- a/docs/development/custom-job-executor.md
+++ b/docs/development/custom-job-executor.md
@@ -17,6 +17,38 @@ Gravitino's job system is extensible: you can implement your own job executor
to run jobs in a distributed environment. Refer to the interface `JobExecutor` in the
code [here](https://github.com/apache/gravitino/blob/main/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java).
+### Submit Jobs and Handle Job Resources
+
+Gravitino submits a job by calling `submitJob(JobContext, JobTemplate)`, which a job executor
+implements:
+
+- The `JobTemplate` is the runtime job template. Its placeholders are already replaced with the
+ job configuration, but its resources, that is its executable, scripts, jars, files and archives,
+ are still the URIs written in the template. A shell executable can also be a command name with no
+ path, such as `python`: it is not a file to fetch, but a command to look up in the environment the
+ job runs in. `JobResourceUtils.isCommandName` tells whether it is one; the `local` job executor
+ runs it through the `PATH` of the Gravitino server process.
+- The `JobContext` carries the Gravitino job id, the metalake of the job, and a staging directory on
+ the Gravitino server dedicated to the job. Gravitino creates the staging directory before
+ submitting the job, removes it right away if the job fails to be submitted, and otherwise cleans
+ it up `gravitino.job.stagingDirKeepTimeInMs` after the job finishes.
+
+The job executor decides how to handle the resources:
+
+- A job executor that runs jobs on the Gravitino server fetches them with
+ `JobResourceUtils.localizeJobTemplate(jobTemplate, context.stagingDir())`, which returns a copy of
+ the job template whose resources are the fetched local files. The `local` job executor does this,
+ and runs the job in the staging directory.
+- A job executor that hands jobs to an external job runner can pass the URIs on to it instead, so
+ the resources are fetched where the job actually runs.
+
+`submitJob(JobTemplate)` is deprecated. A job executor that still implements only this method keeps
+working: the default implementation of `submitJob(JobContext, JobTemplate)` localizes the job
+template into the staging directory and passes it on. Gravitino refuses to load a job executor that
+implements neither method.
+
+### Track Jobs
+
Gravitino tracks the jobs by pulling their state with `getJobExecutionInfo`, which every job executor
must implement. It returns the job's status, and when the job actually started and finished. Report
these times whenever the job runner provides them: Gravitino pulls job states only every
@@ -24,6 +56,8 @@ these times whenever the job runner provides them: Gravitino pulls job states on
status change, and a job that starts and finishes between two pulls gets no start time. Once a job
has started, keep reporting its start time in every later state, including the finished one.
+### Register the Job Executor
+
After you implement your own job executor, you need to register it in the Gravitino server by
using the `gravitino.conf` file. For example, if you have implemented a job executor named
`airflow`, you need to configure it as follows:
diff --git a/docs/manage-jobs-in-gravitino.md b/docs/manage-jobs-in-gravitino.md
index 21ba58a285..451819781e 100644
--- a/docs/manage-jobs-in-gravitino.md
+++ b/docs/manage-jobs-in-gravitino.md
@@ -44,8 +44,34 @@ a job runs. See [Placeholders](#placeholders).
}
```
-`executable` and `scripts` must be reachable by the Gravitino server, which accepts local paths and
-HTTP, HTTPS, FTP, and FTPS URLs.
+`executable` and `scripts` are fetched by the job executor. With the `local` job executor they must
+be reachable by the Gravitino server, which accepts local paths and HTTP, HTTPS, FTP, and FTPS URLs.
+
+Each of them is fetched into the job's working directory under the file name of its path, so it
+must point to a file, and two different resources of a template must not share a file name: a run
+is rejected otherwise, instead of one file silently overwriting the other. The same applies to the
+`executable`, `jars`, `files` and `archives` of a Spark template.
+
+`executable` can also be a command name with no path, such as `python` or `bash`. Such a command is
+not fetched, it is looked up where the job runs: the `local` job executor looks it up on the `PATH`
+of the Gravitino server process, and setting `PATH` in `environments` doesn't change that. The
+scripts are still fetched next to it, into the job's working directory, so a template can run a
+script with an installed interpreter:
+
+```json
+{
+ "name": "python_report",
+ "jobType": "shell",
+ "executable": "python",
+ "arguments": ["report.py", "{{date}}"],
+ "scripts": ["https://repo.example.com/jobs/report.py"]
+}
+```
+
+A file name without a path, such as `run.sh`, is a command name too. Earlier versions fetched it as
+a file relative to the working directory of the Gravitino server; to run a file, write its absolute
+path or URI instead. To avoid running a different program than the one that was fetched, a run is
+rejected when a script has the same file name as a command-name `executable`.
<Tabs groupId='language' queryString>
<TabItem value="shell" label="REST">
diff --git a/docs/open-api/jobs.yaml b/docs/open-api/jobs.yaml
index 36a63aa38e..bd194d64c7 100644
--- a/docs/open-api/jobs.yaml
+++ b/docs/open-api/jobs.yaml
@@ -652,7 +652,7 @@ components:
nullable: true
description: The time when the job finished execution, or null if the job has not finished execution yet
runtimeJobTemplate:
- description: The resolved job template that was actually submitted for execution, with placeholders replaced and referenced files downloaded. Null for jobs run before this field was introduced, or if the stored value could not be read back
+ description: The resolved job template that was actually submitted for execution, with placeholders replaced. Its executable, scripts, jars, files and archives are the URIs from the template, the job executor fetches them where it needs them. Null for jobs run before this field was introduced, or if the stored value could not be read back
type: object
nullable: true
allOf:
@@ -965,11 +965,11 @@ components:
"environments": {
"ENV_VAR": "{{env_var}}"
},
- "executable": "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/test-job.sh",
+ "executable": "https://repo.example.com/jobs/test-job.sh",
"jobType": "shell",
"name": "test_run_get",
"scripts": [
- "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/common.sh"
+ "https://repo.example.com/jobs/common.sh"
]
},
{
@@ -986,12 +986,12 @@ components:
"environments": {
"ENV_VAR": "{{env_var}}"
},
- "executable": "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/spark-demo.jar",
+ "executable": "https://repo.example.com/jobs/spark-demo.jar",
"jobType": "spark",
"name": "test_run_get_spark",
"className": "org.apache.spark.examples.SparkPi",
"jars": [
- "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/spark-job.jar"
+ "https://repo.example.com/jobs/spark-job.jar"
]
}
]
@@ -1003,14 +1003,14 @@ components:
"name": "test_run_get",
"jobType": "shell",
"comment": "Test shell job template",
- "executable": "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/test-job.sh",
+ "executable": "https://repo.example.com/jobs/test-job.sh",
"arguments": ["{{arg1}}", "{{arg2}}"],
"environments": {
"ENV_VAR": "{{env_var}}"
},
"customFields": { },
"scripts": [
- "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/common.sh"
+ "https://repo.example.com/jobs/common.sh"
]
}
}
@@ -1030,7 +1030,7 @@ components:
"@type": "updateTemplate",
"newTemplate": {
"@type": "shell",
- "newExecutable": "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/updated-test-job.sh",
+ "newExecutable": "https://repo.example.com/jobs/updated-test-job.sh",
"newArguments": ["{{new_arg1}}", "{{new_arg2}}"],
"newEnvironments": {
"NEW_ENV_VAR": "{{new_env_var}}"
@@ -1039,7 +1039,7 @@ components:
"field1": "value1"
},
"newScripts": [
- "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/updated-common.sh"
+ "https://repo.example.com/jobs/updated-common.sh"
]
}
}
@@ -1062,14 +1062,14 @@ components:
"name": "test_run_get",
"jobType": "shell",
"comment": "Test shell job template",
- "executable": "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/test-job.sh",
+ "executable": "https://repo.example.com/jobs/test-job.sh",
"arguments": ["{{arg1}}", "{{arg2}}"],
"environments": {
"ENV_VAR": "{{env_var}}"
},
"customFields": { },
"scripts": [
- "/var/folders/90/v1d9hxsd6pj8m0jnn6f22tkr0000gn/T/tmpy65fiugc/common.sh"
+ "https://repo.example.com/jobs/common.sh"
],
"audit": {
"createTime": "2025-08-12T02:14:28.205023Z",
@@ -1097,12 +1097,12 @@ components:
"name": "test_run_get",
"jobType": "shell",
"comment": "Test shell job template",
- "executable": "/tmp/gravitino-job-staging/job-12345/test-job.sh",
+ "executable": "https://repo.example.com/jobs/test-job.sh",
"arguments": ["value1", "value2"],
"environments": { },
"customFields": { },
"scripts": [
- "/tmp/gravitino-job-staging/job-12345/common.sh"
+ "https://repo.example.com/jobs/common.sh"
],
"audit": {
"createTime": "2025-08-12T02:00:00.000000Z",
@@ -1151,12 +1151,12 @@ components:
"name": "test_run_get",
"jobType": "shell",
"comment": "Test shell job template",
- "executable": "/tmp/gravitino-job-staging/job-12345/test-job.sh",
+ "executable": "https://repo.example.com/jobs/test-job.sh",
"arguments": ["value1", "value2"],
"environments": { },
"customFields": { },
"scripts": [
- "/tmp/gravitino-job-staging/job-12345/common.sh"
+ "https://repo.example.com/jobs/common.sh"
],
"audit": {
"createTime": "2025-08-12T02:00:00.000000Z",