github-advanced-security[bot] commented on code in PR #18667:
URL:
https://github.com/apache/dolphinscheduler/pull/18667#discussion_r4244516541
##########
dolphinscheduler-task-plugin/dolphinscheduler-task-flink/src/main/java/org/apache/dolphinscheduler/plugin/task/flink/FlinkArgsUtils.java:
##########
@@ -63,29 +119,297 @@
/**
* build flink cancel command line
- * @param taskExecutionContext
- * @return
+ *
+ * @param jobId the Flink JobID printed by `flink run`, it is not the
YARN/K8s application id
+ * @param clusterConnectionOptions the cluster connection options of the
submission, may be empty
+ * @return argument list
*/
- public static List<String> buildCancelCommandLine(TaskExecutionContext
taskExecutionContext) {
+ public static List<String> buildCancelCommandLine(String jobId,
List<String> clusterConnectionOptions) {
List<String> args = new ArrayList<>();
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_CANCEL);
- args.add(taskExecutionContext.getAppIds());
+ args.add(jobId);
+ if (CollectionUtils.isNotEmpty(clusterConnectionOptions)) {
+ args.addAll(clusterConnectionOptions);
+ }
return args;
}
+ /**
+ * Extract the cluster connection options from the extra options of the
submission, so that the
+ * cancel / savepoint command targets the same cluster as the submission.
+ *
+ * <p>Only the options which identify the cluster are kept: {@code
-m}/{@code --jobmanager},
+ * {@code -t}/{@code --target} and the {@code -D} options which configure
the cluster address or
+ * the execution target. Submission-only arguments, such as the
parallelism, the slots, the
+ * memory, the application name, the main class or the savepoint to
restore from, are not copied.
+ * Reusing the task environment does not preserve the command line
connection options.
+ *
+ * @param others the extra options of the submission, may be null
+ * @return the cluster connection options, in the order they appear in the
submission
+ */
+ public static List<String> extractClusterConnectionOptions(String others) {
+ List<String> options = new ArrayList<>();
+ if (StringUtils.isBlank(others)) {
+ return options;
+ }
+ List<String> tokens = tokenizeOptions(others);
+ for (int i = 0; i < tokens.size(); i++) {
+ String token = tokens.get(i);
+ String option = unquoteToken(token);
+ int separator = option.indexOf('=');
+ String optionName = separator < 0 ? option : option.substring(0,
separator);
+ if (CLUSTER_CONNECTION_OPTIONS.contains(optionName)) {
+ options.add(token);
+ // the value may be given as a separate argument, for example
"-m <jobmanager>"
+ if (separator < 0 && i + 1 < tokens.size()) {
+ options.add(tokens.get(++i));
+ }
+ } else if (isClusterConnectionConfig(option)) {
+ options.add(token);
+ } else if (DYNAMIC_PROPERTY_OPTION.equals(option) && i + 1 <
tokens.size()) {
+ // the configuration may also be given as a separate argument,
"-D <key>=<value>"
+ String value = tokens.get(++i);
+ if (isClusterConnectionConfig(DYNAMIC_PROPERTY_OPTION +
unquoteToken(value))) {
+ options.add(token);
+ options.add(value);
+ }
+ }
+ }
+ return options;
+ }
+
+ /**
+ * Remove the quotes which surround a whole token, so that an option or a
value which is entirely
+ * quoted is still recognized. The original token is kept in the generated
command, the shell
+ * removes the quotes.
+ */
+ private static String unquoteToken(String token) {
+ if (token.length() > 1 && (token.charAt(0) == '"' || token.charAt(0)
== '\'')
+ && token.charAt(token.length() - 1) == token.charAt(0)) {
+ return token.substring(1, token.length() - 1);
+ }
+ return token;
+ }
+
+ /**
+ * Split the extra options of the submission into tokens. A whitespace
inside a quoted segment
+ * does not separate two tokens, and the quotes are kept so that the
generated command stays
+ * quoted for the shell. A quote may appear inside a token, for example
+ * {@code -Dkubernetes.config.file="/opt/flink configs/kube.yaml"}.
+ */
+ private static List<String> tokenizeOptions(String others) {
+ List<String> tokens = new ArrayList<>();
+ StringBuilder token = new StringBuilder();
+ char quote = 0;
+ boolean escaped = false;
+ for (int i = 0; i < others.length(); i++) {
+ char current = others.charAt(i);
+ if (escaped) {
+ token.append(current);
+ escaped = false;
+ } else if (current == '\\') {
+ token.append(current);
+ escaped = true;
+ } else if (quote != 0) {
+ token.append(current);
+ if (current == quote) {
+ quote = 0;
+ }
+ } else if (current == '"' || current == '\'') {
+ token.append(current);
+ quote = current;
+ } else if (Character.isWhitespace(current)) {
+ if (token.length() > 0) {
+ tokens.add(token.toString());
+ token.setLength(0);
+ }
+ } else {
+ token.append(current);
+ }
+ }
+ if (token.length() > 0) {
+ tokens.add(token.toString());
+ }
+ return tokens;
+ }
+
+ private static boolean isClusterConnectionConfig(String token) {
+ if (!token.startsWith(DYNAMIC_PROPERTY_OPTION) || token.length() <=
DYNAMIC_PROPERTY_OPTION.length()) {
+ return false;
+ }
+ String config = token.substring(DYNAMIC_PROPERTY_OPTION.length());
+ int separator = config.indexOf('=');
+ String key = separator < 0 ? config : config.substring(0, separator);
+ return CLUSTER_CONNECTION_CONFIG_KEYS.contains(key);
+ }
+
/**
* build flink savepoint command line, the savepoint folder should be set
in flink conf
- * @return
+ *
+ * <p>The Flink JobID identifies the job, the YARN application id only
identifies the cluster
+ * which runs it, so they are passed as different arguments. The YARN
application id is passed
+ * as the {@code -yid} targeting option, as documented by "Trigger a
Savepoint with YARN":
+ * {@code flink savepoint :jobId [:targetDirectory] -yid :yarnAppId}. The
cluster connection
+ * options of the submission are repeated as well, otherwise the savepoint
is triggered against
+ * the default cluster of the worker instead of the cluster which runs the
job.
+ *
+ * @param jobId the Flink JobID printed by `flink run`, it is not the
YARN/K8s application id
+ * @param yarnApplicationId the YARN application id used to target the
cluster, may be null
+ * @param clusterConnectionOptions the cluster connection options of the
submission, may be empty
+ * @return argument list
*/
- public static List<String> buildSavePointCommandLine(TaskExecutionContext
taskExecutionContext) {
+ public static List<String> buildSavePointCommandLine(String jobId, String
yarnApplicationId,
+ List<String>
clusterConnectionOptions) {
List<String> args = new ArrayList<>();
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_SAVEPOINT);
- args.add(taskExecutionContext.getAppIds());
+ args.add(jobId);
+ if (StringUtils.isNotBlank(yarnApplicationId)) {
+ args.add(FlinkConstants.FLINK_YARN_APPLICATION_ID);
+ args.add(yarnApplicationId);
+ }
+ if (CollectionUtils.isNotEmpty(clusterConnectionOptions)) {
+ args.addAll(clusterConnectionOptions);
+ }
return args;
}
+ /**
+ * Execute a flink command in the same environment as the task itself.
+ *
+ * <p>The task script is executed by a shell interceptor which sources
shell.env_source_list and the
+ * task's custom environment, resolves the task parameters and runs as the
task's tenant. The
+ * cancel / savepoint commands must reuse that environment, otherwise
placeholders like
+ * ${FLINK_HOME} cannot be resolved when they are only defined in the
selected task environment.
+ *
+ * @param taskExecutionContext task execution context
+ * @param args the command arguments
+ * @return true if the command finished successfully
+ */
+ public static boolean executeCommand(TaskExecutionContext
taskExecutionContext, List<String> args) {
+ return executeCommand(taskExecutionContext, args,
OSUtils.isSudoEnable(),
+ FlinkConstants.FLINK_COMMAND_TIMEOUT_SECONDS);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List)}, with a
custom timeout. The
+ * savepoint command uses a much longer timeout than the cancel command.
+ */
+ public static boolean executeCommand(TaskExecutionContext
taskExecutionContext, List<String> args,
+ int timeoutSeconds) {
+ return executeCommand(taskExecutionContext, args,
OSUtils.isSudoEnable(), timeoutSeconds);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List)}, with the
sudo mode injected so that
+ * the command execution can be verified without requiring sudo
permissions.
+ */
+ static boolean executeCommand(TaskExecutionContext taskExecutionContext,
List<String> args, boolean sudoEnable) {
+ return executeCommand(taskExecutionContext, args, sudoEnable,
FlinkConstants.FLINK_COMMAND_TIMEOUT_SECONDS);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List, int)}, with
the sudo mode injected so
+ * that the command execution can be verified without requiring sudo
permissions.
+ */
+ static boolean executeCommand(TaskExecutionContext taskExecutionContext,
List<String> args, boolean sudoEnable,
+ int timeoutSeconds) {
+ Process process = null;
+ try {
+ IShellInterceptorBuilder shellInterceptorBuilder =
ShellInterceptorBuilderFactory.newBuilder()
+ .shellDirectory(taskExecutionContext.getExecutePath())
+ .shellName(taskExecutionContext.getTaskInstanceId() +
FLINK_COMMAND_SHELL_NAME_SUFFIX
+ + System.nanoTime())
+
.properties(ParameterUtils.convert(taskExecutionContext.getPrepareParamsMap()))
+ .appendScript(String.join(" ", args))
+ .sudoMode(sudoEnable)
+ .runUser(taskExecutionContext.getTenantCode());
+ if (CollectionUtils.isNotEmpty(ShellUtils.ENV_SOURCE_LIST)) {
+
ShellUtils.ENV_SOURCE_LIST.forEach(shellInterceptorBuilder::appendSystemEnv);
+ }
+ if
(StringUtils.isNotBlank(taskExecutionContext.getEnvironmentConfig())) {
+
shellInterceptorBuilder.appendCustomEnvScript(taskExecutionContext.getEnvironmentConfig());
+ }
+ process = shellInterceptorBuilder.build().execute();
+ return waitForCommand(process, args, taskExecutionContext,
timeoutSeconds);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ log.error("Execute flink command interrupted, args: {}", args, e);
+ return false;
+ } catch (Exception e) {
+ log.error("Execute flink command error, args: {}", args, e);
Review Comment:
## CodeQL / Insertion of sensitive information into log files
This [potentially sensitive information](1) is written to a log file.
This [potentially sensitive information](2) is written to a log file.
This [potentially sensitive information](3) is written to a log file.
This [potentially sensitive information](4) is written to a log file.
This [potentially sensitive information](5) is written to a log file.
[Show more
details](https://github.com/apache/dolphinscheduler/security/code-scanning/5871)
##########
dolphinscheduler-task-plugin/dolphinscheduler-task-flink/src/main/java/org/apache/dolphinscheduler/plugin/task/flink/FlinkTask.java:
##########
@@ -104,17 +112,155 @@
}
/**
- * find app id
+ * Find the Flink JobID in a log line. Both the {@code flink run} format
(JobID) and the Flink
+ * SQL Client format (Job ID:) are supported. The returned id is the Flink
JobID, it is not the
+ * YARN/K8s application id.
*
* @param line line
- * @return appid
+ * @return the Flink JobID, or null when the line does not contain one
*/
- protected String findAppId(String line) {
- Matcher matcher = FLINK_APPLICATION_REGEX.matcher(line);
+ protected String findFlinkJobId(String line) {
+ Matcher matcher = FLINK_JOB_ID_REGEX.matcher(line);
if (matcher.find()) {
- String str = matcher.group();
- return str.substring(6);
+ return matcher.group(1);
}
return null;
}
+
+ /**
+ * Cancel the flink task.
+ *
+ * <p>The process started by the worker is only the flink client, not the
job itself: when the
+ * client exits, or when it is killed, the job keeps running for
local/standalone/session
+ * deployments. So the job is cancelled through the flink CLI first. The
process tree kill and
+ * the YARN/K8s application cancellation are used when no JobID was found
or when the task was
+ * submitted to a resource manager, and they are always used to stop the
client process when the
+ * CLI fails.
+ */
+ @Override
+ public void cancelApplication() throws TaskException {
+ TaskException cancelFailure = null;
+ try {
+ if (cancelFlinkJob()) {
+ return;
+ }
+ } catch (TaskException e) {
+ cancelFailure = e;
+ }
+ // The client process has to be stopped even when the remote job could
not be cancelled,
+ // otherwise the worker keeps the task executor running and the task
instance cannot reach a
+ // final state. The failure is still propagated afterwards.
+ try {
+ cancelClientByProcess();
+ } catch (TaskException e) {
+ if (cancelFailure == null) {
+ cancelFailure = e;
+ } else {
+ cancelFailure.addSuppressed(e);
+ }
+ }
+ if (cancelFailure != null) {
+ throw cancelFailure;
+ }
+ }
+
+ /**
+ * Stop the flink client process of the task, kept as a separate method so
that the fallback can
+ * be verified in tests.
+ */
+ protected void cancelClientByProcess() throws TaskException {
+ super.cancelApplication();
+ }
+
+ /**
+ * Cancel the flink job through the flink CLI.
+ *
+ * <p>Tasks submitted to YARN are not handled here: their application id
is known and cancelling
+ * the application through the resource manager is the reliable way. A
Kubernetes cluster is
+ * identified by a cluster id rather than by an application id, so a job
submitted to Kubernetes
+ * is cancelled through the CLI, with the cluster connection options of
the submission.
+ *
+ * @return true if the job was cancelled through the CLI, false if the
caller should fall back
+ * @throws TaskException if a cancelable job was found but could not be
cancelled, so that the
+ * failure is not hidden by the fallback
+ */
+ protected boolean cancelFlinkJob() throws TaskException {
+ try {
+ if (CollectionUtils.isNotEmpty(getApplicationIds())) {
+ return false;
+ }
+ } catch (Exception e) {
+ log.warn("Get application ids failed, taskInstanceId: {}",
taskExecutionContext.getTaskInstanceId(), e);
+ }
+ List<String> jobIds = getFlinkJobIds();
+ if (CollectionUtils.isEmpty(jobIds)) {
+ log.info(
+ "Cannot find flink JobID from the task log,
taskInstanceId: {}, will fall back to cancel by process",
+ taskExecutionContext.getTaskInstanceId());
+ return false;
+ }
+ List<String> clusterConnectionOptions = getClusterConnectionOptions();
+ for (String jobId : jobIds) {
+ List<String> args = FlinkArgsUtils.buildCancelCommandLine(jobId,
clusterConnectionOptions);
+ log.info("Cancel flink job, jobId: {}, args: {}", jobId, args);
Review Comment:
## CodeQL / Insertion of sensitive information into log files
This [potentially sensitive information](1) is written to a log file.
This [potentially sensitive information](2) is written to a log file.
This [potentially sensitive information](3) is written to a log file.
This [potentially sensitive information](4) is written to a log file.
This [potentially sensitive information](5) is written to a log file.
[Show more
details](https://github.com/apache/dolphinscheduler/security/code-scanning/5872)
##########
dolphinscheduler-task-plugin/dolphinscheduler-task-flink/src/main/java/org/apache/dolphinscheduler/plugin/task/flink/FlinkArgsUtils.java:
##########
@@ -63,29 +119,297 @@
/**
* build flink cancel command line
- * @param taskExecutionContext
- * @return
+ *
+ * @param jobId the Flink JobID printed by `flink run`, it is not the
YARN/K8s application id
+ * @param clusterConnectionOptions the cluster connection options of the
submission, may be empty
+ * @return argument list
*/
- public static List<String> buildCancelCommandLine(TaskExecutionContext
taskExecutionContext) {
+ public static List<String> buildCancelCommandLine(String jobId,
List<String> clusterConnectionOptions) {
List<String> args = new ArrayList<>();
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_CANCEL);
- args.add(taskExecutionContext.getAppIds());
+ args.add(jobId);
+ if (CollectionUtils.isNotEmpty(clusterConnectionOptions)) {
+ args.addAll(clusterConnectionOptions);
+ }
return args;
}
+ /**
+ * Extract the cluster connection options from the extra options of the
submission, so that the
+ * cancel / savepoint command targets the same cluster as the submission.
+ *
+ * <p>Only the options which identify the cluster are kept: {@code
-m}/{@code --jobmanager},
+ * {@code -t}/{@code --target} and the {@code -D} options which configure
the cluster address or
+ * the execution target. Submission-only arguments, such as the
parallelism, the slots, the
+ * memory, the application name, the main class or the savepoint to
restore from, are not copied.
+ * Reusing the task environment does not preserve the command line
connection options.
+ *
+ * @param others the extra options of the submission, may be null
+ * @return the cluster connection options, in the order they appear in the
submission
+ */
+ public static List<String> extractClusterConnectionOptions(String others) {
+ List<String> options = new ArrayList<>();
+ if (StringUtils.isBlank(others)) {
+ return options;
+ }
+ List<String> tokens = tokenizeOptions(others);
+ for (int i = 0; i < tokens.size(); i++) {
+ String token = tokens.get(i);
+ String option = unquoteToken(token);
+ int separator = option.indexOf('=');
+ String optionName = separator < 0 ? option : option.substring(0,
separator);
+ if (CLUSTER_CONNECTION_OPTIONS.contains(optionName)) {
+ options.add(token);
+ // the value may be given as a separate argument, for example
"-m <jobmanager>"
+ if (separator < 0 && i + 1 < tokens.size()) {
+ options.add(tokens.get(++i));
+ }
+ } else if (isClusterConnectionConfig(option)) {
+ options.add(token);
+ } else if (DYNAMIC_PROPERTY_OPTION.equals(option) && i + 1 <
tokens.size()) {
+ // the configuration may also be given as a separate argument,
"-D <key>=<value>"
+ String value = tokens.get(++i);
+ if (isClusterConnectionConfig(DYNAMIC_PROPERTY_OPTION +
unquoteToken(value))) {
+ options.add(token);
+ options.add(value);
+ }
+ }
+ }
+ return options;
+ }
+
+ /**
+ * Remove the quotes which surround a whole token, so that an option or a
value which is entirely
+ * quoted is still recognized. The original token is kept in the generated
command, the shell
+ * removes the quotes.
+ */
+ private static String unquoteToken(String token) {
+ if (token.length() > 1 && (token.charAt(0) == '"' || token.charAt(0)
== '\'')
+ && token.charAt(token.length() - 1) == token.charAt(0)) {
+ return token.substring(1, token.length() - 1);
+ }
+ return token;
+ }
+
+ /**
+ * Split the extra options of the submission into tokens. A whitespace
inside a quoted segment
+ * does not separate two tokens, and the quotes are kept so that the
generated command stays
+ * quoted for the shell. A quote may appear inside a token, for example
+ * {@code -Dkubernetes.config.file="/opt/flink configs/kube.yaml"}.
+ */
+ private static List<String> tokenizeOptions(String others) {
+ List<String> tokens = new ArrayList<>();
+ StringBuilder token = new StringBuilder();
+ char quote = 0;
+ boolean escaped = false;
+ for (int i = 0; i < others.length(); i++) {
+ char current = others.charAt(i);
+ if (escaped) {
+ token.append(current);
+ escaped = false;
+ } else if (current == '\\') {
+ token.append(current);
+ escaped = true;
+ } else if (quote != 0) {
+ token.append(current);
+ if (current == quote) {
+ quote = 0;
+ }
+ } else if (current == '"' || current == '\'') {
+ token.append(current);
+ quote = current;
+ } else if (Character.isWhitespace(current)) {
+ if (token.length() > 0) {
+ tokens.add(token.toString());
+ token.setLength(0);
+ }
+ } else {
+ token.append(current);
+ }
+ }
+ if (token.length() > 0) {
+ tokens.add(token.toString());
+ }
+ return tokens;
+ }
+
+ private static boolean isClusterConnectionConfig(String token) {
+ if (!token.startsWith(DYNAMIC_PROPERTY_OPTION) || token.length() <=
DYNAMIC_PROPERTY_OPTION.length()) {
+ return false;
+ }
+ String config = token.substring(DYNAMIC_PROPERTY_OPTION.length());
+ int separator = config.indexOf('=');
+ String key = separator < 0 ? config : config.substring(0, separator);
+ return CLUSTER_CONNECTION_CONFIG_KEYS.contains(key);
+ }
+
/**
* build flink savepoint command line, the savepoint folder should be set
in flink conf
- * @return
+ *
+ * <p>The Flink JobID identifies the job, the YARN application id only
identifies the cluster
+ * which runs it, so they are passed as different arguments. The YARN
application id is passed
+ * as the {@code -yid} targeting option, as documented by "Trigger a
Savepoint with YARN":
+ * {@code flink savepoint :jobId [:targetDirectory] -yid :yarnAppId}. The
cluster connection
+ * options of the submission are repeated as well, otherwise the savepoint
is triggered against
+ * the default cluster of the worker instead of the cluster which runs the
job.
+ *
+ * @param jobId the Flink JobID printed by `flink run`, it is not the
YARN/K8s application id
+ * @param yarnApplicationId the YARN application id used to target the
cluster, may be null
+ * @param clusterConnectionOptions the cluster connection options of the
submission, may be empty
+ * @return argument list
*/
- public static List<String> buildSavePointCommandLine(TaskExecutionContext
taskExecutionContext) {
+ public static List<String> buildSavePointCommandLine(String jobId, String
yarnApplicationId,
+ List<String>
clusterConnectionOptions) {
List<String> args = new ArrayList<>();
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_SAVEPOINT);
- args.add(taskExecutionContext.getAppIds());
+ args.add(jobId);
+ if (StringUtils.isNotBlank(yarnApplicationId)) {
+ args.add(FlinkConstants.FLINK_YARN_APPLICATION_ID);
+ args.add(yarnApplicationId);
+ }
+ if (CollectionUtils.isNotEmpty(clusterConnectionOptions)) {
+ args.addAll(clusterConnectionOptions);
+ }
return args;
}
+ /**
+ * Execute a flink command in the same environment as the task itself.
+ *
+ * <p>The task script is executed by a shell interceptor which sources
shell.env_source_list and the
+ * task's custom environment, resolves the task parameters and runs as the
task's tenant. The
+ * cancel / savepoint commands must reuse that environment, otherwise
placeholders like
+ * ${FLINK_HOME} cannot be resolved when they are only defined in the
selected task environment.
+ *
+ * @param taskExecutionContext task execution context
+ * @param args the command arguments
+ * @return true if the command finished successfully
+ */
+ public static boolean executeCommand(TaskExecutionContext
taskExecutionContext, List<String> args) {
+ return executeCommand(taskExecutionContext, args,
OSUtils.isSudoEnable(),
+ FlinkConstants.FLINK_COMMAND_TIMEOUT_SECONDS);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List)}, with a
custom timeout. The
+ * savepoint command uses a much longer timeout than the cancel command.
+ */
+ public static boolean executeCommand(TaskExecutionContext
taskExecutionContext, List<String> args,
+ int timeoutSeconds) {
+ return executeCommand(taskExecutionContext, args,
OSUtils.isSudoEnable(), timeoutSeconds);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List)}, with the
sudo mode injected so that
+ * the command execution can be verified without requiring sudo
permissions.
+ */
+ static boolean executeCommand(TaskExecutionContext taskExecutionContext,
List<String> args, boolean sudoEnable) {
+ return executeCommand(taskExecutionContext, args, sudoEnable,
FlinkConstants.FLINK_COMMAND_TIMEOUT_SECONDS);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List, int)}, with
the sudo mode injected so
+ * that the command execution can be verified without requiring sudo
permissions.
+ */
+ static boolean executeCommand(TaskExecutionContext taskExecutionContext,
List<String> args, boolean sudoEnable,
+ int timeoutSeconds) {
+ Process process = null;
+ try {
+ IShellInterceptorBuilder shellInterceptorBuilder =
ShellInterceptorBuilderFactory.newBuilder()
+ .shellDirectory(taskExecutionContext.getExecutePath())
+ .shellName(taskExecutionContext.getTaskInstanceId() +
FLINK_COMMAND_SHELL_NAME_SUFFIX
+ + System.nanoTime())
+
.properties(ParameterUtils.convert(taskExecutionContext.getPrepareParamsMap()))
+ .appendScript(String.join(" ", args))
+ .sudoMode(sudoEnable)
+ .runUser(taskExecutionContext.getTenantCode());
+ if (CollectionUtils.isNotEmpty(ShellUtils.ENV_SOURCE_LIST)) {
+
ShellUtils.ENV_SOURCE_LIST.forEach(shellInterceptorBuilder::appendSystemEnv);
+ }
+ if
(StringUtils.isNotBlank(taskExecutionContext.getEnvironmentConfig())) {
+
shellInterceptorBuilder.appendCustomEnvScript(taskExecutionContext.getEnvironmentConfig());
+ }
+ process = shellInterceptorBuilder.build().execute();
+ return waitForCommand(process, args, taskExecutionContext,
timeoutSeconds);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ log.error("Execute flink command interrupted, args: {}", args, e);
Review Comment:
## CodeQL / Insertion of sensitive information into log files
This [potentially sensitive information](1) is written to a log file.
This [potentially sensitive information](2) is written to a log file.
This [potentially sensitive information](3) is written to a log file.
This [potentially sensitive information](4) is written to a log file.
This [potentially sensitive information](5) is written to a log file.
[Show more
details](https://github.com/apache/dolphinscheduler/security/code-scanning/5870)
##########
dolphinscheduler-task-plugin/dolphinscheduler-task-flink-stream/src/main/java/org/apache/dolphinscheduler/plugin/task/flink/FlinkStreamTask.java:
##########
@@ -65,40 +63,43 @@
}
@Override
- public void cancelApplication() throws TaskException {
- List<String> appIds = getApplicationIds();
- if (CollectionUtils.isEmpty(appIds)) {
- log.error("can not get appId, taskInstanceId:{}",
taskExecutionContext.getTaskInstanceId());
- return;
+ public void savePoint() throws Exception {
+ // `flink savepoint` takes the Flink JobID. The YARN/K8s application
id is a different
+ // identifier: it is not the savepoint target, it only targets the
cluster which runs the
+ // job, and is passed as the `-yid` option.
+ List<String> jobIds = getFlinkJobIds();
+ if (CollectionUtils.isEmpty(jobIds)) {
+ throw new TaskException(
+ "Cannot find the flink JobID of the task, taskInstanceId: "
+ + taskExecutionContext.getTaskInstanceId());
}
- taskExecutionContext.setAppIds(String.join(TaskConstants.COMMA,
appIds));
- List<String> args =
FlinkArgsUtils.buildCancelCommandLine(taskExecutionContext);
-
- log.info("cancel application args:{}", args);
-
- ProcessBuilder processBuilder = new ProcessBuilder();
- processBuilder.command(args);
- try {
- processBuilder.start();
- } catch (IOException e) {
- throw new TaskException("cancel application error", e);
+ String yarnApplicationId = getYarnApplicationId();
+ List<String> clusterConnectionOptions = getClusterConnectionOptions();
+ for (String jobId : jobIds) {
+ List<String> args =
FlinkArgsUtils.buildSavePointCommandLine(jobId, yarnApplicationId,
+ clusterConnectionOptions);
+ log.info("savepoint args:{}", args);
Review Comment:
## CodeQL / Insertion of sensitive information into log files
This [potentially sensitive information](1) is written to a log file.
This [potentially sensitive information](2) is written to a log file.
This [potentially sensitive information](3) is written to a log file.
This [potentially sensitive information](4) is written to a log file.
This [potentially sensitive information](5) is written to a log file.
[Show more
details](https://github.com/apache/dolphinscheduler/security/code-scanning/5874)
##########
dolphinscheduler-task-plugin/dolphinscheduler-task-flink/src/main/java/org/apache/dolphinscheduler/plugin/task/flink/FlinkArgsUtils.java:
##########
@@ -63,29 +119,297 @@
/**
* build flink cancel command line
- * @param taskExecutionContext
- * @return
+ *
+ * @param jobId the Flink JobID printed by `flink run`, it is not the
YARN/K8s application id
+ * @param clusterConnectionOptions the cluster connection options of the
submission, may be empty
+ * @return argument list
*/
- public static List<String> buildCancelCommandLine(TaskExecutionContext
taskExecutionContext) {
+ public static List<String> buildCancelCommandLine(String jobId,
List<String> clusterConnectionOptions) {
List<String> args = new ArrayList<>();
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_CANCEL);
- args.add(taskExecutionContext.getAppIds());
+ args.add(jobId);
+ if (CollectionUtils.isNotEmpty(clusterConnectionOptions)) {
+ args.addAll(clusterConnectionOptions);
+ }
return args;
}
+ /**
+ * Extract the cluster connection options from the extra options of the
submission, so that the
+ * cancel / savepoint command targets the same cluster as the submission.
+ *
+ * <p>Only the options which identify the cluster are kept: {@code
-m}/{@code --jobmanager},
+ * {@code -t}/{@code --target} and the {@code -D} options which configure
the cluster address or
+ * the execution target. Submission-only arguments, such as the
parallelism, the slots, the
+ * memory, the application name, the main class or the savepoint to
restore from, are not copied.
+ * Reusing the task environment does not preserve the command line
connection options.
+ *
+ * @param others the extra options of the submission, may be null
+ * @return the cluster connection options, in the order they appear in the
submission
+ */
+ public static List<String> extractClusterConnectionOptions(String others) {
+ List<String> options = new ArrayList<>();
+ if (StringUtils.isBlank(others)) {
+ return options;
+ }
+ List<String> tokens = tokenizeOptions(others);
+ for (int i = 0; i < tokens.size(); i++) {
+ String token = tokens.get(i);
+ String option = unquoteToken(token);
+ int separator = option.indexOf('=');
+ String optionName = separator < 0 ? option : option.substring(0,
separator);
+ if (CLUSTER_CONNECTION_OPTIONS.contains(optionName)) {
+ options.add(token);
+ // the value may be given as a separate argument, for example
"-m <jobmanager>"
+ if (separator < 0 && i + 1 < tokens.size()) {
+ options.add(tokens.get(++i));
+ }
+ } else if (isClusterConnectionConfig(option)) {
+ options.add(token);
+ } else if (DYNAMIC_PROPERTY_OPTION.equals(option) && i + 1 <
tokens.size()) {
+ // the configuration may also be given as a separate argument,
"-D <key>=<value>"
+ String value = tokens.get(++i);
+ if (isClusterConnectionConfig(DYNAMIC_PROPERTY_OPTION +
unquoteToken(value))) {
+ options.add(token);
+ options.add(value);
+ }
+ }
+ }
+ return options;
+ }
+
+ /**
+ * Remove the quotes which surround a whole token, so that an option or a
value which is entirely
+ * quoted is still recognized. The original token is kept in the generated
command, the shell
+ * removes the quotes.
+ */
+ private static String unquoteToken(String token) {
+ if (token.length() > 1 && (token.charAt(0) == '"' || token.charAt(0)
== '\'')
+ && token.charAt(token.length() - 1) == token.charAt(0)) {
+ return token.substring(1, token.length() - 1);
+ }
+ return token;
+ }
+
+ /**
+ * Split the extra options of the submission into tokens. A whitespace
inside a quoted segment
+ * does not separate two tokens, and the quotes are kept so that the
generated command stays
+ * quoted for the shell. A quote may appear inside a token, for example
+ * {@code -Dkubernetes.config.file="/opt/flink configs/kube.yaml"}.
+ */
+ private static List<String> tokenizeOptions(String others) {
+ List<String> tokens = new ArrayList<>();
+ StringBuilder token = new StringBuilder();
+ char quote = 0;
+ boolean escaped = false;
+ for (int i = 0; i < others.length(); i++) {
+ char current = others.charAt(i);
+ if (escaped) {
+ token.append(current);
+ escaped = false;
+ } else if (current == '\\') {
+ token.append(current);
+ escaped = true;
+ } else if (quote != 0) {
+ token.append(current);
+ if (current == quote) {
+ quote = 0;
+ }
+ } else if (current == '"' || current == '\'') {
+ token.append(current);
+ quote = current;
+ } else if (Character.isWhitespace(current)) {
+ if (token.length() > 0) {
+ tokens.add(token.toString());
+ token.setLength(0);
+ }
+ } else {
+ token.append(current);
+ }
+ }
+ if (token.length() > 0) {
+ tokens.add(token.toString());
+ }
+ return tokens;
+ }
+
+ private static boolean isClusterConnectionConfig(String token) {
+ if (!token.startsWith(DYNAMIC_PROPERTY_OPTION) || token.length() <=
DYNAMIC_PROPERTY_OPTION.length()) {
+ return false;
+ }
+ String config = token.substring(DYNAMIC_PROPERTY_OPTION.length());
+ int separator = config.indexOf('=');
+ String key = separator < 0 ? config : config.substring(0, separator);
+ return CLUSTER_CONNECTION_CONFIG_KEYS.contains(key);
+ }
+
/**
* build flink savepoint command line, the savepoint folder should be set
in flink conf
- * @return
+ *
+ * <p>The Flink JobID identifies the job, the YARN application id only
identifies the cluster
+ * which runs it, so they are passed as different arguments. The YARN
application id is passed
+ * as the {@code -yid} targeting option, as documented by "Trigger a
Savepoint with YARN":
+ * {@code flink savepoint :jobId [:targetDirectory] -yid :yarnAppId}. The
cluster connection
+ * options of the submission are repeated as well, otherwise the savepoint
is triggered against
+ * the default cluster of the worker instead of the cluster which runs the
job.
+ *
+ * @param jobId the Flink JobID printed by `flink run`, it is not the
YARN/K8s application id
+ * @param yarnApplicationId the YARN application id used to target the
cluster, may be null
+ * @param clusterConnectionOptions the cluster connection options of the
submission, may be empty
+ * @return argument list
*/
- public static List<String> buildSavePointCommandLine(TaskExecutionContext
taskExecutionContext) {
+ public static List<String> buildSavePointCommandLine(String jobId, String
yarnApplicationId,
+ List<String>
clusterConnectionOptions) {
List<String> args = new ArrayList<>();
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_SAVEPOINT);
- args.add(taskExecutionContext.getAppIds());
+ args.add(jobId);
+ if (StringUtils.isNotBlank(yarnApplicationId)) {
+ args.add(FlinkConstants.FLINK_YARN_APPLICATION_ID);
+ args.add(yarnApplicationId);
+ }
+ if (CollectionUtils.isNotEmpty(clusterConnectionOptions)) {
+ args.addAll(clusterConnectionOptions);
+ }
return args;
}
+ /**
+ * Execute a flink command in the same environment as the task itself.
+ *
+ * <p>The task script is executed by a shell interceptor which sources
shell.env_source_list and the
+ * task's custom environment, resolves the task parameters and runs as the
task's tenant. The
+ * cancel / savepoint commands must reuse that environment, otherwise
placeholders like
+ * ${FLINK_HOME} cannot be resolved when they are only defined in the
selected task environment.
+ *
+ * @param taskExecutionContext task execution context
+ * @param args the command arguments
+ * @return true if the command finished successfully
+ */
+ public static boolean executeCommand(TaskExecutionContext
taskExecutionContext, List<String> args) {
+ return executeCommand(taskExecutionContext, args,
OSUtils.isSudoEnable(),
+ FlinkConstants.FLINK_COMMAND_TIMEOUT_SECONDS);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List)}, with a
custom timeout. The
+ * savepoint command uses a much longer timeout than the cancel command.
+ */
+ public static boolean executeCommand(TaskExecutionContext
taskExecutionContext, List<String> args,
+ int timeoutSeconds) {
+ return executeCommand(taskExecutionContext, args,
OSUtils.isSudoEnable(), timeoutSeconds);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List)}, with the
sudo mode injected so that
+ * the command execution can be verified without requiring sudo
permissions.
+ */
+ static boolean executeCommand(TaskExecutionContext taskExecutionContext,
List<String> args, boolean sudoEnable) {
+ return executeCommand(taskExecutionContext, args, sudoEnable,
FlinkConstants.FLINK_COMMAND_TIMEOUT_SECONDS);
+ }
+
+ /**
+ * Same as {@link #executeCommand(TaskExecutionContext, List, int)}, with
the sudo mode injected so
+ * that the command execution can be verified without requiring sudo
permissions.
+ */
+ static boolean executeCommand(TaskExecutionContext taskExecutionContext,
List<String> args, boolean sudoEnable,
+ int timeoutSeconds) {
+ Process process = null;
+ try {
+ IShellInterceptorBuilder shellInterceptorBuilder =
ShellInterceptorBuilderFactory.newBuilder()
+ .shellDirectory(taskExecutionContext.getExecutePath())
+ .shellName(taskExecutionContext.getTaskInstanceId() +
FLINK_COMMAND_SHELL_NAME_SUFFIX
+ + System.nanoTime())
+
.properties(ParameterUtils.convert(taskExecutionContext.getPrepareParamsMap()))
+ .appendScript(String.join(" ", args))
+ .sudoMode(sudoEnable)
+ .runUser(taskExecutionContext.getTenantCode());
+ if (CollectionUtils.isNotEmpty(ShellUtils.ENV_SOURCE_LIST)) {
+
ShellUtils.ENV_SOURCE_LIST.forEach(shellInterceptorBuilder::appendSystemEnv);
+ }
+ if
(StringUtils.isNotBlank(taskExecutionContext.getEnvironmentConfig())) {
+
shellInterceptorBuilder.appendCustomEnvScript(taskExecutionContext.getEnvironmentConfig());
+ }
+ process = shellInterceptorBuilder.build().execute();
+ return waitForCommand(process, args, taskExecutionContext,
timeoutSeconds);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ log.error("Execute flink command interrupted, args: {}", args, e);
+ return false;
+ } catch (Exception e) {
+ log.error("Execute flink command error, args: {}", args, e);
+ return false;
+ } finally {
+ if (process != null && process.isAlive()) {
+ destroyProcessTree(process, taskExecutionContext);
+ }
+ }
+ }
+
+ /**
+ * Wait for the command to finish, consuming its output so that the
command cannot block on a full
+ * pipe, and keep the output for diagnostics.
+ */
+ private static boolean waitForCommand(Process process, List<String> args,
+ TaskExecutionContext
taskExecutionContext,
+ int timeoutSeconds) throws
InterruptedException {
+ StringBuilder output = new StringBuilder();
+ Thread outputReader = new Thread(() -> {
+ try (BufferedReader reader = new BufferedReader(new
InputStreamReader(process.getInputStream()))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ output.append(line).append(System.lineSeparator());
+ }
+ } catch (IOException e) {
+ // the process has exited and its streams are closed
+ }
+ }, "flink-command-output-reader");
+ outputReader.setDaemon(true);
+ outputReader.start();
+
+ boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
+ // both streams are merged into stdout by the shell interceptor, so
joining the reader is enough
+
outputReader.join(TimeUnit.SECONDS.toMillis(OUTPUT_READER_JOIN_TIMEOUT_SECONDS));
+ if (!finished) {
+ destroyProcessTree(process, taskExecutionContext);
+ log.error("Execute flink command timeout after {}s, args: {},
output: {}", timeoutSeconds, args, output);
+ return false;
+ }
+ int exitCode = process.exitValue();
+ if (exitCode != 0) {
+ log.error("Execute flink command failed, exitCode: {}, args: {},
output: {}", exitCode, args, output);
+ return false;
+ }
+ log.info("Execute flink command successfully, args: {}, output: {}",
args, output);
Review Comment:
## CodeQL / Insertion of sensitive information into log files
This [potentially sensitive information](1) is written to a log file.
This [potentially sensitive information](2) is written to a log file.
This [potentially sensitive information](3) is written to a log file.
This [potentially sensitive information](4) is written to a log file.
This [potentially sensitive information](5) is written to a log file.
[Show more
details](https://github.com/apache/dolphinscheduler/security/code-scanning/5875)
--
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]