TaskExecuteThread.java 9.4 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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.
 */
Q
qiaozhanwei 已提交
17
package org.apache.dolphinscheduler.server.worker.runner;
L
ligang 已提交
18 19


20
import com.alibaba.fastjson.JSONObject;
Q
qiaozhanwei 已提交
21 22 23 24 25
import org.apache.dolphinscheduler.common.enums.ExecutionStatus;
import org.apache.dolphinscheduler.common.model.TaskNode;
import org.apache.dolphinscheduler.common.process.Property;
import org.apache.dolphinscheduler.common.task.AbstractParameters;
import org.apache.dolphinscheduler.common.task.TaskTimeoutParameter;
26
import org.apache.dolphinscheduler.common.utils.*;
T
Tboy 已提交
27
import org.apache.dolphinscheduler.remote.command.ExecuteTaskResponseCommand;
Q
qiaozhanwei 已提交
28
import org.apache.dolphinscheduler.server.entity.TaskExecutionContext;
Q
qiaozhanwei 已提交
29
import org.apache.dolphinscheduler.server.worker.processor.TaskCallbackService;
Q
qiaozhanwei 已提交
30 31
import org.apache.dolphinscheduler.server.worker.task.AbstractTask;
import org.apache.dolphinscheduler.server.worker.task.TaskManager;
L
ligang 已提交
32 33 34 35 36 37 38 39 40 41 42
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;


/**
 *  task scheduler thread
 */
T
Tboy 已提交
43
public class TaskExecuteThread implements Runnable {
L
ligang 已提交
44 45 46 47

    /**
     * logger
     */
T
Tboy 已提交
48
    private final Logger logger = LoggerFactory.getLogger(TaskExecuteThread.class);
L
ligang 已提交
49 50 51 52

    /**
     *  task instance
     */
T
Tboy 已提交
53
    private TaskExecutionContext taskExecutionContext;
L
ligang 已提交
54 55

    /**
journey2018's avatar
journey2018 已提交
56
     *  abstract task
L
ligang 已提交
57 58 59
     */
    private AbstractTask task;

T
Tboy 已提交
60
    /**
T
Tboy 已提交
61
     *  task callback service
T
Tboy 已提交
62
     */
T
Tboy 已提交
63
    private TaskCallbackService taskCallbackService;
T
Tboy 已提交
64

65
    /**
66
     *  constructor
T
Tboy 已提交
67
     * @param taskExecutionContext taskExecutionContext
T
Tboy 已提交
68
     * @param taskCallbackService taskCallbackService
69
     */
70
    public TaskExecuteThread(TaskExecutionContext taskExecutionContext, TaskCallbackService taskCallbackService){
T
Tboy 已提交
71
        this.taskExecutionContext = taskExecutionContext;
T
Tboy 已提交
72
        this.taskCallbackService = taskCallbackService;
L
ligang 已提交
73 74 75
    }

    @Override
journey2018's avatar
journey2018 已提交
76
    public void run() {
L
ligang 已提交
77

T
Tboy 已提交
78
        ExecuteTaskResponseCommand responseCommand = new ExecuteTaskResponseCommand(taskExecutionContext.getTaskInstanceId());
L
ligang 已提交
79
        try {
T
Tboy 已提交
80
            logger.info("script path : {}", taskExecutionContext.getExecutePath());
journey2018's avatar
journey2018 已提交
81
            // task node
T
Tboy 已提交
82
            TaskNode taskNode = JSONObject.parseObject(taskExecutionContext.getTaskJson(), TaskNode.class);
L
ligang 已提交
83

84 85
            // get resource files
            List<String> resourceFiles = createProjectResFiles(taskNode);
journey2018's avatar
journey2018 已提交
86
            // copy hdfs/minio file to local
87
            downloadResource(taskExecutionContext.getExecutePath(),
88
                    resourceFiles,
89
                    taskExecutionContext.getTenantCode(),
L
ligang 已提交
90 91
                    logger);

92 93 94 95
            taskExecutionContext.setTaskParams(taskNode.getParams());
            taskExecutionContext.setEnvFile(CommonUtils.getSystemEnvPath());
            taskExecutionContext.setDefinedParams(getGlobalParamsMap());

96
            // set task timeout
97
            setTaskTimeout(taskExecutionContext, taskNode);
98

99
            taskExecutionContext.setTaskAppId(String.format("%s_%s_%s",
T
Tboy 已提交
100 101
                    taskExecutionContext.getProcessDefineId(),
                    taskExecutionContext.getProcessInstanceId(),
T
Tboy 已提交
102
                    taskExecutionContext.getTaskInstanceId()));
103 104 105

            // custom logger
            Logger taskLogger = LoggerFactory.getLogger(LoggerUtils.buildTaskId(LoggerUtils.TASK_LOGGER_INFO_PREFIX,
T
Tboy 已提交
106 107
                    taskExecutionContext.getProcessDefineId(),
                    taskExecutionContext.getProcessInstanceId(),
T
Tboy 已提交
108
                    taskExecutionContext.getTaskInstanceId()));
109

110 111 112


            task = TaskManager.newTask(taskExecutionContext,
113 114 115 116 117 118 119 120 121 122 123
                    taskLogger);

            // task init
            task.init();

            // task handle
            task.handle();

            // task result process
            task.after();

T
Tboy 已提交
124 125
            responseCommand.setStatus(task.getExitStatus().getCode());
            responseCommand.setEndTime(new Date());
126 127
            responseCommand.setProcessId(task.getProcessId());
            responseCommand.setAppIds(task.getAppIds());
T
Tboy 已提交
128
            logger.info("task instance id : {},task final status : {}", taskExecutionContext.getTaskInstanceId(), task.getExitStatus());
L
ligang 已提交
129
        }catch (Exception e){
journey2018's avatar
journey2018 已提交
130
            logger.error("task scheduler failure", e);
L
ligang 已提交
131
            kill();
T
Tboy 已提交
132 133
            responseCommand.setStatus(ExecutionStatus.FAILURE.getCode());
            responseCommand.setEndTime(new Date());
134 135
            responseCommand.setProcessId(task.getProcessId());
            responseCommand.setAppIds(task.getAppIds());
T
Tboy 已提交
136
        } finally {
T
Tboy 已提交
137
            taskCallbackService.sendResult(taskExecutionContext.getTaskInstanceId(), responseCommand);
L
ligang 已提交
138 139 140 141
        }
    }

    /**
journey2018's avatar
journey2018 已提交
142 143 144 145 146 147 148
     * get global paras map
     * @return
     */
    private Map<String, String> getGlobalParamsMap() {
        Map<String,String> globalParamsMap = new HashMap<>(16);

        // global params string
T
Tboy 已提交
149
        String globalParamsStr = taskExecutionContext.getGlobalParams();
journey2018's avatar
journey2018 已提交
150 151 152 153 154 155
        if (globalParamsStr != null) {
            List<Property> globalParamsList = JSONObject.parseArray(globalParamsStr, Property.class);
            globalParamsMap.putAll(globalParamsList.stream().collect(Collectors.toMap(Property::getProp, Property::getValue)));
        }
        return globalParamsMap;
    }
156

journey2018's avatar
journey2018 已提交
157 158
    /**
     * set task timeout
159
     * @param taskExecutionContext TaskExecutionContext
L
ligang 已提交
160 161
     * @param taskNode
     */
162
    private void setTaskTimeout(TaskExecutionContext taskExecutionContext, TaskNode taskNode) {
journey2018's avatar
journey2018 已提交
163
        // the default timeout is the maximum value of the integer
164
        taskExecutionContext.setTaskTimeout(Integer.MAX_VALUE);
L
ligang 已提交
165 166
        TaskTimeoutParameter taskTimeoutParameter = taskNode.getTaskTimeoutParameter();
        if (taskTimeoutParameter.getEnable()){
journey2018's avatar
journey2018 已提交
167
            // get timeout strategy
168
            taskExecutionContext.setTaskTimeoutStrategy(taskTimeoutParameter.getStrategy().getCode());
L
ligang 已提交
169 170 171 172 173
            switch (taskTimeoutParameter.getStrategy()){
                case WARN:
                    break;
                case FAILED:
                    if (Integer.MAX_VALUE > taskTimeoutParameter.getInterval() * 60) {
174
                        taskExecutionContext.setTaskTimeout(taskTimeoutParameter.getInterval() * 60);
L
ligang 已提交
175 176 177 178
                    }
                    break;
                case WARNFAILED:
                    if (Integer.MAX_VALUE > taskTimeoutParameter.getInterval() * 60) {
179
                        taskExecutionContext.setTaskTimeout(taskTimeoutParameter.getInterval() * 60);
L
ligang 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
                    }
                    break;
                default:
                    logger.error("not support task timeout strategy: {}", taskTimeoutParameter.getStrategy());
                    throw new IllegalArgumentException("not support task timeout strategy");

            }
        }
    }


    /**
     *  kill task
     */
    public void kill(){
        if (task != null){
            try {
                task.cancelApplication(true);
            }catch (Exception e){
                logger.error(e.getMessage(),e);
            }
        }
    }


    /**
     *  create project resource files
     */
    private List<String> createProjectResFiles(TaskNode taskNode) throws Exception{

        Set<String> projectFiles = new HashSet<>();
        AbstractParameters baseParam = TaskParametersUtils.getParameters(taskNode.getType(), taskNode.getParams());

        if (baseParam != null) {
            List<String> projectResourceFiles = baseParam.getResourceFilesList();
            if (projectResourceFiles != null) {
                projectFiles.addAll(projectResourceFiles);
            }
        }

        return new ArrayList<>(projectFiles);
    }

    /**
224
     * download resource file
L
ligang 已提交
225 226 227 228 229
     *
     * @param execLocalPath
     * @param projectRes
     * @param logger
     */
230 231 232 233 234 235
    private void downloadResource(String execLocalPath,
                                  List<String> projectRes,
                                  String tenantCode,
                                  Logger logger) throws Exception {
        for (String resource : projectRes) {
            File resFile = new File(execLocalPath, resource);
L
ligang 已提交
236 237
            if (!resFile.exists()) {
                try {
journey2018's avatar
journey2018 已提交
238
                    // query the tenant code of the resource according to the name of the resource
239
                    String resHdfsPath = HadoopUtils.getHdfsFilename(tenantCode, resource);
L
ligang 已提交
240 241

                    logger.info("get resource file from hdfs :{}", resHdfsPath);
242
                    HadoopUtils.getInstance().copyHdfsToLocal(resHdfsPath, execLocalPath + File.separator + resource, false, true);
L
ligang 已提交
243 244 245 246 247 248 249 250 251 252
                }catch (Exception e){
                    logger.error(e.getMessage(),e);
                    throw new RuntimeException(e.getMessage());
                }
            } else {
                logger.info("file : {} exists ", resFile.getName());
            }
        }
    }
}