dill21yu commented on code in PR #17779: URL: https://github.com/apache/dolphinscheduler/pull/17779#discussion_r2730085549
########## dolphinscheduler-task-plugin/dolphinscheduler-task-external-system/src/main/java/org/apache/dolphinscheduler/plugin/task/externalSystem/ExternalSystemTask.java: ########## @@ -0,0 +1,514 @@ +/* + * 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.dolphinscheduler.plugin.task.externalSystem; + +import org.apache.dolphinscheduler.common.model.OkHttpRequestHeaderContentType; +import org.apache.dolphinscheduler.common.model.OkHttpRequestHeaders; +import org.apache.dolphinscheduler.common.model.OkHttpResponse; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.common.utils.OkHttpUtils; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.AuthenticationUtils; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.InterfaceInfo; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.PollingFailureConfig; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.PollingInterfaceInfo; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.PollingSuccessConfig; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.RequestParameter; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.ResponseParameter; +import org.apache.dolphinscheduler.plugin.datasource.thirdpartysystemconnector.param.ThirdPartySystemConnectorConnectionParam; +import org.apache.dolphinscheduler.plugin.task.api.AbstractTask; +import org.apache.dolphinscheduler.plugin.task.api.TaskCallBack; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.TaskTimeoutStrategy; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters; +import org.apache.dolphinscheduler.plugin.task.api.utils.ParameterUtils; + +import org.apache.commons.lang3.StringUtils; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import lombok.extern.slf4j.Slf4j; +import okhttp3.FormBody; + +import com.jayway.jsonpath.JsonPath; + +@Slf4j +public class ExternalSystemTask extends AbstractTask { + + private Boolean traceEnabled = true; + + private ExternalSystemParameters externalSystemParameters; + private ThirdPartySystemConnectorConnectionParam baseExternalSystemParams; + private TaskExecutionContext taskExecutionContext; + private String accessToken; + private Map<String, String> parameterMap = new HashMap<>(); + private Set<String> successStatusCache = new HashSet<>(); + private Set<String> failureStatusCache = new HashSet<>(); + + private boolean isTimeout = false; + private long taskStartTime; + + public ExternalSystemTask(TaskExecutionContext taskExecutionContext) { + super(taskExecutionContext); + this.taskExecutionContext = taskExecutionContext; + this.externalSystemParameters = + JSONUtils.parseObject(taskExecutionContext.getTaskParams(), ExternalSystemParameters.class); + baseExternalSystemParams = + externalSystemParameters.generateExtendedContext(taskExecutionContext.getResourceParametersHelper()); + try { + accessToken = baseExternalSystemParams.getAuthConfig().getHeaderPrefix() + " " + + AuthenticationUtils.authenticateAndGetToken(baseExternalSystemParams); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void init() { + externalSystemParameters = JSONUtils.parseObject( + taskExecutionContext.getTaskParams(), + ExternalSystemParameters.class); + + if (externalSystemParameters == null || !externalSystemParameters.checkParameters()) { + throw new RuntimeException("external system task params is not valid"); + } + + log.info("Initialize external system task with externalSystemId: {}, externalTaskId: {}, externalTaskName: {}", + externalSystemParameters.getDatasource(), + externalSystemParameters.getExternalTaskId(), + externalSystemParameters.getExternalTaskName()); + + // Initialize parameter mapping + initParameterMap(); + initStatusCache(); + } + + @Override + public void handle(TaskCallBack taskCallBack) throws TaskException { + try { + taskStartTime = System.currentTimeMillis(); + submitExternalTask(); + TimeUnit.SECONDS.sleep(10); + trackExternalTaskStatus(); + } catch (Exception e) { + log.error("external system task error", e); + setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE); + throw new TaskException("Execute external system task failed", e); + } + } + + @Override + public void cancel() throws TaskException { + try { + log.info("cancel external system task"); + cancelTaskInstance(); + } catch (Exception e) { + throw new TaskException("cancel external system task error", e); + } finally { + // Only set to failure status when timeout failure strategy is enabled and it actually timed out + log.info("External task timeout check isTimeoutFailureEnabled:{}", isTimeoutFailureEnabled()); + if (isTimeoutFailureEnabled()) { + long currentTime = System.currentTimeMillis(); + long usedTimeMillis = currentTime - taskStartTime; + long usedTime = (usedTimeMillis + 59999) / 60000; // Round up to minutes (ceiling division) + log.info( + "External task timeout check, used time: {}m, timeout: {}m, currentTime: {}, taskStartTime: {}", + usedTime, taskExecutionContext.getTaskTimeout() / 60, currentTime, taskStartTime); + if (usedTime >= taskExecutionContext.getTaskTimeout() / 60) { + isTimeout = true; + log.warn("External task timeout, used time: {}m, timeout: {}m", + usedTime, taskExecutionContext.getTaskTimeout() / 60); + } + } + if (isTimeout) { + setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE); + log.info("External task cancelled due to timeout, set status to FAILED"); + } else { + setExitStatusCode(TaskConstants.EXIT_CODE_KILL); + log.info("External task cancelled manually or timeout not enabled, set status to KILLED"); + } + } + } + + private void submitExternalTask() throws TaskException { + try { + InterfaceInfo submitConfig = baseExternalSystemParams.getSubmitInterface(); + String url = replaceParameterPlaceholders(baseExternalSystemParams.getCompleteUrl(submitConfig.getUrl())); + Map<String, String> headers = new HashMap<>(); + buildAuthHeader(accessToken, headers); + buildHeaders(submitConfig, headers); + Map<String, Object> requestBody = buildRequestBody(submitConfig); + Map<String, Object> requestParams = buildRequestParams(submitConfig); + + int interfaceTimeout = baseExternalSystemParams.getInterfaceTimeout(); + log.info("Using interface timeout value: {} milliseconds", interfaceTimeout); + OkHttpResponse response = + executeRequestWithoutRetry(submitConfig.getMethod(), url, headers, requestParams, requestBody, + interfaceTimeout, interfaceTimeout, interfaceTimeout); + log.info("Submit task response:{}", response); + if (response.getStatusCode() != 200) { + throw new TaskException("Submit task failed: " + response.getBody()); + } + + parseSubmitResponse(submitConfig.getResponseParameters(), response.getBody()); + } catch (Exception e) { + log.error("Submit task failed:{}", e); + throw new TaskException("Submit task failed", e); + } + } + + private void trackExternalTaskStatus() throws TaskException { + try { + String status; + do { + // Only check timeout when timeout failure strategy is enabled + if (isTimeoutFailureEnabled()) { + long currentTime = System.currentTimeMillis(); + long usedTimeMillis = currentTime - taskStartTime; + long usedTime = (usedTimeMillis + 59999) / 60000; // Round up to minutes (ceiling division) + if (usedTime >= taskExecutionContext.getTaskTimeout()) { + isTimeout = true; + log.error("External task timeout, used time: {}m, timeout: {}m", + usedTime, taskExecutionContext.getTaskTimeout() / 60); + setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE); + cancelTaskInstance(); + return; + } + } + + status = pollTaskStatus(); + + if (successStatusCache.contains(status)) { + setExitStatusCode(TaskConstants.EXIT_CODE_SUCCESS); + log.info("External task completed successfully with status: {}", status); + return; + } else if (failureStatusCache.contains(status)) { + setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE); + log.error("External task failed with status: {}", status); + return; + } + + TimeUnit.SECONDS.sleep(10); + } while (traceEnabled); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TaskException("Task status tracking interrupted", e); + } catch (Exception e) { + log.error("Track task status failed", e); + setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE); + throw new TaskException("Track task status failed", e); + } + } + + private String pollTaskStatus() throws TaskException { + try { + PollingInterfaceInfo pollConfig = + baseExternalSystemParams.getPollStatusInterface(); + String url = replaceParameterPlaceholders(baseExternalSystemParams.getCompleteUrl(pollConfig.getUrl())); + Map<String, String> headers = new HashMap<>(); + buildAuthHeader(accessToken, headers); + buildHeaders(pollConfig, headers); + Map<String, Object> requestBody = buildRequestBody(pollConfig); + Map<String, Object> requestParams = buildRequestParams(pollConfig); + + int interfaceTimeout = baseExternalSystemParams.getInterfaceTimeout(); + OkHttpResponse response = + executeRequestWithRetry(pollConfig.getMethod(), url, headers, requestParams, requestBody, + interfaceTimeout, interfaceTimeout, interfaceTimeout, 3); + log.info("poll task status response:{}", response); + + if (response.getStatusCode() != 200) { + throw new TaskException("polling task failed: " + response.getBody()); + } + + String successField = pollConfig.getPollingSuccessConfig().getSuccessField(); + String failureField = pollConfig.getPollingFailureConfig().getFailureField(); + + Object successStatusObj = JsonPath.read(response.getBody(), successField); + Object failureStatusObj = JsonPath.read(response.getBody(), failureField); + + log.info("PollTaskStatus successfully, external task instance success status: {}, failure status: {}", + successStatusObj.toString(), failureStatusObj.toString()); Review Comment: done -- 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]
