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:beans.ExecutorFactoryImpl.java

@Override
public ProcExecutor getDeployExecutor(ServerNode server) {

    logger.info("Creating deploy executor.");
    String key = getKey(server);/*from  w  w w . j  a  v  a2s .  c  om*/

    ProcessStreamHandler streamHandler = getProcessStreamHandler(key);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(
            ApplicationContext.get().conf().cloudify.bootstrapCloudWatchDogProcessTimeoutMillis);

    ProcExecutor executor = (ProcExecutor) Spring.getBean("deployExecutor");
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(streamHandler);
    executor.setId(key);

    return executor;
}

From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java

public int execute(String[] args, Map<String, String> env, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }//from www . ja v a  2s  . com

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args, false);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    return exec.execute(cmd, env);
}

From source file:de.simu.decomap.messaging.resultprocessor.impl.helper.RulesExecutor.java

/**
 * Executing a predefined Rule/*from www .  ja va2  s . co  m*/
 * @param ruleType RuleType
 * @param arg args for Rule
 * @return Success
 */
public boolean executePredefinedRule(byte ruleType, String arg) {
    logger.info("[IPTABLES] -> executing predefined command...");

    // use apache's commons-exec for executing command!
    CommandLine cmdLine = new CommandLine(command);

    // get the predefined rule-parameters
    String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg);

    if (ruleParams != null) {

        // add rule-parameters to CommanLine-Object
        for (int i = 0; i < ruleParams.length; i++) {
            cmdLine.addArgument(ruleParams[i]);
        }

        // execute command
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout);
        Executor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.setWatchdog(watchdog);
        try {
            executor.execute(cmdLine, resultHandler);
        } catch (ExecuteException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: io-exception occured!");
            return false;
        }

        try {
            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitCode = resultHandler.getExitValue();
            logger.info("[IPTABLES] -> command " + ruleType + " executed, exit-code is: " + exitCode);

            switch (exitCode) {
            case EXIT_CODE_SUCCESS:
                return true;
            case EXIT_CODE_ERROR:
                return false;
            default:
                return false;
            }

        } catch (InterruptedException e) {
            logger.warn(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

    } else {
        logger.warn("[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!");
        return false;
    }
}

From source file:its.tools.CommandExecutor.java

public void execute(String[] args, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }//from w  w  w . j a va  2 s .  c o  m

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    exec.execute(cmd, new ResultHander());
}

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

private void runJob(Master.GenerateReport job) {
    TaskEvent taskEvent = job.reportJob.taskEvent;
    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    Map<String, Object> map = new HashMap<>();

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

    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }// ww w.j  a  v  a  2  s.  co m
    String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/";
    cmdLine.addArgument(dir);

    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;
    try {
        List<String> resultFiles = new ArrayList<>(job.results.size());
        //download all files adn
        /*int i=0;
        for (Worker.Result result : job.results) {
        String destFile = dir  + i++ + ".log";
        resultFiles.add(destFile);
        DownloadFile.downloadFile(result.metrics,destFile);
        }*/
        AtomicInteger index = new AtomicInteger();
        job.results.parallelStream().forEach(result -> {
            String destFile = dir + index.incrementAndGet() + ".log";
            resultFiles.add(destFile);
            DownloadFile.downloadFile(result.metrics, destFile);
        });
        String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId);
        String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId);
        //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);
        System.out.println(cmdLine);
        int exitResult = executor.execute(cmdLine);
        ReportResult result;
        if (executor.isFailure(exitResult)) {
            result = new ReportResult(dir, job.reportJob, false);
            log.info("Report Executor Failed, result: " + job.toString());
        } else {
            result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true);
            log.info("Report Executor Completed, result: " + result.toString());
        }
        for (String resultFile : resultFiles) {
            FileUtils.deleteQuietly(new File(resultFile));
        }
        getSender().tell(result, getSelf());

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }

}

From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java

public Executor start() throws Exception {
    CommandLine startCmd = toEngineCommand(Command.start);
    context.log.info("Start Axon.ivy Engine in folder: " + context.engineDirectory);

    Executor executor = createEngineExecutor();
    executor.setStreamHandler(createEngineLogStreamForwarder(logLine -> findStartEngineUrl(logLine)));
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.execute(startCmd, asynchExecutionHandler());
    waitForEngineStart(executor);//  w  ww.ja va2s .co m
    return executor;
}

From source file:io.vertx.config.vault.utils.VaultProcess.java

private void init() {
    String line = executable.getAbsolutePath() + " init -key-shares=1 -key-threshold=1 " + CA_CERT_ARG;
    System.out.println(">> " + line);
    CommandLine parse = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(l -> {
        if (l.contains("Unseal Key 1:")) {
            unseal = l.replace("Unseal Key 1: ", "").trim();
        } else if (l.contains("Initial Root Token:")) {
            token = l.replace("Initial Root Token: ", "").trim();
        }//  w  ww  .j a v a 2  s .c o  m
    }), System.err);

    ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(pump);
    try {
        executor.execute(parse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    //    await().until(() -> token != null);
    //    await().until(() -> unseal != null);

    System.out.println("Vault Server initialized (but sealed)");
    System.out.println("Root token: " + token);
    System.out.println("Unseal key: " + unseal);
}

From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsWrapper.java

@VisibleForTesting
ExecuteWatchdog createWatchDog() {
    return new ExecuteWatchdog(60L * 60 * 1000);
}

From source file:edu.buffalo.fusim.ReadSimulator.java

public void run(String artBinPath, File fusionFile, String outputPrefix, int readLength, int meanFragSize,
        int readCoverage, boolean pairedEnd) {
    // Example art call:
    //   art_illumina -i fusion.txt -o testsim -l 75 -f 10 -p -m 400 -s 10 
    CommandLine cmdLine = new CommandLine(artBinPath);

    // the filename of input DNA reference
    cmdLine.addArgument("-i");
    cmdLine.addArgument("${file}");
    // the prefix of output files
    cmdLine.addArgument("-o");
    cmdLine.addArgument("${outputPrefix}");
    // the length of reads to be simulated
    cmdLine.addArgument("-l");
    cmdLine.addArgument("" + readLength);
    // the fold of read coverage to be simulated
    cmdLine.addArgument("-f");
    cmdLine.addArgument("" + readCoverage);
    if (pairedEnd) {
        // indicate a paired-end read simulation
        cmdLine.addArgument("-p");
        // the mean size of DNA fragments for paired-end simulations
        cmdLine.addArgument("-m");
        cmdLine.addArgument("" + meanFragSize);
        // the standard deviation of DNA fragment size for paired-end simulations.
        cmdLine.addArgument("-s");
        cmdLine.addArgument("10");
    }/*from  w  ww .  ja v  a2s . co m*/
    // quite - turn off end of run summary
    cmdLine.addArgument("-q");

    Map map = new HashMap();
    map.put("file", fusionFile);
    map.put("outputPrefix", outputPrefix);
    cmdLine.setSubstitutionMap(map);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    // Timeout after 5 minutes
    ExecuteWatchdog watchdog = new ExecuteWatchdog(300000);
    executor.setWatchdog(watchdog);

    try {
        int exitValue = executor.execute(cmdLine);
    } catch (Exception e) {
        logger.fatal("Failed to execute ART for simulating Illumina reads: " + e.getMessage());
    }
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);//from w  w  w .ja v  a  2  s .  c om
    executor.setWatchdog(watchdog);
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}