AbstractCommandExecutor.java 15.2 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 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
/*
 * 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 cn.escheduler.server.worker.task;

import cn.escheduler.common.Constants;
import cn.escheduler.common.enums.ExecutionStatus;
import cn.escheduler.common.thread.ThreadUtils;
import cn.escheduler.common.utils.HadoopUtils;
import cn.escheduler.dao.ProcessDao;
import cn.escheduler.dao.model.TaskInstance;
import cn.escheduler.server.utils.ProcessUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * abstract command executor
 */
public abstract class AbstractCommandExecutor {
    /**
     * rules for extracting application ID
     */
    protected static final Pattern APPLICATION_REGEX = Pattern.compile(Constants.APPLICATION_REGEX);

    /**
     *  process
     */
    private Process process;

    /**
     *  log handler
     */
    protected Consumer<List<String>> logHandler;

    /**
     *  task dir
     */
    protected final String taskDir;

    /**
     *  task appId
     */
    protected final String taskAppId;

    /**
     *  tenant code , execute task linux user
     */
    protected final String tenantCode;

    /**
     *  env file
     */
    protected final String envFile;

    /**
     *  start time
     */
    protected final Date startTime;

    /**
     *  timeout
     */
    protected int timeout;

    /**
     *  logger
     */
    protected Logger logger;

    /**
     *  log list
     */
    protected final List<String> logBuffer;


    public AbstractCommandExecutor(Consumer<List<String>> logHandler,
                                   String taskDir, String taskAppId, String tenantCode, String envFile,
                                   Date startTime, int timeout, Logger logger){
        this.logHandler = logHandler;
        this.taskDir = taskDir;
        this.taskAppId = taskAppId;
        this.tenantCode = tenantCode;
        this.envFile = envFile;
        this.startTime = startTime;
        this.timeout = timeout;
        this.logger = logger;
        this.logBuffer = Collections.synchronizedList(new ArrayList<>());
    }

    /**
     * task specific execution logic
     *
     * @param execCommand
     * @param processDao
     * @return
     */
    public int run(String execCommand, ProcessDao processDao) {
        int exitStatusCode;

        try {
            if (StringUtils.isEmpty(execCommand)) {
                exitStatusCode = 0;
                return exitStatusCode;
            }

            String commandFilePath = buildCommandFilePath();

            // create command file if not exists
            createCommandFileIfNotExists(execCommand, commandFilePath);

            //build process
            buildProcess(commandFilePath);

            // parse process output
            parseProcessOutput(process);

            // get process id
            int pid = getProcessId(process);

            // task instance id
            int taskInstId = Integer.parseInt(taskAppId.split("_")[2]);

            processDao.updatePidByTaskInstId(taskInstId, pid);

            logger.info("process start, process id is: {}", pid);

            // if timeout occurs, exit directly
            long remainTime = getRemaintime();

            // waiting for the run to finish
            boolean status = process.waitFor(remainTime, TimeUnit.SECONDS);

            if (status) {
                exitStatusCode = process.exitValue();
                logger.info("process has exited, work dir:{}, pid:{} ,exitStatusCode:{}", taskDir, pid,exitStatusCode);
                //update process state to db
                exitStatusCode = updateState(processDao, exitStatusCode, pid, taskInstId);

            } else {
                cancelApplication();
                exitStatusCode = -1;
                logger.warn("process timeout, work dir:{}, pid:{}", taskDir, pid);
            }

        } catch (InterruptedException e) {
            exitStatusCode = -1;
            logger.error(String.format("interrupt exception: {}, task may be cancelled or killed",e.getMessage()), e);
            throw new RuntimeException("interrupt exception. exitCode is :  " + exitStatusCode);
        } catch (Exception e) {
            exitStatusCode = -1;
            logger.error(e.getMessage(), e);
            throw new RuntimeException("process error . exitCode is :  " + exitStatusCode);
        }

        return exitStatusCode;
    }

    /**
     * build process
     *
     * @param commandFile
     * @throws IOException
     */
    private void buildProcess(String commandFile) throws IOException {
        //init process builder
        ProcessBuilder processBuilder = new ProcessBuilder();
        // setting up a working directory
        processBuilder.directory(new File(taskDir));
        // merge error information to standard output stream
        processBuilder.redirectErrorStream(true);
        // setting up user to run commands
        processBuilder.command("sudo", "-u", tenantCode, commandType(), commandFile);

        process = processBuilder.start();

        // print command
        printCommand(processBuilder);
    }

    /**
     * update process state to db
     *
     * @param processDao
     * @param exitStatusCode
     * @param pid
     * @param taskInstId
     * @return
     */
    private int updateState(ProcessDao processDao, int exitStatusCode, int pid, int taskInstId) {
        //get yarn state by log
216
        if (exitStatusCode != 0) {
L
ligang 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
            TaskInstance taskInstance = processDao.findTaskInstanceById(taskInstId);
            logger.info("process id is {}", pid);

            List<String> appIds = getAppLinks(taskInstance.getLogPath());
            if (appIds.size() > 0) {
                String appUrl = String.join(Constants.COMMA, appIds);
                logger.info("yarn log url:{}",appUrl);
                processDao.updatePidByTaskInstId(taskInstId, pid, appUrl);
            }

            // check if all operations are completed
            if (!isSuccessOfYarnState(appIds)) {
                exitStatusCode = -1;
            }
        }
        return exitStatusCode;
    }


    /**
     *  cancel python task
     */
    public void cancelApplication() throws Exception {
        if (process == null) {
            return;
        }

        // clear log
        clear();

        int processId = getProcessId(process);

        logger.info("cancel process: {}", processId);

        // kill , waiting for completion
        boolean killed = softKill(processId);

        if (!killed) {
            // hard kill
            hardKill(processId);

            // destory
            process.destroy();

            process = null;
        }
    }

    /**
     *  soft kill
     * @param processId
     * @return
     * @throws InterruptedException
     */
    private boolean softKill(int processId) {

        if (processId != 0 && process.isAlive()) {
            try {
                // sudo -u user command to run command
                String cmd = String.format("sudo kill %d", processId);

                logger.info("soft kill task:{}, process id:{}, cmd:{}", taskAppId, processId, cmd);

                Runtime.getRuntime().exec(cmd);
            } catch (IOException e) {
                logger.info("kill attempt failed." + e.getMessage(), e);
            }
        }

        return process.isAlive();
    }

    /**
     *  hard kill
     * @param processId
     */
    private void hardKill(int processId) {
        if (processId != 0 && process.isAlive()) {
            try {
                String cmd = String.format("sudo kill -9 %d", processId);

                logger.info("hard kill task:{}, process id:{}, cmd:{}", taskAppId, processId, cmd);

                Runtime.getRuntime().exec(cmd);
            } catch (IOException e) {
                logger.error("kill attempt failed." + e.getMessage(), e);
            }
        }
    }

    /**
     *  print command
     * @param processBuilder
     */
    private void printCommand(ProcessBuilder processBuilder) {
        String cmdStr;

        try {
            cmdStr = ProcessUtils.buildCommandStr(processBuilder.command());
            logger.info("task run command:\n{}", cmdStr);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     *  clear
     */
    private void clear() {
        if (!logBuffer.isEmpty()) {
            // log handle
            logHandler.accept(logBuffer);

            logBuffer.clear();
        }
    }

    /**
     * get the standard output of the process
     */
    private void parseProcessOutput(Process process) {
        String threadLoggerInfoName = String.format("TaskLogInfo-%s", taskAppId);
        ThreadUtils.newDaemonSingleThreadExecutor(threadLoggerInfoName).submit(new Runnable(){
            @Override
            public void run() {
                BufferedReader inReader = null;

                try {
                    inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;

                    long lastFlushTime = System.currentTimeMillis();

                    while ((line = inReader.readLine()) != null) {
                        if(checkShowLog(line)){
                            logBuffer.add(line);
                        }

                        lastFlushTime = flush(lastFlushTime);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                } finally {
                    clear();
                    close(inReader);
                }
            }
        });

    }

    public int getPid() {
        return getProcessId(process);
    }

    /**
     * check yarn state
     *
     * @param appIds
     * @return
     */
    public boolean isSuccessOfYarnState(List<String> appIds) {

        boolean result = true;
        try {
            for (String appId : appIds) {
                ExecutionStatus applicationStatus = HadoopUtils.getInstance().getApplicationStatus(appId);
                logger.info("appId:{}, final state:{}",appId,applicationStatus.name());
                if (!applicationStatus.equals(ExecutionStatus.SUCCESS)) {
                    result = false;
                }
            }
        } catch (Exception e) {
            logger.error(String.format("mapreduce applications: %s  status failed : " + e.getMessage(), appIds.toString()),e);
            result = false;
        }
        return result;

    }

    /**
     *  get app links
     * @param fileName
     * @return
     */
    private List<String> getAppLinks(String fileName) {
        List<String> logs = convertFile2List(fileName);

        List<String> appIds = new ArrayList<String>();
        /**
         * analysis log,get submited yarn application id
         */
        for (String log : logs) {

            String appId = findAppId(log);
            if (StringUtils.isNotEmpty(appId) && !appIds.contains(appId)) {
                logger.info("find app id: {}", appId);
                appIds.add(appId);
            }
        }
        return appIds;
    }

    /**
     *  convert file to list
     * @param filename
     * @return
     */
    private List<String> convertFile2List(String filename) {
        List lineList = new ArrayList<String>(100);
        File file=new File(filename);

        if (!file.exists()){
            return lineList;
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8));
            String line = null;
            while ((line = br.readLine()) != null) {
                lineList.add(line);
            }
        } catch (Exception e) {
            logger.error(String.format("read file: %s failed : ",filename),e);
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                }
            }

        }
        return lineList;
    }

    /**
     *  find app id
     *
     * @return appid
     */
    private String findAppId(String line) {
        Matcher matcher = APPLICATION_REGEX.matcher(line);

        if (matcher.find() && checkFindApp(line)) {
            return matcher.group();
        }

        return null;
    }


    /**
     * get remain time(s)
     *
     * @return
     */
    private long getRemaintime() {
        long usedTime = (System.currentTimeMillis() - startTime.getTime()) / 1000;
        long remainTime = timeout - usedTime;

        if (remainTime < 0) {
            throw new RuntimeException("task execution time out");
        }

        return remainTime;
    }

    /**
     * get process id
     *
     * @param process
     * @return
     */
    private int getProcessId(Process process) {
        int processId = 0;

        try {
            Field f = process.getClass().getDeclaredField(Constants.PID);
            f.setAccessible(true);

            processId = f.getInt(process);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }

        return processId;
    }

    /**
     * when log buffer siz or flush time reach condition , then flush
     *
     * @param lastFlushTime  last flush time
     * @return
     */
    private long flush(long lastFlushTime) {
        long now = System.currentTimeMillis();

        /**
         * when log buffer siz or flush time reach condition , then flush
         */
        if (logBuffer.size() >= Constants.defaultLogRowsNum  || now - lastFlushTime > Constants.defaultLogFlushInterval) {
            lastFlushTime = now;
            /** log handle */
            logHandler.accept(logBuffer);

            logBuffer.clear();
        }
        return lastFlushTime;
    }

    /**
     * close buffer reader
     *
     * @param inReader
     */
    private void close(BufferedReader inReader) {
        if (inReader != null) {
            try {
                inReader.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }


    protected abstract String buildCommandFilePath();
    protected abstract String commandType();
    protected abstract boolean checkShowLog(String line);
    protected abstract boolean checkFindApp(String line);
    protected abstract void createCommandFileIfNotExists(String execCommand, String commandFile) throws IOException;
}