Search in sources :

Example 41 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project cloudstack by apache.

the class HeatMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        CommandLine commandLine = new CommandLine("heat");
        if (dir != null && !dir.trim().isEmpty()) {
            commandLine.addArgument("dir");
            commandLine.addArgument(dir);
        }
        commandLine.addArgument("-gg");
        commandLine.addArgument("-cg");
        commandLine.addArgument(componentGroup);
        commandLine.addArgument("-ke");
        commandLine.addArgument("-sfrag");
        if (template == null || template.trim().isEmpty()) {
            commandLine.addArgument("-template");
            commandLine.addArgument("fragment");
        } else {
            commandLine.addArgument("-template");
            commandLine.addArgument(template);
        }
        if (outputFile != null) {
            commandLine.addArgument("-out");
            commandLine.addArgument(outputFile.getAbsolutePath());
        }
        if (directoryName != null) {
            commandLine.addArgument("-dr");
            commandLine.addArgument(directoryName);
        }
        if (vars != null) {
            commandLine.addArguments(vars, false);
        }
        DefaultExecutor executor = new DefaultExecutor();
        getLog().debug("working directory " + commandLine.toString());
        executor.setWorkingDirectory(getWorkingDirectory(workingDirectory));
        int exitValue = executor.execute(commandLine);
        if (exitValue != 0) {
            throw new MojoExecutionException("Problem executing heat, return code " + exitValue);
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Problem executing heat", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Problem executing heat", e);
    }
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteException(org.apache.commons.exec.ExecuteException) IOException(java.io.IOException)

Example 42 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project lucene-solr by apache.

the class TestSolrCLIRunExample method testFailExecuteScript.

@Test
public void testFailExecuteScript() throws Exception {
    File solrHomeDir = new File(ExternalPaths.SERVER_HOME);
    if (!solrHomeDir.isDirectory())
        fail(solrHomeDir.getAbsolutePath() + " not found and is required to run this test!");
    Path tmpDir = createTempDir();
    File solrExampleDir = tmpDir.toFile();
    File solrServerDir = solrHomeDir.getParentFile();
    // need a port to start the example server on
    int bindPort = -1;
    try (ServerSocket socket = new ServerSocket(0)) {
        bindPort = socket.getLocalPort();
    }
    File toExecute = new File(tmpDir.toString(), "failExecuteScript");
    assertTrue("Should have been able to create file '" + toExecute.getAbsolutePath() + "' ", toExecute.createNewFile());
    String[] toolArgs = new String[] { "-e", "techproducts", "-serverDir", solrServerDir.getAbsolutePath(), "-exampleDir", solrExampleDir.getAbsolutePath(), "-p", String.valueOf(bindPort), "-script", toExecute.getAbsolutePath().toString() };
    // capture tool output to stdout
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
    DefaultExecutor executor = new DefaultExecutor();
    SolrCLI.RunExampleTool tool = new SolrCLI.RunExampleTool(executor, System.in, stdoutSim);
    int code = tool.runTool(SolrCLI.processCommandLineArgs(SolrCLI.joinCommonAndToolOptions(tool.getOptions()), toolArgs));
    assertTrue("Execution should have failed with return code 1", code == 1);
}
Also used : Path(java.nio.file.Path) PrintStream(java.io.PrintStream) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ServerSocket(java.net.ServerSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File) Test(org.junit.Test)

Example 43 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project sling by apache.

the class JarExecutor method start.

/** Start the jar if not done yet, and setup runtime hook
     *  to stop it.
     */
public void start() throws Exception {
    final ExecuteResultHandler h = new ExecuteResultHandler() {

        public void onProcessFailed(ExecuteException ex) {
            log.error("Process execution failed:" + ex, ex);
        }

        public void onProcessComplete(int result) {
            log.info("Process execution complete, exit code=" + result);
        }
    };
    final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
    executor = new DefaultExecutor();
    final CommandLine cl = new CommandLine(jvmFullPath);
    if (vmOptions != null && vmOptions.length() > 0) {
        cl.addArguments(vmOptions);
    }
    cl.addArgument("-jar");
    cl.addArgument(jarToExecute.getAbsolutePath());
    // Additional options for the jar that's executed.
    // $JAREXEC_SERVER_PORT$ is replaced our serverPort value
    String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
    if (jarOptions != null && jarOptions.length() > 0) {
        jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
        log.info("Executable jar options: {}", jarOptions);
        cl.addArguments(jarOptions);
    }
    final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
    if (workFolderOption != null && workFolderOption.length() > 0) {
        final File workFolder = new File(workFolderOption);
        if (!workFolder.isDirectory()) {
            throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: " + workFolder.getAbsolutePath());
        }
        log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
        executor.setWorkingDirectory(workFolder);
    }
    String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
    final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);
    if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
        final long start = System.currentTimeMillis();
        log.info("Executing and waiting for result: " + cl);
        final int result = executor.execute(cl);
        final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
        log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
        if (result != expected) {
            throw new ExecutorException("Expected result code " + expected + ", got " + result);
        }
    } else {
        log.info("Executing asynchronously: " + cl);
        executor.setStreamHandler(new PumpStreamHandler());
        final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer("java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
        final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
        log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
        pd.setWaitOnShutdown(waitOnShutdown);
        executor.setProcessDestroyer(pd);
        executor.execute(cl, h);
    }
}
Also used : ExecuteResultHandler(org.apache.commons.exec.ExecuteResultHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ExecuteException(org.apache.commons.exec.ExecuteException) File(java.io.File)

Example 44 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project sling by apache.

the class JarExecutor method start.

/** Start the jar if not done yet, and setup runtime hook
     *  to stop it.
     */
public void start() throws Exception {
    final ExecuteResultHandler h = new ExecuteResultHandler() {

        public void onProcessFailed(ExecuteException ex) {
            log.error("Process execution failed:" + ex, ex);
        }

        public void onProcessComplete(int result) {
            log.info("Process execution complete, exit code=" + result);
        }
    };
    final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
    executor = new DefaultExecutor();
    final CommandLine cl = new CommandLine(jvmFullPath);
    if (vmOptions != null && vmOptions.length() > 0) {
        cl.addArguments(vmOptions);
    }
    cl.addArgument("-jar");
    cl.addArgument(jarToExecute.getAbsolutePath());
    // Additional options for the jar that's executed.
    // $JAREXEC_SERVER_PORT$ is replaced our serverPort value
    String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
    if (jarOptions != null && jarOptions.length() > 0) {
        jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
        log.info("Executable jar options: {}", jarOptions);
        cl.addArguments(jarOptions);
    }
    final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
    if (workFolderOption != null && workFolderOption.length() > 0) {
        final File workFolder = new File(workFolderOption);
        if (!workFolder.isDirectory()) {
            throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: " + workFolder.getAbsolutePath());
        }
        log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
        executor.setWorkingDirectory(workFolder);
    }
    String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
    final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);
    if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
        final long start = System.currentTimeMillis();
        log.info("Executing and waiting for result: " + cl);
        final int result = executor.execute(cl);
        final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
        log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
        if (result != expected) {
            throw new ExecutorException("Expected result code " + expected + ", got " + result);
        }
    } else {
        log.info("Executing asynchronously: " + cl);
        executor.setStreamHandler(new PumpStreamHandler());
        final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer("java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
        final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
        log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
        pd.setWaitOnShutdown(waitOnShutdown);
        executor.setProcessDestroyer(pd);
        executor.execute(cl, h);
    }
}
Also used : ExecuteResultHandler(org.apache.commons.exec.ExecuteResultHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ExecuteException(org.apache.commons.exec.ExecuteException) File(java.io.File)

Example 45 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project Saturn by vipshop.

the class ScriptJobRunner method execute.

private SaturnJobReturn execute(long timeoutSeconds) {
    SaturnJobReturn saturnJobReturn;
    ProcessOutputStream processOutputStream = new ProcessOutputStream(1);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(processOutputStream);
    // 关闭线程等待时间, (注意commons-exec会固定增加2秒的addition)
    streamHandler.setStopTimeout(timeoutSeconds * 1000);
    executor.setExitValue(0);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(getWatchdog());
    // filter env key in execParameter. like cd ${mypath} -> cd /root/my.
    Map<String, String> env = ScriptPidUtils.loadEnv();
    CommandLine commandLine = createCommandLine(env);
    try {
        long start = System.currentTimeMillis();
        log.info("[{}] msg=Begin executing {}-{} {}", jobName, jobName, item, commandLine);
        int exitValue = executor.execute(commandLine, env);
        long end = System.currentTimeMillis();
        log.info("[{}] msg=Finish executing {}-{} {}, the exit value is {}, cost={}ms", jobName, jobName, item, commandLine, exitValue, (end - start));
        SaturnJobReturn tmp = readSaturnJobReturn();
        if (tmp == null) {
            tmp = new SaturnJobReturn("the exit value is " + exitValue);
        }
        saturnJobReturn = tmp;
    } catch (Exception e) {
        saturnJobReturn = handleException(timeoutSeconds, e);
    } finally {
        try {
            // 将日志set进jobLog, 写不写zk再由ExecutionService控制
            handleJobLog(processOutputStream.getJobLog());
            processOutputStream.close();
        } catch (Exception ex) {
            log.error("[{}] msg={}-{} Error at closing output stream. Should not be concern: {}", jobName, jobName, item, ex);
        }
        stopStreamHandler(streamHandler);
        ScriptPidUtils.removePidFile(job.getExecutorName(), jobName, "" + item, watchdog.getPid());
    }
    return saturnJobReturn;
}
Also used : SaturnJobReturn(com.vip.saturn.job.SaturnJobReturn) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) IOException(java.io.IOException)

Aggregations

DefaultExecutor (org.apache.commons.exec.DefaultExecutor)82 CommandLine (org.apache.commons.exec.CommandLine)62 PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)47 IOException (java.io.IOException)36 ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)34 ExecuteException (org.apache.commons.exec.ExecuteException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)26 File (java.io.File)25 Executor (org.apache.commons.exec.Executor)12 DefaultExecuteResultHandler (org.apache.commons.exec.DefaultExecuteResultHandler)9 ShutdownHookProcessDestroyer (org.apache.commons.exec.ShutdownHookProcessDestroyer)9 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 URL (java.net.URL)4 Properties (java.util.Properties)4 LogOutputStream (org.apache.commons.exec.LogOutputStream)4 InputStream (java.io.InputStream)3 PipedInputStream (java.io.PipedInputStream)3 PipedOutputStream (java.io.PipedOutputStream)3 HashSet (java.util.HashSet)3