Example usage for org.apache.commons.exec ExecuteWatchdog ExecuteWatchdog

List of usage examples for org.apache.commons.exec ExecuteWatchdog ExecuteWatchdog

Introduction

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

Prototype

public ExecuteWatchdog(final long timeout) 

Source Link

Document

Creates a new watchdog with a given timeout.

Usage

From source file:modules.NativeProcessMonitoringDaemonModule.java

protected void startNativeMonitor(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return;/*from   w ww .j av  a 2s.  c  o m*/
    }
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    executor = new DefaultExecutor();
    esh = new MyExecuteStreamHandler();
    executor.setStreamHandler(esh);

    // GeneralExecutableModuleConfig generalExecutableModuleConfig =
    // getConfig();
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }

    try {
        // System.out.println("Now execute: " + commandLine);
        executor.execute(commandLine, this);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        throw n;
    }
    return;
}

From source file:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

/**
 * Sets the timeout for the process./*from   www .  j a v  a 2s  . co m*/
 * 
 * @param object
 *            the {@link Duration} of the timeout; or the {@link Number}
 *            timeout in milliseconds; or an {@link Object} that is parsed
 *            as the duration.
 * 
 * @throws CommandException
 *             if any errors set the timeout watchdog.
 * 
 * @throws IllegalArgumentException
 *             if the parsed duration is not valid.
 */
public void setTimeout(Object object) throws CommandException {
    if (object instanceof Duration) {
        Duration timeout = (Duration) object;
        setWatchdog(new ExecuteWatchdog(timeout.getMillis()));
    } else if (object instanceof Number) {
        Number timeout = (Number) object;
        setWatchdog(new ExecuteWatchdog(timeout.longValue()));
    } else {
        Duration timeout = Duration.parse(object.toString());
        setWatchdog(new ExecuteWatchdog(timeout.getMillis()));
    }
}

From source file:com.jredrain.startup.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }// www  .  j av a  2  s .co m

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[redrain]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = RedRain.StatusCode.ERROR_EXEC.getValue();
        }
        if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[redrain]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[redrain]:error:{}", e);
            }
        }

        if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[redrain]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java

protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir,
        InputStream input) throws IOException {
    // Create the result object
    TestJobResult.TransformResult result = new TestJobResult.TransformResult();

    CountingOutputStream output = null;/*from  ww  w.  ja  v a 2 s . c  o m*/
    CountingOutputStream error = null;
    try {
        // Create and open temporary file for standard output
        File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir);
        output = new CountingOutputStream(new FileOutputStream(outputFile));

        // Create and open temporary file for standard error
        File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir);
        error = new CountingOutputStream(new FileOutputStream(errorFile));

        // If executable is relative, try to resolve in working directory
        // (This emulates the behavior of Streaming)
        if (!executable.isAbsolute()) {
            File resolvedExecutable = new File(workingDir, executable.toString());
            if (resolvedExecutable.isFile()) {
                resolvedExecutable.setExecutable(true);
                executable = resolvedExecutable.getAbsoluteFile();
            }
        }

        // Run the transform

        CommandLine command;
        if (_switchUserCommand == null)
            command = new CommandLine(executable);
        else {
            command = CommandLine.parse(_switchUserCommand);
            HashMap<String, String> substitutionMap = new HashMap<String, String>();
            substitutionMap.put("cmd", executable.toString());
            command.setSubstitutionMap(substitutionMap);
        }

        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT);
        PumpStreamHandler pump = new PumpStreamHandler(output, error, input);
        executor.setWorkingDirectory(workingDir);
        executor.setWatchdog(dog);
        executor.setStreamHandler(pump);
        executor.setExitValues(null);

        int exitCode = executor.execute(command);

        result.setExitCode(exitCode);

        // Check whether it produced any output
        if (output.getByteCount() == 0) {
            output.close();
            outputFile.delete();
        } else
            result.setOutputFile(outputFile);

        // Check whether it produced any error output
        if (error.getByteCount() == 0) {
            error.close();
            errorFile.delete();
        } else
            result.setErrorFile(errorFile);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(error);
    }

    return result;
}

From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java

private void packageApplication() throws MojoExecutionException {
    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("package");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);/* www .  ja va  2  s .co m*/
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during packaging", e);
    }
}

From source file:com.oneops.inductor.ProcessRunner.java

/**
 * Creates a process and logs the output
 *
 * @param cmd//from  w  ww .  ja v a2  s.co m
 * @param logKey
 * @param result
 */
private void executeProcess(String[] cmd, String logKey, ProcessResult result) {

    Map<String, String> env = getEnvVars(logKey, cmd);
    logger.info(logKey + " Cmd: " + String.join(" ", cmd) + ", Env: " + env);

    // run the cmd
    try {

        CommandLine cmdLine = new CommandLine(cmd[0]);
        // add rest of cmd string[] as arguments
        for (int i = 1; i < cmd.length; i++) {
            // needs the quote handling=false or else doesn't work
            // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec?
            cmdLine.addArgument(cmd[i], false);
        }
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
        executor.setStreamHandler(new OutputHandler(logger, logKey, result));
        result.setResultCode(executor.execute(cmdLine, env));

        // set fault to last error if fault map is empty
        if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) {
            result.getFaultMap().put("ERROR", result.getLastError());
        }

    } catch (ExecuteException ee) {
        logger.error(logKey + ee);
        result.setResultCode(ee.getExitValue());
    } catch (IOException e) {
        logger.error(e);
        result.setResultCode(1);
    }

}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

@DescribeProcess(title = "r.viewshed", description = "Computes the viewshed of a point on an elevation raster map.")
@DescribeResult(description = "area visible from provided location")
public static GridCoverage2D viewshed(
        @DescribeParameter(name = "dem", description = "digitial elevation model") GridCoverage2D dem,
        @DescribeParameter(name = "x", description = "x location in map units") double x,
        @DescribeParameter(name = "y", description = "y location in map units") double y) throws Exception {

    String COMMAND = "viewshed";
    //Stage files in a temporary location
    File geodb = Files.createTempDirectory("grassdata").toFile();
    geodb.deleteOnExit();//  w ww  . java  2  s  .c om
    File location = new File(geodb, COMMAND + Long.toString(random.nextLong()) + "location");

    // stage dem file
    File file = new File(geodb, "dem.tif");
    //The file must exist for FileImageOutputStreamExtImplSpi to create the output stream
    if (!file.exists()) {
        file.getParentFile().mkdirs();
        file.createNewFile();
    }
    final GeoTiffFormat format = new GeoTiffFormat();
    GridCoverageWriter writer = format.getWriter(file);
    writer.write(dem, null);
    LOGGER.info("Staging file:" + file);

    // use file to create location with (returns PERMANENT mapset)
    File mapset = location(location, file);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(60000));
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    executor.setWorkingDirectory(mapset);

    Map<String, String> env = customEnv(geodb, location, mapset);

    // EXPORT IMPORT DEM
    // r.in.gdal input=~/grassdata/viewshed/PERMANENT/dem.tif output=dem --overwrite

    File r_in_gdal = bin("r.in.gdal");
    CommandLine cmd = new CommandLine(r_in_gdal);
    cmd.addArgument("input=${file}");
    cmd.addArgument("output=dem");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("file", file));
    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_in_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE VIEWSHED
    File r_viewshed = bin("r.viewshed");
    cmd = new CommandLine(r_viewshed);
    cmd.addArgument("input=dem");
    cmd.addArgument("output=viewshed");
    cmd.addArgument("coordinates=${x},${y}");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("x", x, "y", y));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_viewshed.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE EXPORT VIEWSHED
    // r.out.gdal --overwrite input=viewshed@PERMANENT output=/Users/jody/grassdata/viewshed/viewshed.tif format=GTiff
    File viewshed = new File(location, "viewshed.tif");

    File r_out_gdal = bin("r.out.gdal");
    cmd = new CommandLine(r_out_gdal);
    cmd.addArgument("input=viewshed");
    cmd.addArgument("output=${viewshed}");
    cmd.addArgument("--overwrite");
    cmd.addArgument("format=GTiff");
    cmd.setSubstitutionMap(new KVP("viewshed", viewshed));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_out_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // STAGE RESULT

    if (!viewshed.exists()) {
        throw new IOException("Generated viweshed.tif not found");
    }
    GeoTiffReader reader = format.getReader(viewshed);
    GridCoverage2D coverage = reader.read(null);
    cleanup(new File(env.get("GISRC")));
    return coverage;
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * Runs a command line task and returns the screen output or throws and
 * error if something bad happened//from  ww  w  . j a  v a 2  s  .c o  m
 *
 * @param command Command to run
 *
 * @return Screen output
 *
 * @throws Exception
 */
public static String execToString(String command) throws Exception {

    // Prepare the command line

    CommandLine commandline = CommandLine.parse(command);

    // Prepare the output stream

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

    // Prepare the executor

    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValues(null);
    exec.setStreamHandler(streamHandler);
    exec.setWatchdog(new ExecuteWatchdog(5000));

    // Execute the command
    try {
        exec.execute(commandline);
        return (outputStream.toString());
    } catch (Exception e) {
        throw new Exception(String.format("%s - %s", outputStream.toString(), e.getMessage()));
    }
}

From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java

private void packageDistribution() throws MojoExecutionException {
    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("dist");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);/*  w  ww.  j  a va2s.  co  m*/
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during distribution creation", e);
    }
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }// w w  w . j av  a2s.  c o m
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}