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

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

Introduction

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

Prototype

long INFINITE_TIMEOUT

To view the source code for org.apache.commons.exec ExecuteWatchdog INFINITE_TIMEOUT.

Click Source Link

Document

The marker for an infinite timeout

Usage

From source file:com.bptselenium.jenkins.BPTSeleniumJenkins.RunCommand.java

public static void runCommand(String command, TaskListener listener, Run<?, ?> build) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    executor.setExitValue(10);/* www.j av  a 2 s.c  o m*/
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        //getting a non-standard execution value, set build result to unstable
        Result result = Result.UNSTABLE;
        if (build.getResult() == null) {
            build.setResult(result);
        } else if (build.getResult().isBetterThan(result)) {
            build.setResult(result.combine(build.getResult()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        listener.getLogger().println(outputStream.toString());
    }
}

From source file:com.boulmier.machinelearning.jobexecutor.job.Job.java

public void start() throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    final PumpStreamHandler output = new PumpStreamHandler(out);
    final DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();

    exec.setWatchdog(wd);/*from   w w  w .ja  va 2 s . c o m*/
    exec.setStreamHandler(output);
    exec.execute(cl, handler);
    JobExecutor.logger.info("Running job " + jobid);

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                handler.waitFor();
                Computer.ComputeProperties properties = Computer.ComputeProperties.buildFromRequest(req);
                new SenderComputer(new StorageComputer(out.toString(), properties)).compute();
                JobExecutor.logger.info("Job complete " + jobid);
            } catch (InterruptedException ex) {
                exec.getWatchdog().destroyProcess();
                JobExecutor.logger.error(
                        "Job (" + jobid + ") has been destroyed due to internal error " + ex.getMessage());
            }
        }

    }).start();

}

From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn,
        ByteArrayOutputStream stdOut, ByteArrayOutputStream stdErr) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }//  w  w w . j  a va  2  s . c o m

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    pendingJobSet.add(jobId);

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));

            if (pendingJobSet.contains(jobId)) {
                pendingJobSet.remove(jobId);
            } else {
                // If the job was removed from the set of pending jobs by someone else, its deletion was requested
                jobIdToHandlerMap.remove(jobId);
                watchdog.destroyProcess();
            }
        }
    });

    return jobId;
}

From source file:com.k42b3.sacmis.ExecutorAbstract.java

public void run() {
    try {/* w  ww  . ja  va  2  s.c  o  m*/
        // clear text
        this.textArea.setText("");

        CommandLine commandLine = CommandLine.parse(this.getExecutable() + " " + this.cmd);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setStreamHandler(new PumpStreamHandler(new TextAreaOutputStream(textArea)));
        executor.setWatchdog(watchdog);
        executor.execute(commandLine);
    } catch (FoundNoExecutableException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Information", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }//www.  j  a  v  a  2 s .  c om

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
            ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));
        }
    });

    return jobId;
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from w ww.j  a va 2 s . c  o  m
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:hoot.services.nativeinterfaces.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        this.stdout = stdout;
        this.stderr = stderr;

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }//from   w  w  w . j  a  va2 s  .  c  o  m

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        this.watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        executor.setWatchdog(this.watchDog);
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);

            if (executor.isFailure(exitValue) && this.watchDog.killedProcess()) {
                // it was killed on purpose by the watchdog
                logger.info("Process for '{}' command was killed!", cmdLine);
            }
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

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());
    }//from   ww  w. java2 s.c om
    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);//  ww w .  jav  a 2 s .  c  o 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();
        }/*from w  ww. j  ava2  s .c om*/
    }), 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);
}