lasdf1234 commented on code in PR #13468: URL: https://github.com/apache/gravitino/pull/13468#discussion_r4119078805
########## core/src/main/java/org/apache/gravitino/job/JobTemplateResolver.java: ########## @@ -0,0 +1,222 @@ +/* + * 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()); + } + + /** + * 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); + Function<String, String> fetcher = + uri -> fetchFileFromUri(resolver.apply(uri), stagingDir, FETCH_TIMEOUT_IN_MS); + + String executable = fetcher.apply(content.executable()); Review Comment: **Low / nit:** `resolve()` fetches `executable` before resolving `environments` / `customFields` / `configs`, so a duplicate-key `IllegalArgumentException` from `resolveMap()` can happen after the executable has already been downloaded into staging. `JobManager` cleans up staging on failure, so this is not a leak, but an early map-resolution pass (before any fetch) would avoid partial work on misconfigured templates. ########## core/src/main/java/org/apache/gravitino/job/JobTemplatePlaceholderUtils.java: ########## @@ -0,0 +1,335 @@ +/* + * 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. 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 therefore has to double it, as in <code>\\{{name}}</code>. + * </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 = "\\{{"; + + /** 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()) { Review Comment: **Design note (not a bug):** if the first occurrence of a parameter is required (`{{name}}`) and a later one declares a default (`{{name:-default}}`), this branch upgrades the parameter to optional with that default. That matches `testDefaultValueAppliesToAllOccurrences`, but it may be worth one sentence in the class Javadoc so template authors know declaration order matters only for the first required-vs-default transition. ########## core/src/main/java/org/apache/gravitino/job/JobManager.java: ########## @@ -508,6 +501,10 @@ public JobEntity runJob(String metalake, String jobTemplateName, Map<String, Str // 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); Review Comment: **Looks good:** rejecting missing parameters via `checkJobConf()` before `Files.createDirectories()` matches the PR goal — failed runs leave no staging artifacts. `testRunJobRejectsMissingParametersBeforeStaging` covers this path. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
