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

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

Introduction

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

Prototype

public synchronized void stop() 

Source Link

Document

Stops the watcher.

Usage

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);
    }//from  w w  w  .j av  a 2 s  .  c om

    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:org.opencron.agent.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }//from   w w  w . j  a va 2 s  .  c  om

    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("[opencron]: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(Opencron.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 = Opencron.StatusCode.ERROR_EXEC.getValue();
        }
        if (Opencron.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[opencron]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[opencron]: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("[opencron]:error:{}", e);
            }
        }

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

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

    return response;
}

From source file:org.waarp.commandexec.server.LocalExecServerHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    answered = false;// w  w  w  .  j a  va2s .  co m
    String request = msg;

    // Generate and write a response.
    String response;
    response = LocalExecDefaultResult.NoStatus.status + " " + LocalExecDefaultResult.NoStatus.result;
    ExecuteWatchdog watchdog = null;
    try {
        if (request.length() == 0) {
            // No command
            response = LocalExecDefaultResult.NoCommand.status + " " + LocalExecDefaultResult.NoCommand.result;
        } else {
            String[] args = request.split(" ");
            int cpt = 0;
            long tempDelay;
            try {
                tempDelay = Long.parseLong(args[0]);
                cpt++;
            } catch (NumberFormatException e) {
                tempDelay = delay;
            }
            if (tempDelay < 0) {
                // Shutdown Order
                isShutdown = true;
                logger.warn("Shutdown order received");
                response = LocalExecDefaultResult.ShutdownOnGoing.status + " "
                        + LocalExecDefaultResult.ShutdownOnGoing.result;
                Thread thread = new GGLEThreadShutdown(factory);
                thread.start();
                return;
            }
            String binary = args[cpt++];
            File exec = new File(binary);
            if (exec.isAbsolute()) {
                // If true file, is it executable
                if (!exec.canExecute()) {
                    logger.error("Exec command is not executable: " + request);
                    response = LocalExecDefaultResult.NotExecutable.status + " "
                            + LocalExecDefaultResult.NotExecutable.result;
                    return;
                }
            }
            // Create command with parameters
            CommandLine commandLine = new CommandLine(binary);
            for (; cpt < args.length; cpt++) {
                commandLine.addArgument(args[cpt]);
            }
            DefaultExecutor defaultExecutor = new DefaultExecutor();
            ByteArrayOutputStream outputStream;
            outputStream = new ByteArrayOutputStream();
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
            defaultExecutor.setStreamHandler(pumpStreamHandler);
            int[] correctValues = { 0, 1 };
            defaultExecutor.setExitValues(correctValues);
            if (tempDelay > 0) {
                // If delay (max time), then setup Watchdog
                watchdog = new ExecuteWatchdog(tempDelay);
                defaultExecutor.setWatchdog(watchdog);
            }
            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(LocalExecDefaultResult.RETRYINMS);
                    } catch (InterruptedException e1) {
                    }
                    try {
                        status = defaultExecutor.execute(commandLine);
                    } catch (ExecuteException e1) {
                        try {
                            pumpStreamHandler.stop();
                        } catch (IOException e3) {
                        }
                        logger.error("Exception: " + e.getMessage() + " Exec in error with "
                                + commandLine.toString());
                        response = LocalExecDefaultResult.BadExecution.status + " "
                                + LocalExecDefaultResult.BadExecution.result;
                        try {
                            outputStream.close();
                        } catch (IOException e2) {
                        }
                        return;
                    } catch (IOException e1) {
                        try {
                            pumpStreamHandler.stop();
                        } catch (IOException e3) {
                        }
                        logger.error("Exception: " + e.getMessage() + " Exec in error with "
                                + commandLine.toString());
                        response = LocalExecDefaultResult.BadExecution.status + " "
                                + LocalExecDefaultResult.BadExecution.result;
                        try {
                            outputStream.close();
                        } catch (IOException e2) {
                        }
                        return;
                    }
                } else {
                    try {
                        pumpStreamHandler.stop();
                    } catch (IOException e3) {
                    }
                    logger.error(
                            "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                    response = LocalExecDefaultResult.BadExecution.status + " "
                            + LocalExecDefaultResult.BadExecution.result;
                    try {
                        outputStream.close();
                    } catch (IOException e2) {
                    }
                    return;
                }
            } catch (IOException e) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e3) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                response = LocalExecDefaultResult.BadExecution.status + " "
                        + LocalExecDefaultResult.BadExecution.result;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return;
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e3) {
            }
            if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
                // kill by the watchdoc (time out)
                logger.error("Exec is in Time Out");
                response = LocalExecDefaultResult.TimeOutExecution.status + " "
                        + LocalExecDefaultResult.TimeOutExecution.result;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
            } else {
                try {
                    response = status + " " + outputStream.toString(WaarpStringUtils.UTF8.name());
                } catch (UnsupportedEncodingException e) {
                    response = status + " " + outputStream.toString();
                }
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
            }
        }
    } finally {
        // We do not need to write a ByteBuf here.
        // We know the encoder inserted at LocalExecInitializer will do the
        // conversion.
        ctx.channel().writeAndFlush(response + "\n");
        answered = true;
        if (watchdog != null) {
            watchdog.stop();
        }
        logger.info("End of Command: " + request + " : " + response);
        ctx.channel().writeAndFlush(LocalExecDefaultResult.ENDOFCOMMAND + "\n");
    }
}