Example usage for org.apache.commons.exec ExecuteException getMessage

List of usage examples for org.apache.commons.exec ExecuteException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.exec ExecuteException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.github.zeroxff.executor.ExtendedExecutor.java

public ExecuteResult execute() throws ExtendedExecuteException {
    this.clearOut();
    if (this.commandLine == null) {
        throw new ExtendedExecuteException("CommandLine cannot be null", Executor.INVALID_EXITVALUE);
    }//from   w  w  w .jav  a2 s. com
    if (this.commandLine.length == 0) {
        throw new ExtendedExecuteException("CommandLine cannot be empty", Executor.INVALID_EXITVALUE);
    }
    if (this.maxExecutiontime != ExecuteWatchdog.INFINITE_TIMEOUT && this.maxExecutiontime < 1) {
        throw new ExtendedExecuteException("Max execution time must not be less than 1",
                Executor.INVALID_EXITVALUE);
    }

    try {
        // load the command line as an array of strings
        CommandLine cmdLine = new CommandLine(this.commandLine[0]);
        for (int counter = 1; counter < commandLine.length; counter++) {
            cmdLine.addArgument(this.commandLine[counter], quoteCommandlineArgs);
        }

        // load the substitution map, if defined
        if (this.substitutionMap != null) {
            cmdLine.setSubstitutionMap(this.substitutionMap);
        }

        // load the watchdog timer, it can be set to infinite time
        ExecuteWatchdog watchdog = new ExecuteWatchdog(this.maxExecutiontime);
        ExtendedResultHandler resultHandler = new ExtendedResultHandler(watchdog);

        // inizialize outputstream processors.
        OutStreamProcessor outLinee = null;
        OutStreamProcessor errLinee = null;
        PumpStreamHandler streamHandler = null;
        if (outputFilter != null && outputFilter.size() > 0) {
            outLinee = new OutStreamProcessor(outputFilter);
        } else {
            outLinee = new OutStreamProcessor();
        }
        if (this.enableAllLinesOut) {
            outLinee.enableAllLines();
        }
        if (mergeOutStreams) {
            // Using Std out for the output/error stream
            streamHandler = new PumpStreamHandler(outLinee);
        } else {
            if (errorFilter != null && errorFilter.size() > 0) {
                errLinee = new OutStreamProcessor(errorFilter);
            } else {
                errLinee = new OutStreamProcessor();
            }
            if (enableAllLinesErr) {
                errLinee.enableAllLines();
            }
            // Using Std out for the output/error stream
            streamHandler = new PumpStreamHandler(outLinee, errLinee);
        }
        DefaultExecutor executor = new DefaultExecutor();
        // set the working directory...
        // if the working directory doesn't exists, it can crash the
        // executor.
        if (workingDirecory != null) {
            executor.setWorkingDirectory(workingDirecory);
        }

        // set the accepted exit values for the command line
        // default is '0'.
        if (okExitValues != null && okExitValues.length > 0) {
            executor.setExitValues(okExitValues);
        }

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        try {
            executor.execute(cmdLine, resultHandler);
            resultHandler.waitFor();
            returnCode = resultHandler.getExitValue();
            exitMode = resultHandler.getExitMode();
            switch (exitMode) {
            case ERROR_IN_EXECUTION:
                this.message = resultHandler.getException().getMessage();
                break;
            default:
                break;
            }
        } catch (ExecuteException e) {
            exitMode = ExecuteResult.EXCEPTION;
            exception = e;
            this.message = e.getMessage();
        } catch (IOException e) {
            exitMode = ExecuteResult.EXCEPTION;
            exception = e;
            this.message = e.getMessage();
        } catch (InterruptedException e) {
            exitMode = ExecuteResult.EXCEPTION;
            exception = e;
            this.message = e.getMessage();
        }

        //

        if (outLinee != null) {
            outputLines = outLinee.getLines();
            allOutputLines = outLinee.getAllLines();
        }
        if (errLinee != null) {
            errorLines = errLinee.getLines();
            allErrorLines = errLinee.getAllLines();
        }

        this.closeStreams(outLinee, errLinee);
    } catch (Exception e) {
        throw new ExtendedExecuteException(e.getMessage(), Executor.INVALID_EXITVALUE, e);
    }

    return exitMode;
}

From source file:com.tascape.qa.th.android.driver.UiAutomatorDevice.java

public File takeDeviceScreenshot() throws IOException {
    try {//from   w  ww .j  a v  a 2  s .co m
        return ss();
    } catch (ExecuteException ex) {
        LOG.warn(ex.getMessage());
        try {
            Utils.sleep(5000, "wait for device");
        } catch (InterruptedException ex1) {
            LOG.warn(ex.getMessage());
        }
        return ss();
    }
}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

/**
 * This calls a TIBCO binary.//from  ww  w. j  a va 2  s .co  m
 * 
 * @param binary, the TIBCO binary file to execute
 * @param tras, the TRA files associated with the TIBCO binary
 * @param arguments, command-line arguments
 * @param workingDir, working directory from where the binary is launched
 * @param errorMsg, error message to display in case of a failure
 * @param fork, if true the chiild process will be detached from the caller
 * 
 * @throws IOException
 * @throws MojoExecutionException
 */
protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir,
        String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException {
    Integer result = 0;

    if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary
        String traPathFileName = binary.getAbsolutePath();
        traPathFileName = FilenameUtils.removeExtension(traPathFileName);
        traPathFileName += ".tra";
        tras = new ArrayList<File>();
        tras.add(new File(traPathFileName));
    }

    HashMap<File, File> trasMap = new HashMap<File, File>();
    for (File tra : tras) {
        // copy of ".tra" file in the working directory
        File tmpTRAFile = new File(directory, tra.getName());
        trasMap.put(tra, tmpTRAFile);
        copyFile(tra, tmpTRAFile);
    }

    for (File tra : trasMap.keySet()) {
        if (trasMap.containsKey(tibcoDesignerTRAPath)
                && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath)
                        || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) {
            if (tras.size() > 1) {
                ReplaceRegExp replaceRegExp = new ReplaceRegExp();
                replaceRegExp.setFile(trasMap.get(tra));
                replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)");
                replaceRegExp.setReplace(
                        "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/'));
                replaceRegExp.setByLine(true);

                replaceRegExp.execute();
            }
        }

        if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly
            // append user.home at the end to force the use of custom Designer5.prefs
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true)));
            out.println("");
            out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/"));
            out.close();
        }
    }

    CommandLine cmdLine = new CommandLine(binary);

    for (String argument : arguments) {
        cmdLine.addArgument(argument);
    }
    getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString());
    getLog().debug("working dir : " + workingDir);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDir);

    if (timeOut > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000);
        executor.setWatchdog(watchdog);
    }

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr));

    if (fork) {
        CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher();
        commandLauncher.exec(cmdLine, null, workingDir);
    } else {
        try {
            if (synchronous) {
                result = executor.execute(cmdLine);
            } else {
                executor.execute(cmdLine, new DefaultExecuteResultHandler());
            }
        } catch (ExecuteException e) {
            // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques)
            getLog().info(cmdLine.toString());
            getLog().info(stdOutAndErr.toString());
            getLog().info(result.toString());
            throw new MojoExecutionException(errorMsg, e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    return result;
}

From source file:org.apache.bigtop.itest.hive.HiveHelper.java

public static Map<String, String> execCommand(CommandLine commandline, Map<String, String> envVars) {

    System.out.println("Executing command:");
    System.out.println(commandline.toString());
    Map<String, String> env = null;
    Map<String, String> entry = new HashMap<String, String>();
    try {//from   w w w .j  a va 2  s. c  o m
        env = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to get process environment: " + e1.getMessage());
        e1.printStackTrace();
    }
    if (envVars != null) {
        for (String key : envVars.keySet()) {
            env.put(key, envVars.get(key));
        }
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 10000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(streamHandler);
    try {
        executor.execute(commandline, env, resultHandler);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    }

    try {
        resultHandler.waitFor();
        /*System.out.println("Command output: "+outputStream.toString());*/
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        return entry;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        /*System.out.println("Command output: "+outputStream.toString());*/
        LOG.debug("exitValue: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        e.printStackTrace();
        return entry;
    }
}

From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java

public ExecResult execute(ExecCommand command) {
    notNull(command, "command");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();

    DefaultExecutor executor = prepareDefaultExecutor(command);
    // handle error and output of the process and write them to the given
    // out stream
    PumpStreamHandler handler = new PumpStreamHandler(out, err, command.getInput());
    executor.setStreamHandler(handler);/* w  w w  . java 2s.c  om*/

    CommandLine cl = toCommandLine(command);

    try {
        int exitValue = executor.execute(cl);
        // if the size is zero, we have no output, so construct the result
        // with null (required by ExecResult)
        InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray());
        InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray());
        ExecResult result = new ExecResult(command, stdout, stderr, exitValue);
        return result;

    } catch (ExecuteException ee) {
        LOG.error("ExecException while executing command: " + command.toString() + " - " + ee.getMessage());
        throw new ExecException("Failed to execute command " + command, ee);
    } catch (IOException ioe) {
        // invalid working dir
        LOG.error("IOException while executing command: " + command.toString() + " - " + ioe.getMessage());
        throw new ExecException("Unable to execute command " + command, ioe);
    } finally {
        // the inputStream must be closed after the execution
        IOUtils.closeQuietly(command.getInput());
    }
}

From source file:org.apache.geode.examples.replicated.ReplicatedTest.java

/**
 * Given a script file name, runs the script and return the exit code.
 * If exitCode != 0 extract and prints exception.
 * @param scriptName//from  w ww  . j  a  v  a 2  s.  c om
 * @return <code>int</code> with exitCode
 * @throws IOException
 * @throws InterruptedException
 */
private int executeScript(String scriptName) throws IOException, InterruptedException {
    final int exitCode;
    DefaultExecuteResultHandler resultHandler = shell.execute(scriptName, scriptTimeout, environment,
            testFolder.getRoot());
    processRunning = true;
    resultHandler.waitFor();

    logger.finest(String.format("Executing %s...", scriptName));
    exitCode = resultHandler.getExitValue();

    // extract and log exception if any happened
    if (exitCode != 0) {
        ExecuteException executeException = resultHandler.getException();
        logger.log(Level.SEVERE, executeException.getMessage(), executeException);
    }
    return exitCode;
}

From source file:org.apache.zeppelin.shell.ShellInterpreter.java

@Override
public InterpreterResult interpret(String cmd, InterpreterContext contextInterpreter) {
    logger.debug("Run shell command '" + cmd + "'");
    long start = System.currentTimeMillis();
    CommandLine cmdLine = CommandLine.parse("bash");
    cmdLine.addArgument("-c", false);
    cmdLine.addArgument(cmd, false);//from www.j  a  v a2 s.  co  m
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    executor.setWatchdog(new ExecuteWatchdog(commandTimeOut));
    try {
        int exitValue = executor.execute(cmdLine);
        return new InterpreterResult(InterpreterResult.Code.SUCCESS, outputStream.toString());
    } catch (ExecuteException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    } catch (IOException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    }
}

From source file:org.apache.zeppelin.spark.ZeppelinR.java

@Override
public void onProcessFailed(ExecuteException e) {
    logger.error(e.getMessage(), e);
    rScriptRunning = false;
}

From source file:org.apache.zeppelin.submarine.job.thread.JobRunThread.java

public void run() {
    boolean tryLock = lockRunning.tryLock();
    if (false == tryLock) {
        LOGGER.warn("Can not get JobRunThread lockRunning!");
        return;//from   w  ww . java 2s  .  com
    }

    SubmarineUI submarineUI = submarineJob.getSubmarineUI();
    try {
        InterpreterContext intpContext = submarineJob.getIntpContext();
        String noteId = intpContext.getNoteId();
        String userName = intpContext.getAuthenticationInfo().getUser();
        String jobName = SubmarineUtils.getJobName(userName, noteId);

        if (true == running.get()) {
            String message = String.format("Job %s already running.", jobName);
            submarineUI.outputLog("WARN", message);
            LOGGER.warn(message);
            return;
        }
        running.set(true);

        Properties properties = submarineJob.getProperties();
        HdfsClient hdfsClient = submarineJob.getHdfsClient();
        File pythonWorkDir = submarineJob.getPythonWorkDir();

        submarineJob.setCurrentJobState(EXECUTE_SUBMARINE);

        String algorithmPath = properties.getProperty(SubmarineConstants.SUBMARINE_ALGORITHM_HDFS_PATH, "");
        if (!algorithmPath.startsWith("hdfs://")) {
            String message = "Algorithm file upload HDFS path, " + "Must be `hdfs://` prefix. now setting "
                    + algorithmPath;
            submarineUI.outputLog("Configuration error", message);
            return;
        }

        List<ParagraphInfo> paragraphInfos = intpContext.getIntpEventClient().getParagraphList(userName,
                noteId);
        String outputMsg = hdfsClient.saveParagraphToFiles(noteId, paragraphInfos,
                pythonWorkDir == null ? "" : pythonWorkDir.getAbsolutePath(), properties);
        if (!StringUtils.isEmpty(outputMsg)) {
            submarineUI.outputLog("Save algorithm file", outputMsg);
        }

        HashMap jinjaParams = SubmarineUtils.propertiesToJinjaParams(properties, submarineJob, true);

        URL urlTemplate = Resources.getResource(SubmarineJob.SUBMARINE_JOBRUN_TF_JINJA);
        String template = Resources.toString(urlTemplate, Charsets.UTF_8);
        Jinjava jinjava = new Jinjava();
        String submarineCmd = jinjava.render(template, jinjaParams);
        // If the first line is a newline, delete the newline
        int firstLineIsNewline = submarineCmd.indexOf("\n");
        if (firstLineIsNewline == 0) {
            submarineCmd = submarineCmd.replaceFirst("\n", "");
        }

        StringBuffer sbLogs = new StringBuffer(submarineCmd);
        submarineUI.outputLog("Submarine submit command", sbLogs.toString());

        long timeout = Long
                .valueOf(properties.getProperty(SubmarineJob.TIMEOUT_PROPERTY, SubmarineJob.defaultTimeout));
        CommandLine cmdLine = CommandLine.parse(SubmarineJob.shell);
        cmdLine.addArgument(submarineCmd, false);
        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchDog);
        StringBuffer sbLogOutput = new StringBuffer();
        executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
            @Override
            protected void processLine(String line, int level) {
                line = line.trim();
                if (!StringUtils.isEmpty(line)) {
                    sbLogOutput.append(line + "\n");
                }
            }
        }));

        if (Boolean.valueOf(properties.getProperty(SubmarineJob.DIRECTORY_USER_HOME))) {
            executor.setWorkingDirectory(new File(System.getProperty("user.home")));
        }

        Map<String, String> env = new HashMap<>();
        String launchMode = (String) jinjaParams.get(SubmarineConstants.INTERPRETER_LAUNCH_MODE);
        if (StringUtils.equals(launchMode, "yarn")) {
            // Set environment variables in the submarine interpreter container run on yarn
            String javaHome, hadoopHome, hadoopConf;
            javaHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_JAVA_HOME);
            hadoopHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_HADOOP_HDFS_HOME);
            hadoopConf = (String) jinjaParams.get(SubmarineConstants.SUBMARINE_HADOOP_CONF_DIR);
            env.put("JAVA_HOME", javaHome);
            env.put("HADOOP_HOME", hadoopHome);
            env.put("HADOOP_HDFS_HOME", hadoopHome);
            env.put("HADOOP_CONF_DIR", hadoopConf);
            env.put("YARN_CONF_DIR", hadoopConf);
            env.put("CLASSPATH", "`$HADOOP_HDFS_HOME/bin/hadoop classpath --glob`");
            env.put("ZEPPELIN_FORCE_STOP", "true");
        }

        LOGGER.info("Execute EVN: {}, Command: {} ", env.toString(), submarineCmd);
        AtomicBoolean cmdLineRunning = new AtomicBoolean(true);
        executor.execute(cmdLine, env, new DefaultExecuteResultHandler() {
            @Override
            public void onProcessComplete(int exitValue) {
                String message = String.format("jobName %s ProcessComplete exit value is : %d", jobName,
                        exitValue);
                LOGGER.info(message);
                submarineUI.outputLog("JOR RUN COMPLETE", message);
                cmdLineRunning.set(false);
                submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_FINISHED);
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                String message = String.format("jobName %s ProcessFailed exit value is : %d, exception is : %s",
                        jobName, e.getExitValue(), e.getMessage());
                LOGGER.error(message);
                submarineUI.outputLog("JOR RUN FAILED", message);
                cmdLineRunning.set(false);
                submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
            }
        });
        int loopCount = 100;
        while ((loopCount-- > 0) && cmdLineRunning.get() && running.get()) {
            Thread.sleep(1000);
        }
        if (watchDog.isWatching()) {
            watchDog.destroyProcess();
            Thread.sleep(1000);
        }
        if (watchDog.isWatching()) {
            watchDog.killedProcess();
        }

        // Check if it has been submitted to YARN
        Map<String, Object> jobState = submarineJob.getJobStateByYarn(jobName);
        loopCount = 50;
        while ((loopCount-- > 0) && !jobState.containsKey("state") && running.get()) {
            Thread.sleep(3000);
            jobState = submarineJob.getJobStateByYarn(jobName);
        }

        if (!jobState.containsKey("state")) {
            String message = String.format("JOB %s was not submitted to YARN!", jobName);
            LOGGER.error(message);
            submarineUI.outputLog("JOR RUN FAILED", message);
            submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
        submarineUI.outputLog("Exception", e.getMessage());
    } finally {
        running.set(false);
        lockRunning.unlock();
    }
}

From source file:org.apache.zeppelin.submarine.job.thread.TensorboardRunThread.java

public void run() {
    SubmarineUI submarineUI = submarineJob.getSubmarineUI();

    boolean tryLock = lockRunning.tryLock();

    try {//w  ww.ja  va2s  .c o m
        Properties properties = submarineJob.getProperties();
        String tensorboardName = SubmarineUtils.getTensorboardName(submarineJob.getUserName());
        if (true == running.get()) {
            String message = String.format("tensorboard %s already running.", tensorboardName);
            submarineUI.outputLog("WARN", message);
            LOGGER.warn(message);
            return;
        }
        running.set(true);

        HashMap jinjaParams = SubmarineUtils.propertiesToJinjaParams(properties, submarineJob, false);
        // update jobName -> tensorboardName
        jinjaParams.put(SubmarineConstants.JOB_NAME, tensorboardName);

        URL urlTemplate = Resources.getResource(SubmarineJob.SUBMARINE_TENSORBOARD_JINJA);
        String template = Resources.toString(urlTemplate, Charsets.UTF_8);
        Jinjava jinjava = new Jinjava();
        String submarineCmd = jinjava.render(template, jinjaParams);
        // If the first line is a newline, delete the newline
        int firstLineIsNewline = submarineCmd.indexOf("\n");
        if (firstLineIsNewline == 0) {
            submarineCmd = submarineCmd.replaceFirst("\n", "");
        }
        StringBuffer sbLogs = new StringBuffer(submarineCmd);
        submarineUI.outputLog("Submarine submit command", sbLogs.toString());

        long timeout = Long
                .valueOf(properties.getProperty(SubmarineJob.TIMEOUT_PROPERTY, SubmarineJob.defaultTimeout));
        CommandLine cmdLine = CommandLine.parse(SubmarineJob.shell);
        cmdLine.addArgument(submarineCmd, false);
        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchDog);
        StringBuffer sbLogOutput = new StringBuffer();
        executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
            @Override
            protected void processLine(String line, int level) {
                line = line.trim();
                if (!StringUtils.isEmpty(line)) {
                    sbLogOutput.append(line + "\n");
                }
            }
        }));

        if (Boolean.valueOf(properties.getProperty(SubmarineJob.DIRECTORY_USER_HOME))) {
            executor.setWorkingDirectory(new File(System.getProperty("user.home")));
        }

        Map<String, String> env = new HashMap<>();
        String launchMode = (String) jinjaParams.get(SubmarineConstants.INTERPRETER_LAUNCH_MODE);
        if (StringUtils.equals(launchMode, "yarn")) {
            // Set environment variables in the container
            String javaHome, hadoopHome, hadoopConf;
            javaHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_JAVA_HOME);
            hadoopHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_HADOOP_HDFS_HOME);
            hadoopConf = (String) jinjaParams.get(SubmarineConstants.SUBMARINE_HADOOP_CONF_DIR);
            env.put("JAVA_HOME", javaHome);
            env.put("HADOOP_HOME", hadoopHome);
            env.put("HADOOP_HDFS_HOME", hadoopHome);
            env.put("HADOOP_CONF_DIR", hadoopConf);
            env.put("YARN_CONF_DIR", hadoopConf);
            env.put("CLASSPATH", "`$HADOOP_HDFS_HOME/bin/hadoop classpath --glob`");
        }

        LOGGER.info("Execute EVN: {}, Command: {} ", env.toString(), submarineCmd);

        AtomicBoolean cmdLineRunning = new AtomicBoolean(true);
        executor.execute(cmdLine, env, new DefaultExecuteResultHandler() {
            @Override
            public void onProcessComplete(int exitValue) {
                String message = String.format("jobName %s ProcessComplete exit value is : %d", tensorboardName,
                        exitValue);
                LOGGER.info(message);
                submarineUI.outputLog("TENSORBOARD RUN COMPLETE", message);
                cmdLineRunning.set(false);
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                String message = String.format("jobName %s ProcessFailed exit value is : %d, exception is : %s",
                        tensorboardName, e.getExitValue(), e.getMessage());
                LOGGER.error(message);
                submarineUI.outputLog("TENSORBOARD RUN FAILED", message);
                cmdLineRunning.set(false);
            }
        });
        int loopCount = 100;
        while ((loopCount-- > 0) && cmdLineRunning.get() && running.get()) {
            Thread.sleep(1000);
        }
        if (watchDog.isWatching()) {
            watchDog.destroyProcess();
            Thread.sleep(1000);
        }
        if (watchDog.isWatching()) {
            watchDog.killedProcess();
        }

        // Check if it has been submitted to YARN
        Map<String, Object> jobState = submarineJob.getJobStateByYarn(tensorboardName);
        loopCount = 50;
        while ((loopCount-- > 0) && !jobState.containsKey("state") && running.get()) {
            Thread.sleep(3000);
            jobState = submarineJob.getJobStateByYarn(tensorboardName);
        }

        if (!jobState.containsKey("state")) {
            String message = String.format("tensorboard %s was not submitted to YARN!", tensorboardName);
            LOGGER.error(message);
            submarineUI.outputLog("JOR RUN FAILED", message);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        submarineUI.outputLog("Exception", e.getMessage());
    } finally {
        running.set(false);
        lockRunning.unlock();
    }
}