Example usage for org.apache.commons.exec DefaultExecutor setWatchdog

List of usage examples for org.apache.commons.exec DefaultExecutor setWatchdog

Introduction

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

Prototype

public void setWatchdog(final ExecuteWatchdog watchDog) 

Source Link

Usage

From source file:org.mule.test.infrastructure.process.MuleUtils.java

public static int executeCommand(String command, String... envVars) throws IOException {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    Map<String, String> env = addEnvProperties(envVars);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TIMEOUT);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(new PumpStreamHandler());
    int result = executor.execute(cmdLine, env);
    if (executor.isFailure(result)) {
        if (watchDog.killedProcess()) {
            throw new RuntimeException("Reached timeout while running: " + cmdLine);
        }/* ww w.ja  va 2  s .  c om*/
        throw new RuntimeException("Process failed with return code [" + result + "]: " + cmdLine);
    }
    return result;
}

From source file:org.mule.test.infrastructure.process.UnixController.java

@Override
public int getProcessId() {
    Map<Object, Object> newEnv = this.copyEnvironmentVariables();
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    if (this.doExecution(executor, new CommandLine(this.muleBin).addArgument("status"), newEnv) == 0) {
        Matcher matcher = STATUS_PATTERN.matcher(outputStream.toString());
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        } else {//  www. ja  va  2s  .com
            throw new MuleControllerException("bin/mule status didn't return the expected pattern: " + STATUS);
        }
    } else {
        throw new MuleControllerException("Mule ESB is not running");
    }
}

From source file:org.mybatis.generator.ext.api.MeldMergeShellCallback.java

public static boolean exec(String command) {
    CommandLine commandLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = DefaultExecutor.INVALID_EXITVALUE;
    ExecuteWatchdog watchdog = new ExecuteWatchdog(2000);
    executor.setWatchdog(watchdog);
    try {//  www . ja v  a2s .  com
        exitValue = executor.execute(commandLine);
    } catch (ExecuteException e) {
        exitValue = e.getExitValue();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
    System.out.println("Exit :" + exitValue);
    return (exitValue == 0);
}

From source file:org.nanoko.playframework.mojo.AbstractPlay2SimpleMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    String line = this.getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    this.addCommandLineArgs(cmdLine);

    DefaultExecutor executor = new DefaultExecutor();
    if (this.timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(this.timeout);
        executor.setWatchdog(watchdog);
    }/*w w  w .  ja  va 2s  . c om*/

    executor.setExitValue(0);
    executor.setWorkingDirectory(this.project.getBasedir());
    try {
        executor.execute(cmdLine, this.getEnvironment());
    } catch (Exception e) {
        this.onExecutionException(e);
    }
}

From source file:org.nanoko.playframework.mojo.Play2TestMojo.java

public void execute() throws MojoExecutionException {

    if (isSkipExecution()) {
        getLog().info("Test phase skipped");
        return;//from  w w  w.j  a v  a2  s  . c o m
    }

    if (noTestFound()) {
        getLog().info("Test phase skipped - no tests found");
        return;
    }

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("test");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    executor.setWorkingDirectory(project.getBasedir());

    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        if (testFailureIgnore) {
            getLog().error("Test execution failures ignored");
        } else {
            throw new MojoExecutionException("Error during compilation", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.FPCCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    FPCCompiler.logger.debug("Compiling {} to {} using FPC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("ppcx64");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-o" + outputFile.toAbsolutePath().toString()); // Set
    // outuput// w w  w  .j ava 2 s  .  c o m
    // file
    commandLine.addArgument("-l-");
    commandLine.addArgument("-v0");
    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input
    // files

    FPCCompiler.logger.debug("Running FPC with arguments: {}", commandLine.toString());

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(errorStream, null, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        FPCCompiler.logger.error("Could not execute FPC: {}", e);
        throw new CompilationException("Could not execute FPC", e);
    }
    switch (result) {
    case 0:
        return;
    case 1:
        try {
            final String errorString = errorStream.toString("UTF-8");

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.getFileName().toString()))
                            .collect(Collectors.joining("|")) + ")",
                    Pattern.MULTILINE);

            FPCCompiler.logger.debug("Compilation error: {}", errorString);

            throw new CompilerError("fpc.wrote.stdout", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.GNUCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    GNUCompiler.logger.debug("Compiling {} to {} using GCC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("g++");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-w"); // Prohibit warnings because they screw
    // up error detection

    commandLine.addArgument("-o");
    commandLine.addArgument(MessageFormat.format("\"{0}\"", outputFile.toAbsolutePath().toString())); // Set outuput file

    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input/*from  w w w .  j a va2s .  c o  m*/
    // files

    GNUCompiler.logger.debug("Running GCC with arguments: {}", Arrays.asList(commandLine.getArguments()));

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        GNUCompiler.logger.error("Could not execute GCC: {}", e);
        throw new CompilationException("Could not execute GCC", e);
    }

    switch (result) {
    case 0:
        return;
    case 1:
        try {
            String errorString = errorStream.toString(StandardCharsets.UTF_8.name());

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString()))
                            .collect(Collectors.joining("|")) + "):",
                    Pattern.MULTILINE);
            errorString = pattern.matcher(errorString).replaceAll("");

            GNUCompiler.logger.debug("Compilation error: {}", errorString);
            throw new CompilerError("gcc.wrote.stderr", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.JavaCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException, IOException {

    FileAccess.createDirectories(outputFile);

    final CommandLine commandLine = new CommandLine("javac");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-d");
    commandLine.addArgument(outputFile.toAbsolutePath().toString());

    commandLine.addArgument("-nowarn"); // Prohibit warnings because they
    // screw/*from  w  w  w  .  j  a  v  a2  s  .c om*/
    // up error detection

    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input
    // files

    JavaCompiler.logger.info("Running javac with arguments: {}", Arrays.asList(commandLine.getArguments()));

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        JavaCompiler.logger.error("Could not execute javac: {}", e);
        throw new CompilationException("Could not execute javac", e);
    }

    switch (result) {
    case 0:
        return;
    case 1:
        try {
            String errorString = errorStream.toString("UTF-8");
            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString()))
                            .collect(Collectors.joining("|")) + "):",
                    Pattern.MULTILINE);
            errorString = pattern.matcher(errorString).replaceAll("");

            JavaCompiler.logger.debug("Compilation error: {}", errorString);

            throw new CompilerError("javac.wrote.stderr", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.executors.JavaExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {

    final Path chrootRoot = this.storage.getPath().resolve("chroot");

    final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString());

    FileAccess.createDirectories(chrootedProgram);
    FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES);

    final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory");

    final Path policyFile = this.storage.getPath().resolve("olymp.policy");

    try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) {
        paths.forEach(path -> {/*w  ww.  j av  a2 s. co  m*/
            try {
                Files.setPosixFilePermissions(path,
                        new HashSet<PosixFilePermission>(
                                Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                                        PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE,
                                        PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE,
                                        PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    this.buildPolicy(chrootRoot, policyFile);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument("--security=0");
    commandLine.addArgument("--jail=/");

    commandLine.addArgument("--");

    commandLine.addArgument("/usr/bin/java");

    commandLine.addArgument("-classpath");
    commandLine.addArgument(chrootedProgram.toAbsolutePath().toString());
    commandLine.addArgument("-Djava.security.manager");
    commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString());

    commandLine.addArgument("-Xmx" + this.getMemoryLimit());
    commandLine.addArgument("-Xms" + this.getMemoryLimit());

    commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}",
            outOfMemoryFile.toAbsolutePath().toString()), false);

    commandLine.addArgument("Main");

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete
    executor.setWorkingDirectory(chrootRoot.toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));
    try {
        executor.execute(commandLine);
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }
    final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt"));

    if (FileAccess.exists(outOfMemoryFile)) {
        readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT);
    }

    readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit());

    return readOlrunnerVerdict;
}

From source file:org.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java

private static String callNativeId(boolean group) throws IOException {
    OpenOlympusWatchdogExecutor.ensureUserAndGroupExists();

    final CommandLine commandLine = new CommandLine("id");
    commandLine.addArgument(group ? "-g" : "-u");
    commandLine.addArgument("olympuswatchdogchild");

    final DefaultExecutor executor = new DefaultExecutor();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    executor.setStreamHandler(new PumpStreamHandler(out));

    executor.setWatchdog(new ExecuteWatchdog(1000));

    try {//w ww. java 2  s. c  om
        executor.execute(commandLine);

        return out.toString(StandardCharsets.UTF_8.name());
    } catch (final ExecuteException e) {
        throw new ExecuteException(
                "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?",
                e.getExitValue(), e);
    }
}