Search in sources :

Example 16 with ExecuteWatchdog

use of org.apache.commons.exec.ExecuteWatchdog in project openhab1-addons by openhab.

the class ExecBinding method executeCommandAndWaitResponse.

/**
     * <p>
     * Executes <code>commandLine</code>. Sometimes (especially observed on
     * MacOS) the commandLine isn't executed properly. In that cases another
     * exec-method is to be used. To accomplish this please use the special
     * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
     * delimiter it is split into a String[] array and the special exec-method
     * is used.
     * </p>
     * <p>
     * A possible {@link IOException} gets logged but no further processing is
     * done.
     * </p>
     *
     * @param commandLine the command line to execute
     * @return response data from executed command line
     */
private String executeCommandAndWaitResponse(String commandLine) {
    String retval = null;
    CommandLine cmdLine = null;
    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);
        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);
    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);
    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }
    return retval;
}
Also used : DefaultExecuteResultHandler(org.apache.commons.exec.DefaultExecuteResultHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) Executor(org.apache.commons.exec.Executor) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ExecuteException(org.apache.commons.exec.ExecuteException)

Example 17 with ExecuteWatchdog

use of org.apache.commons.exec.ExecuteWatchdog in project opennms by OpenNMS.

the class SystemReportResourceLocator method slurpOutput.

@Override
public String slurpOutput(final String commandString, final boolean ignoreExitCode) {
    final CommandLine command = CommandLine.parse(commandString);
    LOG.debug("running: {}", commandString);
    final Map<String, String> environment = new HashMap<String, String>(System.getenv());
    environment.put("COLUMNS", "2000");
    DataInputStream input = null;
    PipedInputStream pis = null;
    OutputSuckingParser parser = null;
    String outputText = null;
    final DefaultExecutor executor = new DefaultExecutor();
    final PipedOutputStream output = new PipedOutputStream();
    final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output);
    executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait));
    executor.setStreamHandler(streamHandler);
    if (ignoreExitCode) {
        executor.setExitValues(null);
    }
    try {
        LOG.trace("executing '{}'", commandString);
        pis = new PipedInputStream(output);
        input = new DataInputStream(pis);
        parser = new OutputSuckingParser(input);
        parser.start();
        final int exitValue = executor.execute(command, environment);
        IOUtils.closeQuietly(output);
        parser.join(m_maxProcessWait);
        if (!ignoreExitCode && exitValue != 0) {
            LOG.debug("error running '{}': exit value was {}", commandString, exitValue);
        } else {
            outputText = parser.getOutput();
        }
        LOG.trace("finished '{}'", commandString);
    } catch (final Exception e) {
        LOG.debug("Failed to run '{}'", commandString, e);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(pis);
    }
    return outputText;
}
Also used : HashMap(java.util.HashMap) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) DataInputStream(java.io.DataInputStream) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler)

Example 18 with ExecuteWatchdog

use of org.apache.commons.exec.ExecuteWatchdog in project opennms by OpenNMS.

the class AbstractSystemReportPlugin method getOpenNMSProcesses.

protected Set<Integer> getOpenNMSProcesses() {
    LOG.trace("getOpenNMSProcesses()");
    final Set<Integer> processes = new HashSet<Integer>();
    final String jps = getResourceLocator().findBinary("jps");
    LOG.trace("jps = {}", jps);
    DataInputStream input = null;
    PsParser parser = null;
    PipedInputStream pis = null;
    PipedOutputStream output = new PipedOutputStream();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(5000));
    if (jps != null) {
        CommandLine command = CommandLine.parse(jps + " -v");
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err);
        try {
            LOG.trace("executing '{}'", command);
            pis = new PipedInputStream(output);
            input = new DataInputStream(pis);
            parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
            parser.start();
            executor.setStreamHandler(streamHandler);
            int exitValue = executor.execute(command);
            IOUtils.closeQuietly(output);
            parser.join();
            processes.addAll(parser.getProcesses());
            LOG.trace("finished '{}'", command);
            if (exitValue != 0) {
                LOG.debug("error running '{}': exit value was {}", command, exitValue);
            }
        } catch (final Exception e) {
            LOG.debug("Failed to run '{}'", command, e);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(pis);
            IOUtils.closeQuietly(output);
        }
    }
    LOG.trace("looking for ps");
    final String ps = getResourceLocator().findBinary("ps");
    if (ps != null) {
        // try Linux/Mac style
        CommandLine command = CommandLine.parse(ps + " aww -o pid -o args");
        output = new PipedOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err);
        try {
            LOG.trace("executing '{}'", command);
            pis = new PipedInputStream(output);
            input = new DataInputStream(pis);
            parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
            parser.start();
            executor.setStreamHandler(streamHandler);
            int exitValue = executor.execute(command);
            IOUtils.closeQuietly(output);
            parser.join(MAX_PROCESS_WAIT);
            processes.addAll(parser.getProcesses());
            LOG.trace("finished '{}'", command);
            if (exitValue != 0) {
                LOG.debug("error running '{}': exit value was {}", command, exitValue);
            }
        } catch (final Exception e) {
            LOG.debug("error running '{}'", command, e);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(pis);
            IOUtils.closeQuietly(output);
        }
        if (processes.size() == 0) {
            // try Solaris style
            command = CommandLine.parse(ps + " -ea -o pid -o args");
            output = new PipedOutputStream();
            streamHandler = new PumpStreamHandler(output, System.err);
            try {
                LOG.trace("executing '{}'", command);
                pis = new PipedInputStream(output);
                input = new DataInputStream(pis);
                parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
                parser.start();
                executor.setStreamHandler(streamHandler);
                int exitValue = executor.execute(command);
                IOUtils.closeQuietly(output);
                parser.join(MAX_PROCESS_WAIT);
                processes.addAll(parser.getProcesses());
                LOG.trace("finished '{}'", command);
                if (exitValue != 0) {
                    LOG.debug("error running '{}': exit value was {}", command, exitValue);
                }
            } catch (final Exception e) {
                LOG.debug("error running '{}'", command, e);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(pis);
                IOUtils.closeQuietly(output);
            }
        }
    }
    if (processes.size() == 0) {
        LOG.warn("Unable to find any OpenNMS processes.");
    }
    return processes;
}
Also used : DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) DataInputStream(java.io.DataInputStream) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) PsParser(org.opennms.systemreport.system.PsParser) HashSet(java.util.HashSet)

Example 19 with ExecuteWatchdog

use of org.apache.commons.exec.ExecuteWatchdog in project opennms by OpenNMS.

the class RScriptExecutor method exec.

/**
 * Executes by given script by:
 *   - Searching both the classpath and the filesystem for the path
 *   - Copying the script at the given path to a temporary file and
 *     performing variable substitution with the arguments using Freemarker.
 *   - Invoking the script with commons-exec
 *   - Converting the input table to CSV and passing this to the process via stdin
 *   - Parsing stdout, expecting CSV output, and converting this to an immutable table
 */
public RScriptOutput exec(String script, RScriptInput input) throws RScriptException {
    Preconditions.checkNotNull(script, "script argument");
    Preconditions.checkNotNull(input, "input argument");
    // Grab the script/template
    Template template;
    try {
        template = m_freemarkerConfiguration.getTemplate(script);
    } catch (IOException e) {
        throw new RScriptException("Failed to read the script.", e);
    }
    // Create a temporary file
    File scriptOnDisk;
    try {
        scriptOnDisk = File.createTempFile("Rcsript", "R");
        scriptOnDisk.deleteOnExit();
    } catch (IOException e) {
        throw new RScriptException("Failed to create a temporary file.", e);
    }
    // Perform variable substitution and write the results to the temporary file
    try (FileOutputStream fos = new FileOutputStream(scriptOnDisk);
        Writer out = new OutputStreamWriter(fos)) {
        template.process(input.getArguments(), out);
    } catch (IOException | TemplateException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to process the template.", e);
    }
    // Convert the input matrix to a CSV string which will be passed to the script via stdin.
    // The table may be large, so we try and avoid writing it to disk
    final StringBuilder inputTableAsCsv;
    try {
        inputTableAsCsv = toCsv(input.getTable());
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to convert the input table to CSV.", e);
    }
    // Invoke Rscript against the script (located in a temporary file)
    CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY);
    cmdLine.addArgument(scriptOnDisk.getAbsolutePath());
    // Use commons-exec to execute the process
    DefaultExecutor executor = new DefaultExecutor();
    // Use the CharSequenceInputStream in order to avoid explicitly converting
    // the StringBuilder a string and then an array of bytes.
    InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, StandardCharsets.UTF_8);
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin));
    // Fail if we get a non-zero exit code
    executor.setExitValue(0);
    // Fail if the process takes too long
    ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);
    // Execute
    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("An error occured while executing Rscript, or the requested script.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e);
    }
    // Parse and return the results
    try {
        ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString());
        return new RScriptOutput(table);
    } catch (Throwable t) {
        throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), t);
    } finally {
        scriptOnDisk.delete();
    }
}
Also used : CharSequenceInputStream(org.apache.commons.io.input.CharSequenceInputStream) TemplateException(freemarker.template.TemplateException) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) CharSequenceInputStream(org.apache.commons.io.input.CharSequenceInputStream) InputStream(java.io.InputStream) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Template(freemarker.template.Template) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 20 with ExecuteWatchdog

use of org.apache.commons.exec.ExecuteWatchdog in project vespa by vespa-engine.

the class ProcessExecutor method execute.

/**
 * Executes the given command synchronously.
 *
 * @param command The command to execute.
 * @param processInput Input provided to the process.
 * @return The result of the execution, or empty if the process does not terminate within the timeout set for this executor.
 * @throws IOException if the process execution failed.
 */
public Optional<ProcessResult> execute(String command, String processInput) throws IOException {
    ByteArrayOutputStream processErr = new ByteArrayOutputStream();
    ByteArrayOutputStream processOut = new ByteArrayOutputStream();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(createStreamHandler(processOut, processErr, processInput));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeoutSeconds));
    executor.setWatchdog(watchDog);
    executor.setExitValues(successExitCodes);
    int exitCode;
    try {
        exitCode = executor.execute(CommandLine.parse(command));
    } catch (ExecuteException e) {
        exitCode = e.getExitValue();
    }
    return (watchDog.killedProcess()) ? Optional.empty() : Optional.of(new ProcessResult(exitCode, processOut.toString(), processErr.toString()));
}
Also used : DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) ExecuteException(org.apache.commons.exec.ExecuteException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)37 DefaultExecutor (org.apache.commons.exec.DefaultExecutor)36 CommandLine (org.apache.commons.exec.CommandLine)25 PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)24 IOException (java.io.IOException)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)14 ExecuteException (org.apache.commons.exec.ExecuteException)14 File (java.io.File)12 Executor (org.apache.commons.exec.Executor)10 DefaultExecuteResultHandler (org.apache.commons.exec.DefaultExecuteResultHandler)8 ShutdownHookProcessDestroyer (org.apache.commons.exec.ShutdownHookProcessDestroyer)7 HashMap (java.util.HashMap)4 PipedInputStream (java.io.PipedInputStream)3 PipedOutputStream (java.io.PipedOutputStream)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 InterpreterResult (org.apache.zeppelin.interpreter.InterpreterResult)3 Code (org.apache.zeppelin.interpreter.InterpreterResult.Code)3 Jinjava (com.hubspot.jinjava.Jinjava)2 DataInputStream (java.io.DataInputStream)2 FileOutputStream (java.io.FileOutputStream)2