World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13385] feat(core): Support default values for job template placeholders (#13468)
Jerry Shao014fa11d58d4
diff --git a/core/src/main/java/org/apache/gravitino/job/JobManager.java b/core/src/main/java/org/apache/gravitino/job/JobManager.javaindex 75b609421c..fb1c190b33 100644--- a/core/src/main/java/org/apache/gravitino/job/JobManager.java+++ b/core/src/main/java/org/apache/gravitino/job/JobManager.java@@ -26,7 +26,6 @@ import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import java.io.File;import java.io.IOException;-import java.net.URI;import java.nio.file.DirectoryIteratorException;import java.nio.file.DirectoryStream;import java.nio.file.Files;@@ -44,13 +43,10 @@ import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import java.util.function.Function;-import java.util.regex.Matcher;import java.util.regex.Pattern;-import java.util.stream.Collectors;import javax.annotation.Nullable;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.ArrayUtils;-import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Config;import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;@@ -78,7 +74,6 @@ import org.apache.gravitino.meta.JobEntity;import org.apache.gravitino.meta.JobTemplateEntity;import org.apache.gravitino.metalake.MetalakeManager;import org.apache.gravitino.storage.IdGenerator;-import org.apache.gravitino.utils.FileFetcher;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;import org.apache.gravitino.utils.PrincipalUtils;@@ -93,8 +88,6 @@ public class JobManager implements JobOperationDispatcher {// clock of the job runner being ahead, while dropping obviously invalid times.private static final Duration MAX_REPORTED_TIME_AHEAD = Duration.ofDays(1);- private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{([\\w.-]+)\\}\\}");-// A job's staging directory is <stagingDir>/job-runs/job-<id>, derived from the job id alone:// template and metalake names can change after the job runs, so a path built from them can't be// rebuilt at cleanup time. The name contains '-', which metalake names can't, so it never@@ -114,8 +107,6 @@ public class JobManager implements JobOperationDispatcher {private static final long JOB_STATUS_PULL_MIN_INTERVAL_IN_MS = 60 * 1000L; // 1 minute- private static final int TIMEOUT_IN_MS = 30 * 1000; // 30 seconds-private final EntityStore entityStore;private final File stagingDir;@@ -242,6 +233,8 @@ public class JobManager implements JobOperationDispatcher {public void registerJobTemplate(String metalake, JobTemplateEntity jobTemplateEntity)throws JobTemplateAlreadyExistsException {checkMetalake(NameIdentifierUtil.ofMetalake(metalake), entityStore);+ // Fail on malformed placeholders now rather than on every job run.+ JobTemplateResolver.validate(jobTemplateEntity);NameIdentifier jobTemplateIdent =NameIdentifierUtil.ofJobTemplate(metalake, jobTemplateEntity.name());@@ -508,6 +501,10 @@ public class JobManager implements JobOperationDispatcher {// Check if the job template exists, will throw NoSuchJobTemplateException if it does not exist.JobTemplateEntity jobTemplateEntity = getJobTemplate(metalake, jobTemplateName);+ // Reject a job with missing parameters before creating anything for it.+ JobTemplateResolver jobTemplateResolver = new JobTemplateResolver(jobTemplateEntity);+ jobTemplateResolver.checkJobConf(jobConf);+// Create staging directory.long jobId = idGenerator.nextId();File jobStagingDir = jobStagingDir(jobId);@@ -521,7 +518,13 @@ public class JobManager implements JobOperationDispatcher {// 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.- JobTemplate jobTemplate = createRuntimeJobTemplate(jobTemplateEntity, jobConf, jobStagingDir);+ JobTemplate jobTemplate;+ try {+ jobTemplate = jobTemplateResolver.resolve(jobConf, jobStagingDir);+ } catch (RuntimeException e) {+ deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);+ throw e;+ }// Serialize the resolved (placeholder-replaced) job template so callers can later see exactly// what was submitted for execution, not just the original template. This is done before@@ -533,6 +536,7 @@ public class JobManager implements JobOperationDispatcher {try {runtimeJobTemplateJson = JsonUtils.anyFieldMapper().writeValueAsString(runtimeJobTemplateDTO);} catch (JsonProcessingException e) {+ deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);throw new RuntimeException("Failed to serialize the runtime job template", e);}@@ -797,153 +801,6 @@ public class JobManager implements JobOperationDispatcher {}}- @VisibleForTesting- public static JobTemplate createRuntimeJobTemplate(- JobTemplateEntity jobTemplateEntity, Map<String, String> jobConf, File stagingDir) {- String name = jobTemplateEntity.name();- String comment = jobTemplateEntity.comment();-- JobTemplateEntity.TemplateContent content = jobTemplateEntity.templateContent();- String executable =- fetchFileFromUri(- replacePlaceholder(content.executable(), jobConf), stagingDir, TIMEOUT_IN_MS);-- List<String> args =- content.arguments().stream()- .map(arg -> replacePlaceholder(arg, jobConf))- .collect(Collectors.toList());- Map<String, String> environments =- content.environments().entrySet().stream()- .collect(- Collectors.toMap(- entry -> replacePlaceholder(entry.getKey(), jobConf),- entry -> replacePlaceholder(entry.getValue(), jobConf)));- Map<String, String> customFields =- content.customFields().entrySet().stream()- .collect(- Collectors.toMap(- entry -> replacePlaceholder(entry.getKey(), jobConf),- entry -> replacePlaceholder(entry.getValue(), jobConf)));-- // For shell job template- if (content.jobType() == JobTemplate.JobType.SHELL) {- List<String> scripts =- content.scripts().stream()- .map(- script ->- fetchFileFromUri(- replacePlaceholder(script, jobConf), stagingDir, TIMEOUT_IN_MS))- .collect(Collectors.toList());-- return ShellJobTemplate.builder()- .withName(name)- .withComment(comment)- .withExecutable(executable)- .withArguments(args)- .withEnvironments(environments)- .withCustomFields(customFields)- .withScripts(scripts)- .build();- }-- // For Spark job template- if (content.jobType() == JobTemplate.JobType.SPARK) {- String className = replacePlaceholder(content.className(), jobConf);- List<String> jars =- content.jars().stream()- .map(- jar ->- fetchFileFromUri(replacePlaceholder(jar, jobConf), stagingDir, TIMEOUT_IN_MS))- .collect(Collectors.toList());-- List<String> files =- content.files().stream()- .map(- file ->- fetchFileFromUri(- replacePlaceholder(file, jobConf), stagingDir, TIMEOUT_IN_MS))- .collect(Collectors.toList());-- List<String> archives =- content.archives().stream()- .map(- archive ->- fetchFileFromUri(- replacePlaceholder(archive, jobConf), stagingDir, TIMEOUT_IN_MS))- .collect(Collectors.toList());-- Map<String, String> configs =- content.configs().entrySet().stream()- .collect(- Collectors.toMap(- entry -> replacePlaceholder(entry.getKey(), jobConf),- entry -> replacePlaceholder(entry.getValue(), jobConf)));-- return SparkJobTemplate.builder()- .withName(name)- .withComment(comment)- .withExecutable(executable)- .withArguments(args)- .withEnvironments(environments)- .withCustomFields(customFields)- .withClassName(className)- .withJars(jars)- .withFiles(files)- .withArchives(archives)- .withConfigs(configs)- .build();- }-- throw new IllegalArgumentException("Unsupported job type: " + content.jobType());- }-- @VisibleForTesting- static String replacePlaceholder(String inputString, Map<String, String> replacements) {- if (StringUtils.isBlank(inputString)) {- return inputString; // Return as is if the input string is blank- }-- StringBuilder result = new StringBuilder();-- Matcher matcher = PLACEHOLDER_PATTERN.matcher(inputString);- while (matcher.find()) {- String key = matcher.group(1);- String replacement = replacements.get(key);- if (replacement != null) {- matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));- } else {- // If no replacement is found, keep the placeholder as is- matcher.appendReplacement(result, matcher.group(0));- }- }- matcher.appendTail(result);-- return result.toString();- }-- @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);- }- }-@VisibleForTestingJobTemplateEntity updateJobTemplateEntity(NameIdentifier jobTemplateIdent,@@ -1045,20 +902,24 @@ public class JobManager implements JobOperationDispatcher {}}- return newTemplateBuilder- .withId(jobTemplateEntity.id())- .withName(newName)- .withComment(newComment)- .withNamespace(jobTemplateIdent.namespace())- .withTemplateContent(newTemplateContentBuilder.build())- .withAuditInfo(- AuditInfo.builder()- .withCreator(jobTemplateEntity.auditInfo().creator())- .withCreateTime(jobTemplateEntity.auditInfo().createTime())- .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())- .withLastModifiedTime(Instant.now())- .build())- .build();+ JobTemplateEntity newJobTemplateEntity =+ newTemplateBuilder+ .withId(jobTemplateEntity.id())+ .withName(newName)+ .withComment(newComment)+ .withNamespace(jobTemplateIdent.namespace())+ .withTemplateContent(newTemplateContentBuilder.build())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(jobTemplateEntity.auditInfo().creator())+ .withCreateTime(jobTemplateEntity.auditInfo().createTime())+ .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build())+ .build();+ // Fail on malformed placeholders in the updated template.+ JobTemplateResolver.validate(newJobTemplateEntity);+ return newJobTemplateEntity;}@VisibleForTestingdiff --git a/core/src/main/java/org/apache/gravitino/job/JobTemplatePlaceholderUtils.java b/core/src/main/java/org/apache/gravitino/job/JobTemplatePlaceholderUtils.javanew file mode 100644index 0000000000..918e282560--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/job/JobTemplatePlaceholderUtils.java@@ -0,0 +1,366 @@+/*+ * 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.job;++import java.util.ArrayList;+import java.util.Collection;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.TreeSet;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import javax.annotation.Nullable;+import org.apache.gravitino.meta.JobTemplateEntity;++/**+ * Utility methods to parse and replace the placeholders of a job template.+ *+ * <p>The syntax is:+ *+ * <ul>+ * <li>{@code {{name}}}: a required parameter. Submitting a job without a value for it fails.+ * <li>{@code {{name:-default}}}: an optional parameter that falls back to {@code default}, which+ * may be empty ({@code {{name:-}}}). A default declared on one occurrence of a parameter+ * applies to all of its occurrences in the template, wherever it is declared, so a parameter+ * written as {@code {{name}}} in one place and {@code {{name:-default}}} in another is+ * optional everywhere. Declaring different defaults for the same parameter is rejected. The+ * default value is used as is and may span lines, but its braces must be balanced, so the+ * placeholder ends at the first <code>+ * }}</code> outside of them. A JSON object is a valid default value, for example {@code+ * {{options:-{"k":"v"}}}}.+ * <li><code>\{{</code>: a literal <code>{{</code>, for templates that must pass through text such+ * as another tool's {@code {{macro}}}. A value that ends with a backslash right before a+ * placeholder doubles it, as in <code>\\{{name}}</code>, which resolves the placeholder and+ * keeps one backslash. A backslash anywhere else is plain text.+ * </ul>+ *+ * <p>A parameter takes its value from the job configuration first, where an explicit empty string+ * counts as a value, and from its default otherwise. The job configuration value is used as is and+ * is never scanned for placeholders.+ */+final class JobTemplatePlaceholderUtils {++ // The start of a placeholder: "{{", its name in group 1, and ":-" in group 2 if it has a default+ // value. The default value and the closing "}}" are found by scanning.+ private static final Pattern PLACEHOLDER_START = Pattern.compile("\\{\\{([\\w.-]+)(:-)?");++ private static final String OPEN = "{{";++ private static final String CLOSE = "}}";++ private static final String ESCAPED_OPEN = "\\{{";++ private static final String ESCAPED_BACKSLASH_OPEN = "\\\\{{";++ /** Receives the literal text and the placeholders of a template value, in order. */+ private interface TokenVisitor {+ void literal(String text);++ void placeholder(String name, @Nullable String defaultValue);+ }++ private JobTemplatePlaceholderUtils() {}++ /**+ * Parses the parameters referenced by a job template, together with their default values.+ *+ * @param content the job template content+ * @return the parameters in order of first appearance, each mapped to its default value, or to an+ * empty optional if the parameter is required+ * @throws IllegalArgumentException if a placeholder is malformed, for example its default value+ * has unbalanced braces, or a parameter declares conflicting default values+ */+ static Map<String, Optional<String>> parseParameters(JobTemplateEntity.TemplateContent content) {+ Map<String, Optional<String>> parameters = new LinkedHashMap<>();+ for (String value : templateValues(content)) {+ collectParameters(value, parameters);+ }+ return parameters;+ }++ /**+ * Finds the required parameters that have no value in the job configuration.+ *+ * @param parameters the parameters of the job template, from {@link #parseParameters}+ * @param jobConf the job configuration+ * @return the missing parameters, sorted, or an empty set if none is missing+ */+ static Set<String> findMissingParameters(+ Map<String, Optional<String>> parameters, Map<String, String> jobConf) {+ Set<String> missing = new TreeSet<>();+ parameters.forEach(+ (name, defaultValue) -> {+ if (!defaultValue.isPresent() && jobConf.get(name) == null) {+ missing.add(name);+ }+ });+ return missing;+ }++ /**+ * Finds the job configuration keys that the job template does not reference.+ *+ * @param parameters the parameters of the job template, from {@link #parseParameters}+ * @param jobConf the job configuration+ * @return the unreferenced keys, sorted+ */+ static Set<String> findUnusedKeys(+ Map<String, Optional<String>> parameters, Map<String, String> jobConf) {+ Set<String> unused = new TreeSet<>(jobConf.keySet());+ unused.removeAll(parameters.keySet());+ return unused;+ }++ /**+ * Replaces the placeholders in a template value with their values from the job configuration, or+ * with their default values.+ *+ * @param value the template value, may be null+ * @param jobConf the job configuration+ * @param parameters the parameters of the whole job template, from {@link #parseParameters},+ * which supply the default values. A placeholder whose parameter isn't listed falls back to+ * the default value written on it+ * @return the resolved value, or null if {@code value} is null+ * @throws IllegalArgumentException if a placeholder is malformed, or has neither a value nor a+ * default value+ */+ @Nullable+ static String replacePlaceholders(+ @Nullable String value,+ Map<String, String> jobConf,+ Map<String, Optional<String>> parameters) {+ if (value == null) {+ return null;+ }++ StringBuilder result = new StringBuilder();+ scan(+ value,+ new TokenVisitor() {+ @Override+ public void literal(String text) {+ result.append(text);+ }++ @Override+ public void placeholder(String name, @Nullable String defaultValue) {+ String replacement = jobConf.get(name);+ if (replacement == null) {+ replacement =+ parameters+ .getOrDefault(name, Optional.ofNullable(defaultValue))+ .orElseThrow(+ () ->+ new IllegalArgumentException(+ String.format(+ "No value is provided for the job template parameter %s",+ name)));+ }+ result.append(replacement);+ }+ });+ return result.toString();+ }++ private static void collectParameters(+ @Nullable String value, Map<String, Optional<String>> parameters) {+ if (value == null) {+ return;+ }++ scan(+ value,+ new TokenVisitor() {+ @Override+ public void literal(String text) {}++ @Override+ public void placeholder(String name, @Nullable String defaultValue) {+ Optional<String> existing = parameters.get(name);+ if (existing == null || !existing.isPresent()) {+ parameters.put(name, Optional.ofNullable(defaultValue));+ } else if (defaultValue != null && !existing.get().equals(defaultValue)) {+ throw new IllegalArgumentException(+ String.format(+ "Job template parameter %s has conflicting default values '%s' and '%s'",+ name, existing.get(), defaultValue));+ }+ }+ });+ }++ /**+ * Splits a template value into literal text and placeholders, and passes them in order to the+ * visitor.+ *+ * <p>Text that only looks like a placeholder, for example {@code {{ name }}} or <code>{{name}+ * </code>, is literal text. A placeholder with a default value, however, must be well formed: its+ * default value must have balanced braces and the placeholder must end with <code>}}</code>.+ */+ private static void scan(String value, TokenVisitor visitor) {+ StringBuilder literal = new StringBuilder();+ Matcher start = PLACEHOLDER_START.matcher(value);+ int index = 0;+ while (index < value.length()) {+ // "\\{{" keeps one backslash and lets the placeholder resolve, so a value that ends with a+ // backslash can still be followed by a placeholder. It is checked first, because its tail is+ // itself an escape.+ if (value.startsWith(ESCAPED_BACKSLASH_OPEN, index)) {+ literal.append('\\');+ // Consume both backslashes, so the "{{" that follows is read as a placeholder.+ index += 2;+ continue;+ }++ if (value.startsWith(ESCAPED_OPEN, index)) {+ literal.append(OPEN);+ index += ESCAPED_OPEN.length();+ continue;+ }++ if (value.startsWith(OPEN, index) && start.region(index, value.length()).lookingAt()) {+ String name = start.group(1);+ boolean hasDefaultValue = start.group(2) != null;+ if (hasDefaultValue || value.startsWith(CLOSE, start.end())) {+ String defaultValue = null;+ int closeIndex = start.end();+ if (hasDefaultValue) {+ closeIndex = findDefaultValueEnd(value, start.end(), name);+ defaultValue = value.substring(start.end(), closeIndex);+ }+ flushLiteral(literal, visitor);+ visitor.placeholder(name, defaultValue);+ index = closeIndex + CLOSE.length();+ continue;+ }+ }++ literal.append(value.charAt(index));+ index++;+ }+ flushLiteral(literal, visitor);+ }++ /**+ * Returns the index of the "}}" that closes a placeholder whose default value starts at {@code+ * from}, which is the first "}}" outside of the braces of the default value.+ */+ private static int findDefaultValueEnd(String value, int from, String name) {+ int depth = 0;+ boolean hasBrace = false;+ boolean hasUnmatchedClose = false;+ for (int index = from; index < value.length(); index++) {+ char c = value.charAt(index);+ if (c == '{') {+ depth++;+ hasBrace = true;+ } else if (c == '}') {+ if (depth > 0) {+ // A "}" that closes a brace of the default value, not the placeholder.+ depth--;+ } else if (value.startsWith(CLOSE, index)) {+ // A default value that has braces and is followed by one more "}" was meant to take that+ // "}" too, which happens when a brace sits inside a quoted string, for example+ // {{o:-{"k":"}"}}}. Reject it rather than silently cutting the default value. A default+ // value without braces cannot be extended that way, so the "}" is literal text after the+ // placeholder, as in {"k":{{v:-1}}}.+ int next = index + CLOSE.length();+ if (hasBrace && next < value.length() && value.charAt(next) == '}') {+ throw new IllegalArgumentException(+ String.format(+ "The placeholder of job template parameter %s is followed by '}', so it is "+ + "unclear whether that '}' closes the placeholder or belongs to its "+ + "default value. Insert a space before it, or move it into the default "+ + "value: %s",+ name, value));+ }+ return index;+ } else if (index < value.length() - 1) {+ throw new IllegalArgumentException(+ String.format(+ "The default value of job template parameter %s has an unmatched '}': %s",+ name, value));+ } else {+ hasUnmatchedClose = true;+ }+ }+ }++ String reason;+ if (depth > 0) {+ reason = "The default value of job template parameter %s has an unmatched '{': %s";+ } else if (hasUnmatchedClose) {+ reason = "The default value of job template parameter %s has an unmatched '}': %s";+ } else {+ reason = "The placeholder of job template parameter %s is not closed with '}}': %s";+ }+ throw new IllegalArgumentException(String.format(reason, name, value));+ }++ private static void flushLiteral(StringBuilder literal, TokenVisitor visitor) {+ if (literal.length() > 0) {+ visitor.literal(literal.toString());+ literal.setLength(0);+ }+ }++ /**+ * Returns the values of a job template that are resolved when a job runs. Only the fields of the+ * template's own job type are included, so a leftover value of another job type never turns into+ * a parameter the job configuration has to provide.+ */+ private static List<String> templateValues(JobTemplateEntity.TemplateContent content) {+ List<String> values = new ArrayList<>();+ values.add(content.executable());+ addAll(values, content.arguments());+ addEntries(values, content.environments());+ addEntries(values, content.customFields());++ if (content.jobType() == JobTemplate.JobType.SHELL) {+ addAll(values, content.scripts());+ } else if (content.jobType() == JobTemplate.JobType.SPARK) {+ values.add(content.className());+ addAll(values, content.jars());+ addAll(values, content.files());+ addAll(values, content.archives());+ addEntries(values, content.configs());+ }+ return values;+ }++ private static void addAll(List<String> values, @Nullable Collection<String> source) {+ if (source != null) {+ values.addAll(source);+ }+ }++ private static void addEntries(List<String> values, @Nullable Map<String, String> source) {+ if (source != null) {+ source.forEach(+ (key, value) -> {+ values.add(key);+ values.add(value);+ });+ }+ }+}diff --git a/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java b/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.javanew file mode 100644index 0000000000..158af7b9fa--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java@@ -0,0 +1,247 @@+/*+ * 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.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;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.function.Function;+import java.util.stream.Collectors;+import javax.annotation.Nullable;+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.+ *+ * <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+ * template, use {@link #validate}.+ */+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+ // the parameter is required.+ private final Map<String, Optional<String>> parameters;++ /**+ * Creates a resolver for a job template.+ *+ * @param jobTemplateEntity the job template+ * @throws IllegalArgumentException if the template's placeholders are malformed, for example a+ * parameter has conflicting default values+ */+ public JobTemplateResolver(JobTemplateEntity jobTemplateEntity) {+ this.jobTemplateEntity = jobTemplateEntity;+ this.parameters =+ JobTemplatePlaceholderUtils.parseParameters(jobTemplateEntity.templateContent());+ }++ /**+ * Validates the placeholders of a job template, for example when the template is registered or+ * updated, so a malformed template is rejected before any job runs from it.+ *+ * @param jobTemplateEntity the job template+ * @throws IllegalArgumentException if the template's placeholders are malformed, for example a+ * parameter has conflicting default values+ */+ public static void validate(JobTemplateEntity jobTemplateEntity) {+ JobTemplatePlaceholderUtils.parseParameters(jobTemplateEntity.templateContent());+ }++ /**+ * Returns the parameters of the template that a job configuration has to provide, which are the+ * ones whose placeholders declare no default value.+ *+ * @return the required parameters, sorted+ */+ public Set<String> requiredParameters() {+ return JobTemplatePlaceholderUtils.findMissingParameters(parameters, Collections.emptyMap());+ }++ /**+ * Checks that a job configuration provides every required parameter of the template, and logs a+ * warning for the keys that the template does not use. It fetches nothing, so it can run before+ * any resource is created for the job.+ *+ * @param jobConf the job configuration, may be null+ * @throws IllegalArgumentException listing all the required parameters that have no value+ */+ public void checkJobConf(@Nullable Map<String, String> jobConf) {+ Map<String, String> conf = jobConf == null ? Collections.emptyMap() : jobConf;+ checkRequiredParameters(conf);++ Set<String> unusedKeys = JobTemplatePlaceholderUtils.findUnusedKeys(parameters, conf);+ if (!unusedKeys.isEmpty()) {+ LOG.warn(+ "Job configuration keys {} are not used by job template {}",+ unusedKeys,+ jobTemplateEntity.name());+ }+ }++ /**+ * Resolves the template into the runtime job template of a job run.+ *+ * @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) {+ 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.+ 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());+ 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))+ .withArguments(args)+ .withEnvironments(environments)+ .withCustomFields(customFields)+ .withScripts(fetchFilesFromUri(scriptUris, stagingDir, FETCH_TIMEOUT_IN_MS))+ .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))+ .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)+ .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()) {+ throw new IllegalArgumentException(+ String.format(+ "No value is provided for the parameter(s) %s of job template %s. Set them in the "+ + "job configuration, or give them a default value in the template, for example "+ + "{{name:-default}}",+ missing, jobTemplateEntity.name()));+ }+ }++ private static List<String> resolveList(+ @Nullable List<String> source, Function<String, String> resolver) {+ if (source == null) {+ return Collections.emptyList();+ }+ return source.stream().map(resolver).collect(Collectors.toList());+ }++ private static Map<String, String> resolveMap(+ @Nullable Map<String, String> source, Function<String, String> resolver, String field) {+ Map<String, String> resolved = new LinkedHashMap<>();+ if (source == null) {+ return resolved;+ }+ source.forEach(+ (key, value) -> {+ String resolvedKey = resolver.apply(key);+ String resolvedValue = resolver.apply(value);+ String previous = resolved.putIfAbsent(resolvedKey, resolvedValue);+ if (previous != null) {+ throw new IllegalArgumentException(+ String.format(+ "Job template %s key %s is duplicated after resolving placeholders",+ field, resolvedKey));+ }+ });+ return resolved;+ }+}diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobManager.java b/core/src/test/java/org/apache/gravitino/job/TestJobManager.javaindex a1b0f9f485..33ae423217 100644--- a/core/src/test/java/org/apache/gravitino/job/TestJobManager.java+++ b/core/src/test/java/org/apache/gravitino/job/TestJobManager.java@@ -35,14 +35,9 @@ import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import com.google.common.collect.ImmutableSet;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.Duration;import java.time.Instant;import java.time.temporal.ChronoUnit;@@ -94,7 +89,6 @@ import org.apache.gravitino.meta.SchemaVersion;import org.apache.gravitino.metalake.MetalakeManager;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.RandomIdGenerator;-import org.apache.gravitino.utils.FileFetcher;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;import org.awaitility.Awaitility;@@ -899,7 +893,7 @@ public class TestJobManager {Assertions.assertEquals(Lists.newArrayList("Hello!"), runtimeJobTemplateDTO.arguments());Assertions.assertEquals(jobTemplateEntity.name(), runtimeJobTemplateDTO.name());Assertions.assertEquals(jobTemplateEntity.comment(), runtimeJobTemplateDTO.comment());- // createRuntimeJobTemplate() also resolves the executable by fetching it into the job's+ // 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(@@ -907,6 +901,112 @@ public class TestJobManager {() -> "Unexpected resolved executable: " + runtimeJobTemplateDTO.executable());}+ @Test+ public void testRunJobResolvesDefaultValues() throws IOException {+ mockedMetalake+ .when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))+ .thenAnswer(a -> null);++ JobTemplateEntity jobTemplateEntity =+ newShellJobTemplateEntity(+ "shell_job_with_defaults",+ Lists.newArrayList(+ "--greeting", "{{greeting:-Hi}}", "--note", "{{note:-}}", "{{name}}"));+ when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))+ .thenReturn(jobTemplateEntity);+ when(jobExecutor.submitJob(any())).thenReturn("job_execution_id_for_test");+ doNothing().when(entityStore).put(any(JobEntity.class), anyBoolean());++ JobEntity jobEntity =+ jobManager.runJob(+ metalake, jobTemplateEntity.name(), ImmutableMap.of("name", "Bob", "unused", "x"));++ ShellJobTemplateDTO runtimeJobTemplateDTO =+ (ShellJobTemplateDTO)+ JsonUtils.anyFieldMapper()+ .readValue(jobEntity.runtimeJobTemplate(), JobTemplateDTO.class);+ Assertions.assertEquals(+ Lists.newArrayList("--greeting", "Hi", "--note", "", "Bob"),+ runtimeJobTemplateDTO.arguments());+ }++ @Test+ public void testRunJobRejectsMissingParametersBeforeStaging() throws IOException {+ mockedMetalake+ .when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))+ .thenAnswer(a -> null);++ JobTemplateEntity jobTemplateEntity =+ newShellJobTemplateEntity(+ "shell_job_with_required", Lists.newArrayList("{{b}}", "{{a}}", "{{c:-x}}"));+ when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))+ .thenReturn(jobTemplateEntity);++ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> jobManager.runJob(metalake, jobTemplateEntity.name(), Collections.emptyMap()));+ Assertions.assertTrue(e.getMessage().contains("[a, b]"), e.getMessage());++ verify(jobExecutor, never()).submitJob(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());+ }++ @Test+ public void testRunJobRemovesStagingDirWhenTemplateResolutionFails() throws IOException {+ mockedMetalake+ .when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))+ .thenAnswer(a -> null);++ ShellJobTemplate shellJobTemplate =+ ShellJobTemplate.builder()+ .withName("shell_job_with_missing_executable")+ .withExecutable("/non_existent_dir_" + UUID.randomUUID() + "/run.sh")+ .build();+ JobTemplateEntity jobTemplateEntity = toJobTemplateEntity(shellJobTemplate);+ when(jobManager.getJobTemplate(metalake, jobTemplateEntity.name()))+ .thenReturn(jobTemplateEntity);++ 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.+ 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+ public void testRegisterAndAlterJobTemplateRejectConflictingDefaults() throws IOException {+ mockedMetalake+ .when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))+ .thenAnswer(a -> null);++ JobTemplateEntity conflicting =+ newShellJobTemplateEntity(+ "shell_job_conflicting", Lists.newArrayList("{{mode:-all}}", "{{mode:-stats}}"));+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> jobManager.registerJobTemplate(metalake, conflicting));+ Assertions.assertTrue(e.getMessage().contains("mode"), e.getMessage());+ verify(entityStore, never()).put(any(JobTemplateEntity.class), anyBoolean());++ JobTemplateEntity valid = newShellJobTemplateEntity("shell_job", "A shell job template");+ JobTemplateChange invalidUpdate =+ JobTemplateChange.updateTemplate(+ JobTemplateChange.ShellTemplateUpdate.builder()+ .withNewArguments(ImmutableList.of("--options", "{{options:-{}}"))+ .build());+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> jobManager.updateJobTemplateEntity(valid.nameIdentifier(), valid, invalidUpdate));+ }+@Testpublic void testRunJobSucceedsWhenStagingDirectoryAlreadyExists() throws Exception {mockedMetalake@@ -1626,10 +1726,8 @@ public class TestJobManager {try {JobTemplate jobTemplate =- JobManager.createRuntimeJobTemplate(- newShellJobTemplateEntity("shell_job", "echo"),- Collections.emptyMap(),- jobStagingDir);+ new JobTemplateResolver(newShellJobTemplateEntity("shell_job", "echo"))+ .resolve(Collections.emptyMap(), jobStagingDir);String executionId = ownerExecutor.submitJob(jobTemplate);Awaitility.await().atMost(1, TimeUnit.MINUTES)@@ -2326,6 +2424,26 @@ public class TestJobManager {.build();}+ private JobTemplateEntity newShellJobTemplateEntity(String name, List<String> arguments) {+ return toJobTemplateEntity(+ ShellJobTemplate.builder()+ .withName(name)+ .withExecutable("/bin/echo")+ .withArguments(arguments)+ .build());+ }++ private JobTemplateEntity toJobTemplateEntity(JobTemplate jobTemplate) {+ return JobTemplateEntity.builder()+ .withId(new Random().nextLong())+ .withName(jobTemplate.name())+ .withNamespace(NamespaceUtil.ofJobTemplate(metalake))+ .withTemplateContent(JobTemplateEntity.TemplateContent.fromJobTemplate(jobTemplate))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ }+private JobTemplateEntity newSparkJobTemplateEntity(String name, String comment) {SparkJobTemplate sparkJobTemplate =SparkJobTemplate.builder()@@ -2775,98 +2893,6 @@ public class TestJobManager {return captor.getValue().apply(latestJobEntity);}- private 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 = new File(testStagingDir);- Assertions.assertTrue(stagingDir.mkdirs() || stagingDir.exists());-- Path missingFilePath =- Path.of(System.getProperty("java.io.tmpdir"), "missing-job-file-" + UUID.randomUUID());- String uri = missingFilePath.toUri().toString();-- Assertions.assertThrows(- RuntimeException.class, () -> JobManager.fetchFileFromUri(uri, stagingDir, 1000));- }-- @Test- public void testFetchFileFromUriSsrfBlocked() {- File stagingDir = new File(testStagingDir);- Assertions.assertTrue(stagingDir.mkdirs() || stagingDir.exists());- FileFetcher.get().initialize(true);-- // Loopback address- RuntimeException e1 =- Assertions.assertThrows(- RuntimeException.class,- () -> JobManager.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,- () ->- JobManager.fetchFileFromUri(- "http://169.254.169.254/latest/meta-data/", stagingDir, 1000));- assertRemoteUriBlockedMessage(e2);-- // RFC-1918 private range- RuntimeException e3 =- Assertions.assertThrows(- RuntimeException.class,- () -> JobManager.fetchFileFromUri("http://192.168.1.1/", stagingDir, 1000));- assertRemoteUriBlockedMessage(e3);-- // Alibaba Cloud / Oracle Cloud metadata endpoint- RuntimeException e4 =- Assertions.assertThrows(- RuntimeException.class,- () -> JobManager.fetchFileFromUri("http://100.100.100.200/", stagingDir, 1000));- assertRemoteUriBlockedMessage(e4);- }-- @Test- public void testFetchFileFromUriShouldAllowLocalhostWhenBlockingDisabled() throws Exception {- File stagingDir = new File(testStagingDir);- Assertions.assertTrue(stagingDir.mkdirs() || stagingDir.exists());- HttpServer server = createLoopbackHttpServer("job artifact");-- try {- server.start();- int port = server.getAddress().getPort();- FileFetcher.get().initialize(false);-- String fetchedFile =- JobManager.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));- }-@Testpublic void testCloseShouldShutdownExecutorsWhenJobExecutorCloseFails() throws IOException {JobExecutor failingJobExecutor = Mockito.mock(JobExecutor.class);diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobTemplatePlaceholderUtils.java b/core/src/test/java/org/apache/gravitino/job/TestJobTemplatePlaceholderUtils.javanew file mode 100644index 0000000000..d587b2a79d--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/job/TestJobTemplatePlaceholderUtils.java@@ -0,0 +1,433 @@+/*+ * 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.job;++import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Lists;+import java.util.Collections;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import org.apache.gravitino.meta.JobTemplateEntity;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestJobTemplatePlaceholderUtils {++ @Test+ public void testResolveWithValues() {+ String template = "Hello, {{name}}! Welcome to {{place}}.";+ Map<String, String> conf = ImmutableMap.of("name", "Alice", "place", "Wonderland");+ Assertions.assertEquals("Hello, Alice! Welcome to Wonderland.", replace(template, conf));++ Assertions.assertEquals("Hello, World!", replace("Hello, World!", conf));+ Assertions.assertEquals("", replace("", conf));+ Assertions.assertNull(replace(null, conf));++ Assertions.assertEquals("Alice is Alice", replace("{{name}} is {{name}}", conf));++ // Names may contain letters, digits, '_', '.' and '-'.+ Assertions.assertEquals(+ "a-b-c",+ replace(+ "{{user_name}}-{{user.name}}-{{score-1}}",+ ImmutableMap.of("user_name", "a", "user.name", "b", "score-1", "c")));+ }++ @Test+ public void testResolveKeepsTextThatIsNotAPlaceholder() {+ Map<String, String> conf = ImmutableMap.of("name", "Dave", "value", "42");+ Assertions.assertEquals("{{name}! 42", replace("{{name}! {{value}}", conf));+ Assertions.assertEquals("{{score%}}", replace("{{score%}}", conf));+ Assertions.assertEquals("{{ name }}", replace("{{ name }}", conf));+ Assertions.assertEquals("{42}", replace("{{{value}}}", conf));+ Assertions.assertEquals("{{42}}", replace("{{{{value}}}}", conf));+ }++ @Test+ public void testResolveMissingValueFails() {+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> replace("Hello, {{name}}!", Collections.emptyMap()));+ Assertions.assertTrue(e.getMessage().contains("name"), e.getMessage());++ // A null value in the job configuration counts as no value.+ Map<String, String> conf = new HashMap<>();+ conf.put("name", null);+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> replace("Hello, {{name}}!", conf));+ }++ @Test+ public void testResolveDefaultValues() {+ String template = "--strategy {{strategy:-binpack}} --where {{where:-}}";+ Assertions.assertEquals(+ "--strategy binpack --where ", replace(template, Collections.emptyMap()));++ // A provided value, including an explicit empty string, wins over the default value.+ Assertions.assertEquals(+ "--strategy sort --where a > 1",+ replace(template, ImmutableMap.of("strategy", "sort", "where", "a > 1")));+ Assertions.assertEquals(+ "--strategy --where ", replace(template, ImmutableMap.of("strategy", "")));++ // A default value may contain ':', '-', spaces, '$' and backslashes, all used as is.+ Assertions.assertEquals(+ "local[*] a:-b x y $1 C:\\tmp",+ replace(+ "{{master:-local[*]}} {{a:-a:-b}} {{b:-x y}} {{c:-$1}} {{d:-C:\\tmp}}",+ Collections.emptyMap()));+ }++ @Test+ public void testResolveEscapedPlaceholder() {+ Map<String, String> conf = ImmutableMap.of("ds", "2026-09-22");+ Assertions.assertEquals("echo {{ds}} 2026-09-22", replace("echo \\{{ds}} {{ds}}", conf));+ Assertions.assertEquals("{{missing}}", replace("\\{{missing}}", Collections.emptyMap()));+ }++ @Test+ public void testResolveValueIsNotScanned() {+ // Values are used as is: placeholders, escapes and replacement syntax in them stay literal.+ Map<String, String> conf =+ ImmutableMap.of("conf", "path=C:\\tmp and cost=$5 {{other}} \\{{x}}", "other", "x");+ Assertions.assertEquals(+ "config=path=C:\\tmp and cost=$5 {{other}} \\{{x}}", replace("config={{conf}}", conf));++ Assertions.assertEquals(+ "config=p$1x", replace("config={{conf}}", ImmutableMap.of("conf", "p$1x")));+ }++ @Test+ public void testParametersCollectsAllFields() {+ JobTemplateEntity.TemplateContent content =+ JobTemplateEntity.TemplateContent.builder()+ .withJobType(JobTemplate.JobType.SPARK)+ .withExecutable("{{exec}}")+ .withArguments(Lists.newArrayList("--a", "{{arg:-1}}", "\\{{escaped}}"))+ .withEnvironments(ImmutableMap.of("{{env_key}}", "{{env_value:-}}"))+ .withCustomFields(ImmutableMap.of("field", "{{custom}}"))+ .withClassName("{{class_name:-Main}}")+ .withJars(Lists.newArrayList("{{jar}}"))+ .withFiles(Lists.newArrayList("{{file:-}}"))+ .withArchives(Lists.newArrayList("{{archive:-}}"))+ .withConfigs(ImmutableMap.of("spark.master", "{{spark_master:-local[*]}}"))+ .build();++ Map<String, Optional<String>> parameters = JobTemplatePlaceholderUtils.parseParameters(content);+ Map<String, Optional<String>> expected = new LinkedHashMap<>();+ expected.put("exec", Optional.empty());+ expected.put("arg", Optional.of("1"));+ expected.put("env_key", Optional.empty());+ expected.put("env_value", Optional.of(""));+ expected.put("custom", Optional.empty());+ expected.put("class_name", Optional.of("Main"));+ expected.put("jar", Optional.empty());+ expected.put("file", Optional.of(""));+ expected.put("archive", Optional.of(""));+ expected.put("spark_master", Optional.of("local[*]"));+ Assertions.assertEquals(expected, parameters);+ }++ @Test+ public void testDefaultValueAppliesToAllOccurrences() {+ JobTemplateEntity.TemplateContent content =+ shellContent(+ Lists.newArrayList("--catalog", "{{catalog}}", "--table", "{{catalog:-ice}}.{{t}}"));+ Map<String, Optional<String>> parameters = JobTemplatePlaceholderUtils.parseParameters(content);+ Assertions.assertEquals(Optional.of("ice"), parameters.get("catalog"));++ Map<String, String> conf = ImmutableMap.of("t", "db.t");+ Assertions.assertEquals(+ "ice", JobTemplatePlaceholderUtils.replacePlaceholders("{{catalog}}", conf, parameters));+ }++ @Test+ public void testConflictingDefaultValuesFail() {+ JobTemplateEntity.TemplateContent content =+ shellContent(Lists.newArrayList("{{mode:-all}}", "{{mode:-stats}}"));+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> JobTemplatePlaceholderUtils.parseParameters(content));+ Assertions.assertTrue(e.getMessage().contains("mode"), e.getMessage());++ // Repeating the same default value is allowed.+ Assertions.assertEquals(+ Optional.of("all"),+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("{{mode:-all}}", "{{mode:-all}}")))+ .get("mode"));+ }++ @Test+ public void testJsonDefaultValues() {+ Map<String, String> noConf = Collections.emptyMap();+ Assertions.assertEquals("--options {}", replace("--options {{options:-{}}}", noConf));+ Assertions.assertEquals("{\"k\":\"v\"}", replace("{{o:-{\"k\":\"v\"}}}", noConf));+ Assertions.assertEquals(+ "{\"a\":{\"b\":{\"c\":1}}}", replace("{{o:-{\"a\":{\"b\":{\"c\":1}}}}}", noConf));+ Assertions.assertEquals("[]", replace("{{o:-[]}}", noConf));+ Assertions.assertEquals(+ "[{\"a\":1},{\"b\":{\"c\":2}}]", replace("{{o:-[{\"a\":1},{\"b\":{\"c\":2}}]}}", noConf));+ // A quoted "}}" is fine as long as all the braces are balanced.+ Assertions.assertEquals("{\"a\":\"{{}}\"}", replace("{{o:-{\"a\":\"{{}}\"}}}", noConf));++ // A provided value replaces the whole JSON default value.+ Assertions.assertEquals(+ "--options {\"x\":1}",+ replace("--options {{options:-{\"k\":\"v\"}}}", ImmutableMap.of("options", "{\"x\":1}")));+ }++ @Test+ public void testDefaultValueSpanningLines() {+ Assertions.assertEquals(+ "{\n \"k\": \"v\"\n}", replace("{{o:-{\n \"k\": \"v\"\n}}}", Collections.emptyMap()));+ Assertions.assertEquals("a\nb", replace("{{o:-a\nb}}", Collections.emptyMap()));+ }++ @Test+ public void testMultiplePlaceholdersWithBracedDefaultValues() {+ Assertions.assertEquals(+ "--a {\"x\":1} --b v --c {}",+ replace("--a {{a:-{\"x\":1}}} --b {{b}} --c {{c:-{}}}", ImmutableMap.of("b", "v")));+ Assertions.assertEquals("{}{}", replace("{{a:-{}}}{{b:-{}}}", Collections.emptyMap()));+ }++ @Test+ public void testJsonDefaultValueIsParsedAsOneParameter() {+ JobTemplateEntity.TemplateContent content =+ shellContent(Lists.newArrayList("--options", "{{options:-{\"k\":{\"v\":1}}}}", "{{name}}"));+ Map<String, Optional<String>> parameters = JobTemplatePlaceholderUtils.parseParameters(content);+ Map<String, Optional<String>> expected = new LinkedHashMap<>();+ expected.put("options", Optional.of("{\"k\":{\"v\":1}}"));+ expected.put("name", Optional.empty());+ Assertions.assertEquals(expected, parameters);+ }++ @Test+ public void testDefaultValueWithoutBracesFollowedByBrace() {+ Map<String, String> noConf = Collections.emptyMap();+ // The "}" after the placeholder belongs to the surrounding text, and a default value without+ // braces could not have taken it, so this is not ambiguous.+ Assertions.assertEquals("{\"k\":1}", replace("{\"k\":{{v:-1}}}", noConf));+ Assertions.assertEquals("1}", replace("{{v:-1}}}", noConf));+ Assertions.assertEquals("1}", replace("{{v:-1}}}", ImmutableMap.of()));+ Assertions.assertEquals("2}", replace("{{v:-1}}}", ImmutableMap.of("v", "2")));+ // Without a default value the same text has always been accepted, and still is.+ Assertions.assertEquals("2}", replace("{{v}}}", ImmutableMap.of("v", "2")));++ // A default value that has braces is still rejected, because it could have taken the "}".+ assertMalformed("{\"k\":{{v:-{}}}}", "v");+ }++ @Test+ public void testTemplatesRelyingOnUnresolvedPlaceholdersNowFail() {+ // Before default values were supported, a placeholder with no value was passed through as+ // literal text. It is now a required parameter, so such a template has to escape it.+ Map<String, Optional<String>> parameters =+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("--image", "{{.Values.image}}")));+ Assertions.assertEquals(+ Lists.newArrayList(".Values.image"), Lists.newArrayList(parameters.keySet()));+ assertMalformed("{{.Values.image}}", ".Values.image");++ Assertions.assertTrue(+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("--image", "\\{{.Values.image}}")))+ .isEmpty());+ Assertions.assertEquals(+ "{{.Values.image}}", replace("\\{{.Values.image}}", Collections.emptyMap()));+ }++ @Test+ public void testMalformedDefaultValuesFail() {+ // Unbalanced braces in the default value.+ assertMalformed("{{c:-{}}", "c");+ assertMalformed("{{c:-{{}}", "c");+ assertMalformed("{{c:-a}b}}", "c");+ assertMalformed("{{c:-{\"k\":1}", "c");+ // A brace inside a quoted string unbalances the braces, so the default value is ambiguous.+ assertMalformed("{{c:-{\"k\":\"}\"}}}", "c");+ // The placeholder is never closed.+ assertMalformed("{{c:-abc", "c");+ assertMalformed("prefix {{c:-abc} suffix", "c");++ // Malformed placeholders are rejected when parsing, so when registering a template.+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("--options", "{{options:-{}}"))));+ }++ @Test+ public void testPlaceholdersWithoutDefaultValueKeepLooseText() {+ // Without ":-", text that doesn't form a placeholder stays literal instead of failing.+ Map<String, String> conf = ImmutableMap.of("a", "1");+ Assertions.assertEquals("{{a", replace("{{a", conf));+ Assertions.assertEquals("{{a}", replace("{{a}", conf));+ Assertions.assertEquals("1}", replace("{{a}}}", conf));+ Assertions.assertEquals("{{}}", replace("{{}}", conf));+ Assertions.assertEquals("{{a b}}", replace("{{a b}}", conf));+ Assertions.assertEquals("}} 1 }}", replace("}} {{a}} }}", conf));+ }++ @Test+ public void testDoubledBackslashKeepsOneAndResolvesThePlaceholder() {+ Map<String, String> conf = ImmutableMap.of("dir", "tmp", "a", "1");+ Assertions.assertEquals("C:\\tmp", replace("C:\\\\{{dir}}", conf));+ Assertions.assertEquals("\\1", replace("\\\\{{a}}", conf));+ // A backslash that is not right before a placeholder is plain text.+ Assertions.assertEquals("a\\\\b", replace("a\\\\b", conf));+ Assertions.assertEquals("C:\\tmp\\", replace("C:\\tmp\\", conf));+ // Backslashes are read left to right, and only a "\\" right before "{{" is special, so three+ // of them keep the first as plain text and the second as the escaped one.+ Assertions.assertEquals("\\\\1", replace("\\\\\\{{a}}", conf));+ // A doubled backslash is not an escape, so the parameter is still required.+ assertMalformed("\\\\{{missing}}", "missing");+ }++ @Test+ public void testParametersOfTheOtherJobTypeAreIgnored() {+ // A SHELL template keeps only its own fields; a leftover Spark field must not become a+ // parameter the job configuration has to provide.+ JobTemplateEntity.TemplateContent shell =+ JobTemplateEntity.TemplateContent.builder()+ .withJobType(JobTemplate.JobType.SHELL)+ .withExecutable("/bin/echo")+ .withArguments(Lists.newArrayList("{{arg}}"))+ .withEnvironments(Collections.emptyMap())+ .withCustomFields(Collections.emptyMap())+ .withScripts(Lists.newArrayList("{{script}}"))+ .withClassName("{{main_class}}")+ .withJars(Lists.newArrayList("{{jar}}"))+ .withConfigs(ImmutableMap.of("k", "{{conf}}"))+ .build();+ Assertions.assertEquals(+ Lists.newArrayList("arg", "script"),+ Lists.newArrayList(JobTemplatePlaceholderUtils.parseParameters(shell).keySet()));++ JobTemplateEntity.TemplateContent spark =+ JobTemplateEntity.TemplateContent.builder()+ .withJobType(JobTemplate.JobType.SPARK)+ .withExecutable("{{exec}}")+ .withArguments(Collections.emptyList())+ .withEnvironments(Collections.emptyMap())+ .withCustomFields(Collections.emptyMap())+ .withScripts(Lists.newArrayList("{{script}}"))+ .withClassName("{{main_class}}")+ .withJars(Collections.emptyList())+ .withFiles(Collections.emptyList())+ .withArchives(Collections.emptyList())+ .withConfigs(Collections.emptyMap())+ .build();+ Assertions.assertEquals(+ Lists.newArrayList("exec", "main_class"),+ Lists.newArrayList(JobTemplatePlaceholderUtils.parseParameters(spark).keySet()));+ }++ @Test+ public void testMalformedDefaultValueMessages() {+ // The message names the actual problem, so the template author knows what to change.+ assertMessage("{{c:-{}}", "unmatched '}'");+ assertMessage("{{c:-{", "unmatched '{'");+ // A balanced but unterminated default value reports the missing "}}" instead.+ assertMessage("{{c:-{{}}", "not closed with '}}'");+ assertMessage("{{c:-abc", "not closed with '}}'");+ assertMessage("{\"k\":{{c:-{\"a\":1}}}}", "followed by '}'");+ }++ @Test+ public void testEscapesAreNotPlaceholders() {+ Map<String, String> conf = ImmutableMap.of("a", "1");+ Assertions.assertEquals("{{a:-{}}}", replace("\\{{a:-{}}}", conf));+ Assertions.assertEquals("{{a}} 1", replace("\\{{a}} {{a}}", conf));+ Assertions.assertTrue(+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("\\{{ds}}", "\\{{a:-{}}")))+ .isEmpty());+ }++ @Test+ public void testFindMissingParameters() {+ Map<String, Optional<String>> parameters =+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("{{b}}", "{{a}}", "{{c:-x}}", "{{d}}")));++ // A null value counts as no value, an empty string counts as a value.+ Map<String, String> conf = new HashMap<>();+ conf.put("d", "");+ conf.put("a", null);+ Assertions.assertEquals(+ Lists.newArrayList("a", "b"),+ Lists.newArrayList(JobTemplatePlaceholderUtils.findMissingParameters(parameters, conf)));++ Assertions.assertTrue(+ JobTemplatePlaceholderUtils.findMissingParameters(+ parameters, ImmutableMap.of("a", "1", "b", "2", "d", ""))+ .isEmpty());+ }++ @Test+ public void testFindUnusedKeys() {+ Map<String, Optional<String>> parameters =+ JobTemplatePlaceholderUtils.parseParameters(+ shellContent(Lists.newArrayList("{{a}}", "{{b:-}}")));+ Assertions.assertEquals(+ Lists.newArrayList("c", "z"),+ Lists.newArrayList(+ JobTemplatePlaceholderUtils.findUnusedKeys(+ parameters, ImmutableMap.of("z", "1", "a", "1", "c", "1"))));+ }++ private static JobTemplateEntity.TemplateContent shellContent(List<String> arguments) {+ return JobTemplateEntity.TemplateContent.builder()+ .withJobType(JobTemplate.JobType.SHELL)+ .withExecutable("/bin/echo")+ .withArguments(arguments)+ .withEnvironments(Collections.emptyMap())+ .withCustomFields(Collections.emptyMap())+ .withScripts(Collections.emptyList())+ .build();+ }++ private static void assertMessage(String value, String expected) {+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> replace(value, Collections.emptyMap()));+ Assertions.assertTrue(e.getMessage().contains(expected), e.getMessage());+ }++ private static void assertMalformed(String value, String name) {+ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> replace(value, Collections.emptyMap()));+ Assertions.assertTrue(e.getMessage().contains(name), e.getMessage());+ }++ // Replaces the placeholders of a single value, whose default values are the ones written on it.+ private static String replace(String value, Map<String, String> jobConf) {+ return JobTemplatePlaceholderUtils.replacePlaceholders(value, jobConf, Collections.emptyMap());+ }+}diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobTemplate.java b/core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.javasimilarity index 65%rename from core/src/test/java/org/apache/gravitino/job/TestJobTemplate.javarename to core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.javaindex 7d2115d8c3..5ea282f795 100644--- a/core/src/test/java/org/apache/gravitino/job/TestJobTemplate.java+++ b/core/src/test/java/org/apache/gravitino/job/TestJobTemplateResolver.java@@ -20,16 +20,22 @@ 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.Map;+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;@@ -38,7 +44,7 @@ import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;-public class TestJobTemplate {+public class TestJobTemplateResolver {private static File tempDir;private File tempStagingDir;@@ -73,95 +79,12 @@ public class TestJobTemplate {}}- @Test- public void testReplacePlaceholders() {- String template = "Hello, {{name}}! Welcome to {{place}}.";- Map<String, String> replacements = ImmutableMap.of("name", "Alice", "place", "Wonderland");-- String result = JobManager.replacePlaceholder(template, replacements);- Assertions.assertEquals("Hello, Alice! Welcome to Wonderland.", result);-- // Test with missing replacements- replacements = ImmutableMap.of("name", "Bob");- result = JobManager.replacePlaceholder(template, replacements);- Assertions.assertEquals("Hello, Bob! Welcome to {{place}}.", result);-- // Test with no replacements- result = JobManager.replacePlaceholder(template, ImmutableMap.of());- Assertions.assertEquals("Hello, {{name}}! Welcome to {{place}}.", result);-- // Test with no placeholders- String noPlaceholders = "Hello, World!";- result = JobManager.replacePlaceholder(noPlaceholders, replacements);- Assertions.assertEquals("Hello, World!", result);-- // Test with repeated placeholders- String repeatedTemplate = "Hello, {{name}}! Your name is {{name}}.";- replacements = ImmutableMap.of("name", "Charlie");- result = JobManager.replacePlaceholder(repeatedTemplate, replacements);- Assertions.assertEquals("Hello, Charlie! Your name is Charlie.", result);-- // Test with incomplete placeholders- String incompleteTemplate = "Hello, {{name}! Welcome to {{place}}.";- replacements = ImmutableMap.of("name", "Dave", "place", "Earth");- result = JobManager.replacePlaceholder(incompleteTemplate, replacements);- Assertions.assertEquals("Hello, {{name}! Welcome to Earth.", result);-- // Test with empty template- String emptyTemplate = "";- result = JobManager.replacePlaceholder(emptyTemplate, replacements);- Assertions.assertEquals("", result);-- // Test with nested braces- String nestedTemplate = "Hello, {{name}}! Your code is {{{value}}}.";- replacements = ImmutableMap.of("name", "Eve", "value", "42");- result = JobManager.replacePlaceholder(nestedTemplate, replacements);- Assertions.assertEquals("Hello, Eve! Your code is {42}.", result);-- nestedTemplate = "Hello, {{name}}! Your code is {{{{value}}}}.";- result = JobManager.replacePlaceholder(nestedTemplate, replacements);- Assertions.assertEquals("Hello, Eve! Your code is {{42}}.", result);-- // Test with special characters in placeholders.- String specialTemplate = "Hello, {{name}}! Your score is {{score%}}.";- replacements = ImmutableMap.of("name", "Frank", "score%", "100%");- result = JobManager.replacePlaceholder(specialTemplate, replacements);- Assertions.assertEquals("Hello, Frank! Your score is {{score%}}.", result);-- // Test with alphanumeric placeholders- String alphanumericTemplate = "Hello, {{user_name}}! Your score is {{score123}}.";- replacements = ImmutableMap.of("user_name", "Grace", "score123", "200");- result = JobManager.replacePlaceholder(alphanumericTemplate, replacements);- Assertions.assertEquals("Hello, Grace! Your score is 200.", result);-- // Test with "." and "-"- String dotDashTemplate = "Hello, {{user.name}}! Your score is {{score-123}}.";- replacements = ImmutableMap.of("user.name", "Hank", "score-123", "300");- result = JobManager.replacePlaceholder(dotDashTemplate, replacements);- Assertions.assertEquals("Hello, Hank! Your score is 300.", result);- }-- @Test- public void testReplacePlaceholdersWithSpecialCharacters() {- // Replacement values containing '$' and '\' must be treated as literal text,- // not as Matcher replacement syntax (group references and escapes).- String template = "config={{conf}}";-- Map<String, String> replacements = ImmutableMap.of("conf", "path=C:\\tmp and cost=$5");- String result = JobManager.replacePlaceholder(template, replacements);- Assertions.assertEquals("config=path=C:\\tmp and cost=$5", result);-- // A '$' followed by a digit must not substitute the placeholder's own group- replacements = ImmutableMap.of("conf", "p$1x");- result = JobManager.replacePlaceholder(template, replacements);- Assertions.assertEquals("config=p$1x", result);- }-@Testpublic void testFetchFilesFromUir() throws IOException {File testFile1 = Files.createTempFile(tempDir.toPath(), "testFile1", ".txt").toFile();String result =- JobManager.fetchFileFromUri(testFile1.toURI().toString(), tempStagingDir, 30 * 1000);+ JobTemplateResolver.fetchFileFromUri(+ testFile1.toURI().toString(), tempStagingDir, 30 * 1000);File resultFile = new File(result);Assertions.assertEquals(testFile1.getName(), resultFile.getName());@@ -170,7 +93,8 @@ public class TestJobTemplate {List<String> expectedUris =Lists.newArrayList(testFile2.toURI().toString(), testFile3.toURI().toString());- List<String> resultUris = JobManager.fetchFilesFromUri(expectedUris, tempStagingDir, 30 * 1000);+ List<String> resultUris =+ JobTemplateResolver.fetchFilesFromUri(expectedUris, tempStagingDir, 30 * 1000);Assertions.assertEquals(2, resultUris.size());List<String> resultFileNames =@@ -209,15 +133,15 @@ public class TestJobTemplate {.build();JobTemplate result =- JobManager.createRuntimeJobTemplate(- entity,- ImmutableMap.of(- "arg3", "value3",- "arg4", "value4",- "val1", "value1",- "val2", "value2",- "customVal1", "customValue1"),- tempStagingDir);+ new JobTemplateResolver(entity)+ .resolve(+ ImmutableMap.of(+ "arg3", "value3",+ "arg4", "value4",+ "val1", "value1",+ "val2", "value2",+ "customVal1", "customValue1"),+ tempStagingDir);Assertions.assertEquals(shellJobTemplate.name(), result.name());Assertions.assertEquals(shellJobTemplate.comment(), result.comment());@@ -270,17 +194,17 @@ public class TestJobTemplate {.build();JobTemplate result =- JobManager.createRuntimeJobTemplate(- entity,- ImmutableMap.of(- "arg3", "value3",- "arg4", "value4",- "val1", "value1",- "val2", "value2",- "customVal1", "customValue1",- "scriptName1", "testScript1",- "scriptName2", "testScript2"),- tempStagingDir);+ new JobTemplateResolver(entity)+ .resolve(+ ImmutableMap.of(+ "arg3", "value3",+ "arg4", "value4",+ "val1", "value1",+ "val2", "value2",+ "customVal1", "customValue1",+ "scriptName1", "testScript1",+ "scriptName2", "testScript2"),+ tempStagingDir);Assertions.assertEquals("echo", new File(result.executable).getName());Assertions.assertEquals(2, ((ShellJobTemplate) result).scripts().size());@@ -337,16 +261,16 @@ public class TestJobTemplate {.build();JobTemplate result =- JobManager.createRuntimeJobTemplate(- entity,- ImmutableMap.of(- "arg3", "value3",- "val1", "value1",- "val2", "value2",- "customVal1", "customValue1",- "executor-mem", "4g",- "driver-cores", "2"),- tempStagingDir);+ new JobTemplateResolver(entity)+ .resolve(+ ImmutableMap.of(+ "arg3", "value3",+ "val1", "value1",+ "val2", "value2",+ "customVal1", "customValue1",+ "executor-mem", "4g",+ "driver-cores", "2"),+ tempStagingDir);Assertions.assertEquals(sparkJobTemplate.name(), result.name());Assertions.assertEquals(sparkJobTemplate.comment(), result.comment());@@ -434,17 +358,17 @@ public class TestJobTemplate {.build();JobTemplate result =- JobManager.createRuntimeJobTemplate(- entity,- ImmutableMap.of(- "arg3", "value3",- "val1", "value1",- "val2", "value2",- "customVal1", "customValue1",- "executor-mem", "4g",- "driver-cores", "2",- "env", "test"),- tempStagingDir);+ new JobTemplateResolver(entity)+ .resolve(+ ImmutableMap.of(+ "arg3", "value3",+ "val1", "value1",+ "val2", "value2",+ "customVal1", "customValue1",+ "executor-mem", "4g",+ "driver-cores", "2",+ "env", "test"),+ tempStagingDir);Assertions.assertEquals(executable.getName(), new File(result.executable).getName());Assertions.assertEquals(Lists.newArrayList("arg1", "arg2", "value3"), result.arguments());@@ -474,4 +398,179 @@ public class TestJobTemplate {.collect(Collectors.toList());Assertions.assertTrue(archiveNames.contains(archive1.getName()));}++ @Test+ public void testCheckJobConf() {+ JobTemplateEntity entity =+ shellTemplateEntity(Lists.newArrayList("{{table}}", "{{target}}", "{{mode:-full}}"));++ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> new JobTemplateResolver(entity).checkJobConf(ImmutableMap.of("table", "t")));+ Assertions.assertTrue(e.getMessage().contains("[target]"), e.getMessage());+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> new JobTemplateResolver(entity).checkJobConf(null));++ // Optional parameters and unused keys don't fail the check.+ Assertions.assertDoesNotThrow(+ () ->+ new JobTemplateResolver(entity)+ .checkJobConf(ImmutableMap.of("table", "t", "target", "", "unused", "x")));+ }++ @Test+ public void testCreateUsesDefaultValues() {+ JobTemplateEntity entity =+ shellTemplateEntity(+ Lists.newArrayList("--table", "{{table}}", "--mode", "{{mode:-full}}", "{{note:-}}"));++ JobTemplate result =+ new JobTemplateResolver(entity).resolve(ImmutableMap.of("table", "t"), tempStagingDir);+ Assertions.assertEquals(+ Lists.newArrayList("--table", "t", "--mode", "full", ""), result.arguments());+ }++ @Test+ public void testCreateFailsBeforeFetchingOnMissingParameters() {+ 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);+ }++ @Test+ public void testCreateRejectsDuplicateKeysAfterResolution() {+ ShellJobTemplate template =+ ShellJobTemplate.builder()+ .withName("duplicate_keys")+ .withExecutable("/bin/echo")+ .withEnvironments(ImmutableMap.of("{{a}}", "1", "{{b}}", "2"))+ .build();+ JobTemplateEntity entity = toEntity(template);++ IllegalArgumentException e =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ new JobTemplateResolver(entity)+ .resolve(ImmutableMap.of("a", "SAME", "b", "SAME"), tempStagingDir));+ 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()+ .withName("shell_job")+ .withExecutable("/bin/echo")+ .withArguments(arguments)+ .build());+ }++ private static JobTemplateEntity toEntity(JobTemplate template) {+ return JobTemplateEntity.builder()+ .withId(1L)+ .withName(template.name())+ .withNamespace(NamespaceUtil.ofJobTemplate("test"))+ .withTemplateContent(JobTemplateEntity.TemplateContent.fromJobTemplate(template))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ }}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.javaindex 7908021347..8f1676ef42 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@@ -47,8 +47,8 @@ import org.apache.gravitino.connector.job.JobExecutionInfo;import org.apache.gravitino.connector.job.JobExecutor;import org.apache.gravitino.exceptions.NoSuchJobException;import org.apache.gravitino.job.JobHandle;-import org.apache.gravitino.job.JobManager;import org.apache.gravitino.job.JobTemplate;+import org.apache.gravitino.job.JobTemplateResolver;import org.apache.gravitino.job.ShellJobTemplate;import org.apache.gravitino.job.SparkJobTemplate;import org.apache.gravitino.json.JsonUtils;@@ -152,8 +152,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Assertions.assertNotNull(jobId);@@ -178,10 +177,9 @@ public class TestLocalJobExecutor {Assertions.assertTrue(executor.executorId().matches("[0-9a-f]{8}"));JobTemplate template =- JobManager.createRuntimeJobTemplate(- jobTemplateEntity,- ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"),- workingDir);+ new JobTemplateResolver(jobTemplateEntity)+ .resolve(+ ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"), workingDir);String jobId = executor.submitJob(template);Assertions.assertTrue(jobId.matches("local-job-" + executor.executorId() + "-[0-9a-f-]{36}"), jobId);@@ -241,8 +239,7 @@ public class TestLocalJobExecutor {"arg2", "fail","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Assertions.assertNotNull(jobId);@@ -307,8 +304,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -356,8 +352,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -394,9 +389,9 @@ 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 =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDirA);+ new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDirA);JobTemplate templateB =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDirB);+ new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDirB);exec.submitJob(templateA);String jobIdB = exec.submitJob(templateB);@@ -424,8 +419,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -454,8 +448,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -485,8 +478,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -517,8 +509,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -550,8 +541,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -574,8 +564,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -601,8 +590,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Awaitility.await()@@ -631,8 +619,7 @@ public class TestLocalJobExecutor {"arg2", "success","var", "value3");- JobTemplate template =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, jobConf, workingDir);+ JobTemplate template = new JobTemplateResolver(jobTemplateEntity).resolve(jobConf, workingDir);String jobId = jobExecutor.submitJob(template);Assertions.assertNotNull(jobId);@@ -662,7 +649,7 @@ public class TestLocalJobExecutor {"var", "value3");JobTemplate successTemplate =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, successJobConf, workingDir);+ new JobTemplateResolver(jobTemplateEntity).resolve(successJobConf, workingDir);String successJobId = jobExecutor.submitJob(successTemplate);Awaitility.await().atMost(3, TimeUnit.MINUTES)@@ -682,7 +669,7 @@ public class TestLocalJobExecutor {"var", "value3");JobTemplate failTemplate =- JobManager.createRuntimeJobTemplate(jobTemplateEntity, failJobConf, workingDir);+ new JobTemplateResolver(jobTemplateEntity).resolve(failJobConf, workingDir);String failJobId = jobExecutor.submitJob(failTemplate);Awaitility.await().atMost(3, TimeUnit.MINUTES)@@ -1156,10 +1143,8 @@ public class TestLocalJobExecutor {}private static JobTemplate newRuntimeJobTemplate(File jobDir) {- return JobManager.createRuntimeJobTemplate(- jobTemplateEntity,- ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"),- jobDir);+ return new JobTemplateResolver(jobTemplateEntity)+ .resolve(ImmutableMap.of("arg1", "value1", "arg2", "success", "var", "value3"), jobDir);}private static String runSucceededJob(File jobDir) {diff --git a/design-docs/iceberg-expire-snapshots-maintenance-job.md b/design-docs/iceberg-expire-snapshots-maintenance-job.mdindex 30587a9052..483ab3c1c7 100644--- a/design-docs/iceberg-expire-snapshots-maintenance-job.md+++ b/design-docs/iceberg-expire-snapshots-maintenance-job.md@@ -627,4 +627,4 @@ combined into a single PR if preferred.| Data requirements | `TABLE_METADATA` + `TABLE_STATISTICS` + `PARTITION_STATISTICS` | `TABLE_METADATA` || Trigger input | `custom-data-file-mse`, `custom-delete-file-number` (statistics) | `snapshot-count` (table metadata property) || Iceberg procedure | `rewrite_data_files` | `expire_snapshots` |-| Key parameters | strategy, sort-order, where, options (all required) | older_than, retain_last (independently optional, fall back to Iceberg table properties), stream_results (defaults to `true`) |+| Key parameters | strategy, sort-order, where, options (all required) | older_than, retain_last (independently optional, fall back to Iceberg table properties), stream_results (defaults to `false`) |diff --git a/docs/manage-jobs-in-gravitino.md b/docs/manage-jobs-in-gravitino.mdindex 165c660b59..139f48d619 100644--- a/docs/manage-jobs-in-gravitino.md+++ b/docs/manage-jobs-in-gravitino.md@@ -29,8 +29,8 @@ means implementing an executor. See### Register a Shell Template-A shell template runs an executable. Placeholders in `arguments`, `environments`, and `customFields`-are filled in when a job runs.+A shell template runs an executable. Its placeholders are filled in with the job configuration when+a job runs. See [Placeholders](#placeholders).```json{@@ -85,6 +85,53 @@ an error that names the missing setting, and no job is created.}```+### Placeholders++Any string in a template can contain placeholders: `executable`, `className`, the entries of+`scripts`, `jars`, `files`, and `archives`, and the keys and values of `environments`, `configs`,+and `customFields`. When a job runs, each placeholder is replaced with a value from the job+configuration (`jobConf`).++| Syntax | Meaning |+|---------------------|----------------------------------------------------------------------------------------------|+| `{{name}}` | Required. A run without a value for `name` is rejected. |+| `{{name:-default}}` | Optional. `default` is used when the job configuration has no value. It can be empty: `{{name:-}}`. |+| `\{{` | A literal `{{`, for example to pass `{{ds}}` to another tool. Written as `"\\{{"` in JSON. |++For example, a template with `"arguments": ["--date", "{{date}}", "--mode", "{{mode:-full}}"]` run+with `{"date": "2026-09-22"}` passes `--date 2026-09-22 --mode full` to the job.++:::caution+Templates registered before Gravitino supported default values could pass an unresolved+placeholder through to the job as literal text, which is how templates carried another tool's+syntax, such as `{{ds}}` or `{{.Values.image}}`. A placeholder with no value is now a required+parameter, so those runs are rejected. Escape such text as `\{{ds}}`, or give the parameter a+default value.+:::++- A value in the job configuration is used as is, including an empty string `""`. A `null` value+ counts as no value. Values are never scanned for placeholders.+- A default declared on one occurrence of a parameter applies to all of its occurrences. A+ template that gives the same parameter different defaults is rejected when it is registered or+ updated.+- A default value is used as is and can span lines, but its braces must be balanced, so the+ placeholder ends at the first `}}` outside of them. This makes a JSON object a valid default, for+ example `{{options:-{"k":"v"}}}`. A default with unbalanced braces, such as `{{options:-{}}`, is+ rejected when the template is registered or updated.+- If any required parameter has no value, the run request fails with an error that lists all the+ missing parameters. No job is created and no file is downloaded.+- Keys in the job configuration that the template does not use are ignored, and the server logs a+ warning.+- A placeholder name can contain ASCII letters, digits, `_`, `.`, and `-`. Text such as+ `{{ name }}`, with spaces, is not a placeholder and is passed through as is.+- Only `{{` needs escaping. A placeholder always starts with `{{`, so `}}` on its own is plain+ text. A value that ends with a backslash right before a placeholder doubles it, as in+ `\\{{name}}`, which keeps one backslash and still resolves the placeholder. A backslash anywhere+ else is plain text.+- A placeholder whose default value contains braces cannot be immediately followed by a literal+ `}`, because it is then unclear which `}}` closes it. Put the whole structure in the default+ value, or insert a space. A default value without braces, such as `{"k":{{v:-1}}}`, is fine.+### List, Get, and Delete Templates<Tabs groupId='language' queryString>diff --git a/docs/table-maintenance-service/optimizer-cli-reference.md b/docs/table-maintenance-service/optimizer-cli-reference.mdindex 5fe7e04a7e..26c989d799 100644--- a/docs/table-maintenance-service/optimizer-cli-reference.md+++ b/docs/table-maintenance-service/optimizer-cli-reference.md@@ -259,11 +259,22 @@ in Gravitino's own jobs tests is `org.apache.iceberg:iceberg-spark-runtime-3.5_2Without that runtime, built-in Iceberg jobs fail after Spark starts instead of continuing withoutIceberg support.-Optional template arguments are still listed as `--flag` + `{{placeholder}}` pairs. If `jobConf`-omits a key (or leaves the placeholder unresolved), the flag remains on the process command line as-a dangling argument (for example `--updater-options` with no value before `--spark-conf`). Callers-and UIs should supply every placeholder they care about with an explicit value, including optional-ones they intentionally disable or leave at a documented default, rather than omitting the key.+`jobConf` only needs the required keys below. Optional keys fall back to the template default when+left out, and a submission that misses a required key is rejected with an error that lists the+missing keys. An empty string is a value, not an omission: it overrides the default and means+"not set" to these jobs.++| Job template | Required keys | Optional keys and defaults |+|--------------------------------------|-----------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|+| Every Iceberg job | `catalog_name`, `table_identifier`, `catalog_type`, `catalog_uri`, `warehouse_location` | `spark_master` (`local[*]`), `spark_executor_instances` (`1`), `spark_executor_cores` (`1`), `spark_executor_memory` (`1g`), `spark_driver_memory` (`1g`), `spark_conf` (empty) |+| `builtin-iceberg-update-stats` | — | `update_mode` (`all`), `updater_options` (empty) |+| `builtin-iceberg-rewrite-data-files` | `where_clause` (pass `""` to rewrite the whole table) | `strategy` (`binpack`), `sort_order` (empty), `options` (empty) |+| `builtin-iceberg-expire-snapshots` | — | `older_than` (empty), `retain_last` (empty), `stream_results` (`false`) |+| `builtin-iceberg-remove-orphan-files` | — | `older_than` (empty), `location` (empty), `dry_run` (`false`) |+| `builtin-iceberg-rewrite-manifests` | — | `use_caching` (empty), `spec_id` (empty) |++`where_clause` has no default on purpose: an empty where clause compacts every data file in the+table, so it must be asked for explicitly.## Update Statisticsdiff --git a/docs/table-maintenance-service/optimizer-configuration.md b/docs/table-maintenance-service/optimizer-configuration.mdindex 465afb3e06..f17eafc9ab 100644--- a/docs/table-maintenance-service/optimizer-configuration.md+++ b/docs/table-maintenance-service/optimizer-configuration.md@@ -74,6 +74,11 @@ redacts them in DRY-RUN / SUBMIT output).Everything under `gravitino.optimizer.jobSubmitterConfig.` becomes the `jobConf` of jobs this CLI submits, so the two layers carry the same keys under different names.+The policy-driven path needs the same keys. Its compaction adapter only derives the table, the+where clause and the rewrite options from the policy, so `catalog_name`, `catalog_type`,+`catalog_uri` and `warehouse_location` must come from `gravitino.optimizer.jobSubmitterConfig.`.+Missing ones are reported when the job is submitted, instead of failing later inside Spark.+## Job Submission ConfigurationA direct job submission carries its own `jobConf`. This is `builtin-iceberg-update-stats` with the keys it needs.@@ -98,11 +103,11 @@ A direct job submission carries its own `jobConf`. This is `builtin-iceberg-upda`updater_options` and `spark_conf` are JSON strings inside a JSON object, so their quotes are escaped. That nesting is the most common source of malformed submissions.-Built-in Iceberg templates list optional keys as `--flag` + `{{placeholder}}`. Omitting a key from-`jobConf` does not remove that flag from the submitted command; it can leave a dangling flag such as-`--updater-options` with no value. Prefer sending an explicit value for each placeholder you use-(or a documented default) instead of dropping the key. See-[Built-in Job Templates](./optimizer-cli-reference.md#built-in-job-templates).+Only some of these keys are required. The built-in templates give the optional ones a default, so+`jobConf` can leave them out; a submission that misses a required key is rejected with an error+that lists the missing keys. See+[Built-in Job Templates](./optimizer-cli-reference.md#built-in-job-templates) for the required keys+and the defaults of each template.Built-in Iceberg templates also need an Iceberg Spark runtime on the Spark classpath. They do notship that JAR or fill template `jars`, so include it yourself — for examplediff --git a/maintenance/jobs/build.gradle.kts b/maintenance/jobs/build.gradle.ktsindex 5d44c3f637..49615a7d97 100644--- a/maintenance/jobs/build.gradle.kts+++ b/maintenance/jobs/build.gradle.kts@@ -54,6 +54,8 @@ dependencies {testImplementation(project(":api"))testImplementation(project(":common"))+ // Used to check that the placeholders of the built-in templates resolve the way the server does.+ testImplementation(project(":core"))testImplementation(project(":clients:client-java"))testImplementation(libs.bundles.log4j)testImplementation(libs.hadoop3.common) {diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.javaindex 19b9ccf6dd..1d80a76029 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java@@ -39,7 +39,7 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob {private static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-expire-snapshots";- private static final String VERSION = "v1";+ private static final String VERSION = "v2";@Overridepublic SparkJobTemplate jobTemplate() {@@ -66,7 +66,8 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob {* <li>--older-than <timestamp> Optional. Expire snapshots older than this timestamp* (e.g., '2024-01-01 00:00:00')* <li>--retain-last <count> Optional. Number of most recent snapshots to retain- * <li>--stream-results Optional. Flag to enable streaming of intermediate results+ * <li>--stream-results [true|false] Optional. Whether to stream intermediate results. A bare+ * --stream-results means true* <li>--spark-conf <spark_conf_json> Optional. JSON map of custom Spark configurations* </ul>*@@ -115,13 +116,12 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob {// Optional argumentsString olderThan = argMap.get("older-than");String retainLast = argMap.get("retain-last");- // --stream-results is a boolean flag (presence = true)- boolean streamResults = argMap.containsKey("stream-results");String sparkConfJson = argMap.get("spark-conf");- // Validate retain-last if provided+ boolean streamResults = false;try {validateRetainLast(retainLast);+ streamResults = parseStreamResults(argMap.get("stream-results"));} catch (IllegalArgumentException e) {System.err.println("Error: " + e.getMessage());printUsage();@@ -222,6 +222,29 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob {return sql.toString();}+ /**+ * Parse the value of {@code --stream-results}.+ *+ * @param value the raw value, which is {@code true} for a bare {@code --stream-results}, and null+ * or blank when the option is absent+ * @return whether to stream intermediate results+ * @throws IllegalArgumentException if the value is neither true nor false+ */+ static boolean parseStreamResults(String value) {+ if (value == null || value.trim().isEmpty()) {+ return false;+ }+ String trimmed = value.trim();+ if ("true".equalsIgnoreCase(trimmed)) {+ return true;+ }+ if ("false".equalsIgnoreCase(trimmed)) {+ return false;+ }+ throw new IllegalArgumentException(+ "Invalid stream-results value '" + value + "'. Must be true or false");+ }+/*** Validate the retain-last parameter value.*@@ -261,7 +284,8 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob {+ " --retain-last <count> Number of most recent snapshots to retain\n"+ " Must be a positive integer (>= 1)\n"+ " Default: 1 (Iceberg default)\n"- + " --stream-results Enable streaming of intermediate delete results\n"+ + " --stream-results [bool] Stream intermediate delete results (true or false)\n"+ + " A bare --stream-results means true\n"+ " --spark-conf <json> JSON map of custom Spark configurations\n"+ " Example: '{\"spark.sql.shuffle.partitions\":\"200\"}'\n"+ " Note: Overriding required catalog/extensions/app-name configs is unsupported\n"@@ -293,12 +317,13 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob {"--table","{{table_identifier}}","--older-than",- "{{older_than}}",+ "{{older_than:-}}","--retain-last",- "{{retain_last}}",- "{{stream_results}}",+ "{{retain_last:-}}",+ "--stream-results",+ "{{stream_results:-false}}","--spark-conf",- "{{spark_conf}}");+ "{{spark_conf:-}}");}/**diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.javaindex e8569a966d..0aaab168a0 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java@@ -51,7 +51,7 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob {private static final Logger LOG = LoggerFactory.getLogger(IcebergRemoveOrphanFilesJob.class);private static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-remove-orphan-files";- private static final String VERSION = "v1";+ private static final String VERSION = "v2";@Overridepublic SparkJobTemplate jobTemplate() {@@ -180,13 +180,13 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob {"--table","{{table_identifier}}","--older-than",- "{{older_than}}",+ "{{older_than:-}}","--location",- "{{location}}",+ "{{location:-}}","--dry-run",- "{{dry_run}}",+ "{{dry_run:-false}}","--spark-conf",- "{{spark_conf}}");+ "{{spark_conf:-}}");}private static Map<String, String> buildSparkConfigs() {diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.javaindex c3e3453bea..87ca6ab715 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java@@ -39,7 +39,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob {private static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-rewrite-data-files";- private static final String VERSION = "v1";+ private static final String VERSION = "v2";// Valid strategy values for Iceberg rewrite_data_files procedureprivate static final String STRATEGY_BINPACK = "binpack";@@ -378,15 +378,17 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob {"--table","{{table_identifier}}","--strategy",- "{{strategy}}",+ "{{strategy:-binpack}}","--sort-order",- "{{sort_order}}",+ "{{sort_order:-}}",+ // No default on purpose: an empty where clause rewrites the whole table, so callers must+ // pass it explicitly, as "" to target the whole table."--where","{{where_clause}}","--options",- "{{options}}",+ "{{options:-}}","--spark-conf",- "{{spark_conf}}");+ "{{spark_conf:-}}");}/**diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.javaindex 4044379c7e..4c4ec7dbd8 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java@@ -41,7 +41,7 @@ public class IcebergRewriteManifestsJob implements BuiltInJob {private static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-rewrite-manifests";- private static final String VERSION = "v1";+ private static final String VERSION = "v2";@Overridepublic SparkJobTemplate jobTemplate() {@@ -248,11 +248,11 @@ public class IcebergRewriteManifestsJob implements BuiltInJob {"--table","{{table_identifier}}","--use-caching",- "{{use_caching}}",+ "{{use_caching:-}}","--spec-id",- "{{spec_id}}",+ "{{spec_id:-}}","--spark-conf",- "{{spark_conf}}");+ "{{spark_conf:-}}");}/**diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.javaindex 21db50d6f6..abf482de3b 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java@@ -61,7 +61,7 @@ public class IcebergUpdateStatsAndMetricsJob implements BuiltInJob {private static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-update-stats";- private static final String VERSION = "v1";+ private static final String VERSION = "v2";private static final String DEFAULT_STATISTICS_UPDATER = "gravitino-statistics-updater";private static final String DEFAULT_METRICS_UPDATER = "gravitino-metrics-updater";private static final long DEFAULT_TARGET_FILE_SIZE_BYTES = 128L * 1024 * 1024;@@ -558,11 +558,11 @@ public class IcebergUpdateStatsAndMetricsJob implements BuiltInJob {"--table","{{table_identifier}}","--update-mode",- "{{update_mode}}",+ "{{update_mode:-all}}","--updater-options",- "{{updater_options}}",+ "{{updater_options:-}}","--spark-conf",- "{{spark_conf}}");+ "{{spark_conf:-}}");}private static Map<String, String> buildSparkConfigs() {diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/spark/SparkPiJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/spark/SparkPiJob.javaindex 6ff35181ea..e97348bb5e 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/spark/SparkPiJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/spark/SparkPiJob.java@@ -40,7 +40,7 @@ public class SparkPiJob implements BuiltInJob {private static final String NAME = JobTemplateProvider.BUILTIN_NAME_PREFIX + "sparkpi";// Bump VERSION whenever SparkPi template behavior changes (name/executable/class/args/configs).- private static final String VERSION = "v1";+ private static final String VERSION = "v2";@Overridepublic SparkJobTemplate jobTemplate() {@@ -49,7 +49,7 @@ public class SparkPiJob implements BuiltInJob {.withComment("Built-in SparkPi job template").withExecutable(resolveExecutable(SparkPiJob.class)).withClassName(SparkPiJob.class.getName())- .withArguments(Collections.singletonList("{{slices}}"))+ .withArguments(Collections.singletonList("{{slices:-2}}")).withConfigs(buildSparkConfigs()).withCustomFields(Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, VERSION))@@ -94,11 +94,11 @@ public class SparkPiJob implements BuiltInJob {private Map<String, String> buildSparkConfigs() {Map<String, String> configs = new HashMap<>();- configs.put("spark.master", "{{spark_master}}");- configs.put("spark.executor.instances", "{{spark_executor_instances}}");- configs.put("spark.executor.cores", "{{spark_executor_cores}}");- configs.put("spark.executor.memory", "{{spark_executor_memory}}");- configs.put("spark.driver.memory", "{{spark_driver_memory}}");+ configs.put("spark.master", "{{spark_master:-local[*]}}");+ configs.put("spark.executor.instances", "{{spark_executor_instances:-1}}");+ configs.put("spark.executor.cores", "{{spark_executor_cores:-1}}");+ configs.put("spark.executor.memory", "{{spark_executor_memory:-1g}}");+ configs.put("spark.driver.memory", "{{spark_driver_memory:-1g}}");return Collections.unmodifiableMap(configs);}}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TemplateArguments.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TemplateArguments.javanew file mode 100644index 0000000000..f7e4778554--- /dev/null+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TemplateArguments.java@@ -0,0 +1,70 @@+/*+ * 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.maintenance.jobs;++import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import org.apache.gravitino.job.JobTemplate;++/**+ * Resolves the arguments of a job template the way the Gravitino server does, so a test can run a+ * job with the arguments its own template produces.+ */+public final class TemplateArguments {++ private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{([\\w.-]+)(?::-(.*?))?}}");++ private TemplateArguments() {}++ /**+ * Resolves the arguments of a job template against a job configuration. A parameter takes its+ * value from the job configuration, and otherwise the default value its placeholder declares.+ *+ * @param template the job template+ * @param jobConf the job configuration+ * @return the resolved arguments+ * @throws IllegalArgumentException if a parameter has neither a value nor a default value+ */+ public static String[] resolve(JobTemplate template, Map<String, String> jobConf) {+ return template.arguments().stream()+ .map(argument -> resolve(argument, jobConf))+ .toArray(String[]::new);+ }++ private static String resolve(String argument, Map<String, String> jobConf) {+ Matcher matcher = PLACEHOLDER.matcher(argument);+ StringBuilder resolved = new StringBuilder();+ while (matcher.find()) {+ String name = matcher.group(1);+ String replacement = jobConf.get(name);+ if (replacement == null) {+ replacement = matcher.group(2);+ }+ if (replacement == null) {+ throw new IllegalArgumentException(+ "No value is provided for the job template parameter " + name);+ }+ matcher.appendReplacement(resolved, Matcher.quoteReplacement(replacement));+ }+ matcher.appendTail(resolved);+ return resolved.toString();+ }+}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.javaindex 4470dc10df..7f38c34966 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java@@ -18,14 +18,24 @@*/package org.apache.gravitino.maintenance.jobs;+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertTrue;+import com.google.common.collect.ImmutableSet;+import java.time.Instant;+import java.util.HashMap;import java.util.List;+import java.util.Map;+import java.util.Set;import org.apache.gravitino.job.JobTemplate;import org.apache.gravitino.job.JobTemplateProvider;+import org.apache.gravitino.job.JobTemplateResolver;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.JobTemplateEntity;+import org.apache.gravitino.utils.NamespaceUtil;import org.junit.jupiter.api.Test;public class TestBuiltInJobTemplateProvider {@@ -75,4 +85,58 @@ public class TestBuiltInJobTemplateProvider {"Version should match pattern v\\d+: " + version);}}++ @Test+ public void testTemplatesOnlyRequireTheParametersTheyHaveTo() {+ // A built-in template must let a caller run it with the catalog and the table alone, so every+ // other parameter needs a default value. The catalog connection has no default that fits every+ // catalog, and an empty where clause rewrites a whole table, so those stay required.+ Map<String, Set<String>> expected = new HashMap<>();+ Set<String> icebergCatalog =+ ImmutableSet.of(+ "catalog_name",+ "catalog_type",+ "catalog_uri",+ "table_identifier",+ "warehouse_location");+ expected.put("builtin-sparkpi", ImmutableSet.of());+ expected.put("builtin-iceberg-update-stats", icebergCatalog);+ expected.put("builtin-iceberg-expire-snapshots", icebergCatalog);+ expected.put("builtin-iceberg-remove-orphan-files", icebergCatalog);+ expected.put("builtin-iceberg-rewrite-manifests", icebergCatalog);+ expected.put(+ "builtin-iceberg-rewrite-data-files",+ ImmutableSet.<String>builder().addAll(icebergCatalog).add("where_clause").build());++ for (JobTemplate template : new BuiltInJobTemplateProvider().jobTemplates()) {+ Set<String> required = new JobTemplateResolver(toEntity(template)).requiredParameters();+ assertEquals(+ expected.get(template.name()),+ required,+ "Unexpected required parameters of built-in job template " + template.name());+ }+ }++ @Test+ public void testAllTemplatePlaceholdersAreValid() {+ // Built-in templates are stored without going through registerJobTemplate, so a malformed+ // placeholder in one of them would only fail when a job runs from it.+ for (JobTemplate template : new BuiltInJobTemplateProvider().jobTemplates()) {+ assertDoesNotThrow(+ () -> JobTemplateResolver.validate(toEntity(template)),+ "Built-in job template has invalid placeholders: " + template.name());+ }+ }++ private static JobTemplateEntity toEntity(JobTemplate template) {+ return JobTemplateEntity.builder()+ .withId(1L)+ .withName(template.name())+ .withComment(template.comment())+ .withNamespace(NamespaceUtil.ofJobTemplate("test"))+ .withTemplateContent(JobTemplateEntity.TemplateContent.fromJobTemplate(template))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ }}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.javaindex 90f71478b4..1795704542 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java@@ -21,9 +21,11 @@ package org.apache.gravitino.maintenance.jobs.iceberg;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.junit.jupiter.api.Assertions.fail;+import java.util.Arrays;import java.util.Map;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.job.SparkJobTemplate;@@ -73,22 +75,23 @@ public class TestIcebergExpireSnapshotsJob {IcebergExpireSnapshotsJob job = new IcebergExpireSnapshotsJob();SparkJobTemplate template = job.jobTemplate();- assertNotNull(template.arguments());- assertEquals(11, template.arguments().size());-- // Verify all expected arguments are present- assertTrue(template.arguments().contains("--catalog"));- assertTrue(template.arguments().contains("{{catalog_name}}"));- assertTrue(template.arguments().contains("--table"));- assertTrue(template.arguments().contains("{{table_identifier}}"));- assertTrue(template.arguments().contains("--older-than"));- assertTrue(template.arguments().contains("{{older_than}}"));- assertTrue(template.arguments().contains("--retain-last"));- assertTrue(template.arguments().contains("{{retain_last}}"));- // --stream-results is a boolean flag, value is the template variable itself- assertTrue(template.arguments().contains("{{stream_results}}"));- assertTrue(template.arguments().contains("--spark-conf"));- assertTrue(template.arguments().contains("{{spark_conf}}"));+ // Only the catalog and the table are required; the other options default to empty values,+ // which the job treats as unset, and stream results defaults to false.+ assertEquals(+ Arrays.asList(+ "--catalog",+ "{{catalog_name}}",+ "--table",+ "{{table_identifier}}",+ "--older-than",+ "{{older_than:-}}",+ "--retain-last",+ "{{retain_last:-}}",+ "--stream-results",+ "{{stream_results:-false}}",+ "--spark-conf",+ "{{spark_conf:-}}"),+ template.arguments());}@Test@@ -130,7 +133,7 @@ public class TestIcebergExpireSnapshotsJob {assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));String version = customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);- assertEquals("v1", version);+ assertEquals("v2", version);assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));}@@ -474,4 +477,27 @@ public class TestIcebergExpireSnapshotsJob {assertTrue(e.getMessage().contains("--spark-conf"));}}++ @Test+ public void testParseStreamResults() {+ assertFalse(IcebergExpireSnapshotsJob.parseStreamResults(null));+ assertFalse(IcebergExpireSnapshotsJob.parseStreamResults(""));+ assertFalse(IcebergExpireSnapshotsJob.parseStreamResults("false"));+ assertFalse(IcebergExpireSnapshotsJob.parseStreamResults(" FALSE "));+ assertTrue(IcebergExpireSnapshotsJob.parseStreamResults("true"));+ assertTrue(IcebergExpireSnapshotsJob.parseStreamResults("True"));+ assertThrows(+ IllegalArgumentException.class, () -> IcebergExpireSnapshotsJob.parseStreamResults("yes"));++ // The template renders "--stream-results false" by default, which must not enable streaming,+ // while a bare "--stream-results" on the command line still does.+ assertFalse(+ IcebergExpireSnapshotsJob.parseStreamResults(+ IcebergJobUtils.parseArguments(new String[] {"--stream-results", "false"})+ .get("stream-results")));+ assertTrue(+ IcebergExpireSnapshotsJob.parseStreamResults(+ IcebergJobUtils.parseArguments(new String[] {"--stream-results"})+ .get("stream-results")));+ }}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.javaindex d51f2a6838..8599f1b1b1 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java@@ -42,7 +42,8 @@ public class TestIcebergRemoveOrphanFilesJob {new BuiltInJobTemplateProvider().jobTemplates().stream().anyMatch(t -> t.name().equals("builtin-iceberg-remove-orphan-files")));- assertTrue(new IcebergRemoveOrphanFilesJob().jobTemplate().arguments().contains("{{dry_run}}"));+ assertTrue(+ new IcebergRemoveOrphanFilesJob().jobTemplate().arguments().contains("{{dry_run:-false}}"));}/** Verifies server-side template discovery without Spark, Iceberg, or Hadoop libraries. */diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobMain.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobMain.javaindex 5d6f293944..2ff57a8799 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobMain.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobMain.java@@ -37,6 +37,7 @@ import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;import java.util.stream.Collectors;+import org.apache.gravitino.maintenance.jobs.TemplateArguments;import org.apache.hadoop.conf.Configuration;import org.apache.iceberg.Schema;import org.apache.iceberg.hadoop.HadoopTables;@@ -110,11 +111,7 @@ public class TestIcebergRemoveOrphanFilesJobMain {}private String[] templateArguments(Map<String, String> jobConf) {- return new IcebergRemoveOrphanFilesJob()- .jobTemplate().arguments().stream()- .map(- arg -> arg.startsWith("{{") ? jobConf.get(arg.substring(2, arg.length() - 2)) : arg)- .toArray(String[]::new);+ return TemplateArguments.resolve(new IcebergRemoveOrphanFilesJob().jobTemplate(), jobConf);}private String runFailure(boolean omitIcebergRuntime, String[] args) throws Exception {diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.javaindex 9f99e673ed..e734991fb6 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java@@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.junit.jupiter.api.Assertions.fail;+import java.util.Arrays;import java.util.Map;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.job.SparkJobTemplate;@@ -73,24 +74,25 @@ public class TestIcebergRewriteDataFilesJob {IcebergRewriteDataFilesJob job = new IcebergRewriteDataFilesJob();SparkJobTemplate template = job.jobTemplate();- assertNotNull(template.arguments());- assertEquals(14, template.arguments().size()); // 7 flags * 2 (flag + value)-- // Verify all expected arguments are present- assertTrue(template.arguments().contains("--catalog"));- assertTrue(template.arguments().contains("{{catalog_name}}"));- assertTrue(template.arguments().contains("--table"));- assertTrue(template.arguments().contains("{{table_identifier}}"));- assertTrue(template.arguments().contains("--strategy"));- assertTrue(template.arguments().contains("{{strategy}}"));- assertTrue(template.arguments().contains("--sort-order"));- assertTrue(template.arguments().contains("{{sort_order}}"));- assertTrue(template.arguments().contains("--where"));- assertTrue(template.arguments().contains("{{where_clause}}"));- assertTrue(template.arguments().contains("--options"));- assertTrue(template.arguments().contains("{{options}}"));- assertTrue(template.arguments().contains("--spark-conf"));- assertTrue(template.arguments().contains("{{spark_conf}}"));+ // The where clause has no default: an empty one rewrites the whole table, so callers must+ // pass it explicitly.+ assertEquals(+ Arrays.asList(+ "--catalog",+ "{{catalog_name}}",+ "--table",+ "{{table_identifier}}",+ "--strategy",+ "{{strategy:-binpack}}",+ "--sort-order",+ "{{sort_order:-}}",+ "--where",+ "{{where_clause}}",+ "--options",+ "{{options:-}}",+ "--spark-conf",+ "{{spark_conf:-}}"),+ template.arguments());}@Test@@ -132,7 +134,7 @@ public class TestIcebergRewriteDataFilesJob {assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));String version = customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);- assertEquals("v1", version);+ assertEquals("v2", version);assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.javaindex e4b5fa322b..9d5f894acf 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java@@ -29,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.nio.charset.StandardCharsets;+import java.util.Arrays;import java.util.Map;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.job.SparkJobTemplate;@@ -146,20 +147,21 @@ public class TestIcebergRewriteManifestsJob {IcebergRewriteManifestsJob job = new IcebergRewriteManifestsJob();SparkJobTemplate template = job.jobTemplate();- assertNotNull(template.arguments());- assertEquals(10, template.arguments().size()); // 5 flags * 2 (flag + value)-- // Verify all expected arguments are present- assertTrue(template.arguments().contains("--catalog"));- assertTrue(template.arguments().contains("{{catalog_name}}"));- assertTrue(template.arguments().contains("--table"));- assertTrue(template.arguments().contains("{{table_identifier}}"));- assertTrue(template.arguments().contains("--use-caching"));- assertTrue(template.arguments().contains("{{use_caching}}"));- assertTrue(template.arguments().contains("--spec-id"));- assertTrue(template.arguments().contains("{{spec_id}}"));- assertTrue(template.arguments().contains("--spark-conf"));- assertTrue(template.arguments().contains("{{spark_conf}}"));+ // Only the catalog and the table are required; the other options default to empty values,+ // which the job treats as unset.+ assertEquals(+ Arrays.asList(+ "--catalog",+ "{{catalog_name}}",+ "--table",+ "{{table_identifier}}",+ "--use-caching",+ "{{use_caching:-}}",+ "--spec-id",+ "{{spec_id:-}}",+ "--spark-conf",+ "{{spark_conf:-}}"),+ template.arguments());}@Test@@ -195,7 +197,7 @@ public class TestIcebergRewriteManifestsJob {assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));String version = customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);- assertEquals("v1", version);+ assertEquals("v2", version);assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.javaindex 81edc2e4c1..e518511c6e 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java@@ -31,6 +31,7 @@ import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;+import org.apache.gravitino.maintenance.jobs.TemplateArguments;import org.apache.spark.sql.Row;import org.apache.spark.sql.SparkSession;import org.junit.jupiter.api.AfterEach;@@ -193,18 +194,7 @@ public class TestIcebergRewriteManifestsJobWithSpark {if (caching != null) {jobConf.put("use_caching", caching);}- // Model JobManager's template substitution, including unresolved optional values.- return new IcebergRewriteManifestsJob()- .jobTemplate().arguments().stream()- .map(- value -> {- String resolved = value;- for (Map.Entry<String, String> entry : jobConf.entrySet()) {- resolved = resolved.replace("{{" + entry.getKey() + "}}", entry.getValue());- }- return resolved;- })- .toArray(String[]::new);+ return TemplateArguments.resolve(new IcebergRewriteManifestsJob().jobTemplate(), jobConf);}private void startSpark() {diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.javaindex 2baefa9043..d15ddb92ca 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.java@@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.Map;@@ -41,7 +42,7 @@ public class TestIcebergUpdateStatsJob {assertNotNull(template);assertEquals("builtin-iceberg-update-stats", template.name());assertTrue(template.name().matches(JobTemplateProvider.BUILTIN_NAME_PATTERN));- assertEquals("v1", template.customFields().get(JobTemplateProvider.PROPERTY_VERSION_KEY));+ assertEquals("v2", template.customFields().get(JobTemplateProvider.PROPERTY_VERSION_KEY));}@Test@@ -49,18 +50,19 @@ public class TestIcebergUpdateStatsJob {IcebergUpdateStatsAndMetricsJob job = new IcebergUpdateStatsAndMetricsJob();SparkJobTemplate template = job.jobTemplate();- assertNotNull(template.arguments());- assertEquals(10, template.arguments().size());- assertTrue(template.arguments().contains("--catalog"));- assertTrue(template.arguments().contains("{{catalog_name}}"));- assertTrue(template.arguments().contains("--table"));- assertTrue(template.arguments().contains("{{table_identifier}}"));- assertTrue(template.arguments().contains("--update-mode"));- assertTrue(template.arguments().contains("{{update_mode}}"));- assertTrue(template.arguments().contains("--updater-options"));- assertTrue(template.arguments().contains("{{updater_options}}"));- assertTrue(template.arguments().contains("--spark-conf"));- assertTrue(template.arguments().contains("{{spark_conf}}"));+ assertEquals(+ Arrays.asList(+ "--catalog",+ "{{catalog_name}}",+ "--table",+ "{{table_identifier}}",+ "--update-mode",+ "{{update_mode:-all}}",+ "--updater-options",+ "{{updater_options:-}}",+ "--spark-conf",+ "{{spark_conf:-}}"),+ template.arguments());}@Testdiff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/spark/TestSparkPiJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/spark/TestSparkPiJob.javaindex e2afbd2115..768f3c881a 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/spark/TestSparkPiJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/spark/TestSparkPiJob.java@@ -73,7 +73,7 @@ public class TestSparkPiJob {assertNotNull(template.arguments());assertEquals(1, template.arguments().size());- assertEquals("{{slices}}", template.arguments().get(0));+ assertEquals("{{slices:-2}}", template.arguments().get(0));}@Test@@ -93,11 +93,11 @@ public class TestSparkPiJob {assertTrue(configs.containsKey("spark.driver.memory"));// Verify placeholders- assertEquals("{{spark_master}}", configs.get("spark.master"));- assertEquals("{{spark_executor_instances}}", configs.get("spark.executor.instances"));- assertEquals("{{spark_executor_cores}}", configs.get("spark.executor.cores"));- assertEquals("{{spark_executor_memory}}", configs.get("spark.executor.memory"));- assertEquals("{{spark_driver_memory}}", configs.get("spark.driver.memory"));+ assertEquals("{{spark_master:-local[*]}}", configs.get("spark.master"));+ assertEquals("{{spark_executor_instances:-1}}", configs.get("spark.executor.instances"));+ assertEquals("{{spark_executor_cores:-1}}", configs.get("spark.executor.cores"));+ assertEquals("{{spark_executor_memory:-1g}}", configs.get("spark.executor.memory"));+ assertEquals("{{spark_driver_memory:-1g}}", configs.get("spark.driver.memory"));}@Test@@ -110,7 +110,7 @@ public class TestSparkPiJob {assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));String version = customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);- assertEquals("v1", version);+ assertEquals("v2", version);assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));}diff --git a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.java b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.javaindex 0e03e3ecc3..a1f92aae7e 100644--- a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.java+++ b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.java@@ -50,11 +50,12 @@ public final class IcebergSparkConfigUtils {/** Build default Spark template configs for Iceberg jobs. */public static Map<String, String> buildTemplateSparkConfigs() {Map<String, String> configs = new HashMap<>();- configs.put("spark.master", "{{spark_master}}");- configs.put("spark.executor.instances", "{{spark_executor_instances}}");- configs.put("spark.executor.cores", "{{spark_executor_cores}}");- configs.put("spark.executor.memory", "{{spark_executor_memory}}");- configs.put("spark.driver.memory", "{{spark_driver_memory}}");+ configs.put("spark.master", "{{spark_master:-local[*]}}");+ configs.put("spark.executor.instances", "{{spark_executor_instances:-1}}");+ configs.put("spark.executor.cores", "{{spark_executor_cores:-1}}");+ configs.put("spark.executor.memory", "{{spark_executor_memory:-1g}}");+ configs.put("spark.driver.memory", "{{spark_driver_memory:-1g}}");+ // The catalog connection has no default that fits every catalog, so it stays required.configs.put(SPARK_SQL_CATALOG_PREFIX + "{{catalog_name}}", "org.apache.iceberg.spark.SparkCatalog");configs.put(SPARK_SQL_CATALOG_PREFIX + "{{catalog_name}}.type", "{{catalog_type}}");