Example #1
0
  private int checkAgentStatus() throws Exception {
    log.debug("Checking RHQ agent status");

    File agentBinDir = new File(getAgentBasedir(), "bin");

    org.apache.commons.exec.CommandLine commandLine = getCommandLine("rhq-agent-wrapper", "status");
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(agentBinDir);
    executor.setStreamHandler(new PumpStreamHandler());

    int rValue;
    try {
      rValue = executor.execute(commandLine);
    } catch (ExecuteException e) {
      // For windows the JSW exit code for a status check is expected to be a mask value and the
      // agent wrapper
      // .bat will return it explicitly.  We can ignore it and assume that the logged output is
      // sufficient.
      // See http://wrapper.tanukisoftware.com/doc/english/launch-win.html#standalone-status
      if (!isWindows()) {
        // UNIX script will exit with 1 if its not running, this is expected, so don't throw
        // exception on 1
        if (e.getExitValue() != 1) {
          throw e;
        }
      }
      rValue = e.getExitValue();
      if (rValue == RHQControl.EXIT_CODE_OK) {
        // if somehow we were told it was OK, change it to unknown since it can't be OK
        rValue = RHQControl.EXIT_CODE_STATUS_UNKNOWN;
      }
    }

    return rValue;
  }
Example #2
0
  private int checkStorageStatus(boolean isColorSupported) throws Exception {
    log.debug("Checking RHQ storage node status");

    int rValue = RHQControl.EXIT_CODE_OK;

    if (isWindows()) {
      Executor executor = new DefaultExecutor();
      executor.setStreamHandler(new PumpStreamHandler());
      org.apache.commons.exec.CommandLine commandLine;
      executor.setWorkingDirectory(getBinDir());
      commandLine = getCommandLine("rhq-storage", "status");
      try {
        rValue = executor.execute(commandLine);
      } catch (ExecuteException ee) {
        log.debug("Failed to check storage service status", ee);
        rValue = ee.getExitValue();
        if (rValue == RHQControl.EXIT_CODE_OK) {
          // if somehow we were told it was OK, change it to unknown since it can't be OK
          rValue = RHQControl.EXIT_CODE_STATUS_UNKNOWN;
        }
      } catch (Exception e) {
        log.debug("Failed to check storage service status", e);
        rValue = RHQControl.EXIT_CODE_STATUS_UNKNOWN;
      }
    } else {
      final String ANSI_RED = "\u001B[31m";
      final String ANSI_GREEN = "\u001B[32m";
      final String ANSI_RESET = "\u001B[0m";
      if (isStorageRunning()) {
        System.out.println(
            String.format("%-30s", "RHQ Storage Node")
                + " (pid "
                + String.format("%-7s", getStoragePid())
                + ") is "
                + (isColorSupported ? ANSI_GREEN : "")
                + "\u2714running"
                + (isColorSupported ? ANSI_RESET : ""));
      } else {
        System.out.println(
            String.format("%-30s", "RHQ Storage Node")
                + " (no pid file) is "
                + (isColorSupported ? ANSI_RED : "")
                + "\u2718down"
                + (isColorSupported ? ANSI_RESET : ""));
        rValue = RHQControl.EXIT_CODE_STATUS_NOT_RUNNING;
      }
    }
    return rValue;
  }
 public void onProcessFailed(ExecuteException e) {
   super.onProcessFailed(e);
   if (watchdog != null && watchdog.killedProcess())
     System.err.println("[resultHandler] The Syntren launcher process timed out");
   else
     System.err.println(
         "[resultHandler] The Syntren laucher process failed to do: " + e.getMessage());
 }
Example #4
0
  protected boolean isUnixPidRunning(String pid) {
    try {
      Integer numericPid = Integer.valueOf(pid);
    } catch (NumberFormatException e) {
      // PID wasn't numeric, it can't be correct
      return false;
    }

    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(getBinDir());
    PumpStreamHandler streamHandler =
        new PumpStreamHandler(createNullOutputStream(), createNullOutputStream());
    executor.setStreamHandler(streamHandler);
    org.apache.commons.exec.CommandLine commandLine;
    commandLine =
        new org.apache.commons.exec.CommandLine("kill").addArgument("-0").addArgument(pid);

    boolean isRunning = true; // assume it is running
    try {
      int code = executor.execute(commandLine);
      if (code != 0) {
        isRunning = false;
      }
    } catch (ExecuteException ee) {
      log.debug(
          "kill -0 for pid ["
              + pid
              + "] threw exception with exit value ["
              + ee.getExitValue()
              + "]");
      if (ee.getExitValue() == 1) {
        // return code 1 means process does not exist
        isRunning = false;
      }
    } catch (IOException e) {
      log.error(
          "Checking for running process failed. Will assume it is running. Error: "
              + e.getMessage());
    }

    log.debug("unix pid [" + pid + "] " + ((isRunning) ? "is" : "is NOT") + " running");
    return isRunning;
  }
Example #5
0
  /**
   * Execute a command line in with a given map of environment settings. The execution outupt is
   * filtered unless verbose is set to true.
   *
   * @param cmdLine The command to execute
   * @param env Environment settings available for the command execution
   * @return the command's execution exit code, or -2 if the command failed to execute
   */
  private int executeRecipe(final CommandLine cmdLine, final Map<Object, Object> env) {
    final DefaultExecutor executor = new DefaultExecutor();

    // The watchdog will terminate the process if it does not end within the
    // specified timeout
    final int externalProcessTimeout = (this.timeout + EXTERNAL_PROCESS_WATCHDOG_TIMEOUT) * 1000;
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(externalProcessTimeout);
    executor.setWatchdog(watchdog);

    executor.setExitValue(0);
    int result = -1;

    PipedInputStream in = null;
    PipedOutputStream out = null;
    BufferedReader reader = null;
    try {
      in = new PipedInputStream();
      out = new PipedOutputStream(in);
      reader = new BufferedReader(new InputStreamReader(in));

      final Thread thread = new Thread(new FilteredOutputHandler(reader, this.verbose));
      thread.setDaemon(true);
      thread.start();

      final PumpStreamHandler psh = new PumpStreamHandler(out, out);
      executor.setStreamHandler(psh);
      result = executor.execute(cmdLine, env);
    } catch (final ExecuteException e) {
      logger.log(
          Level.SEVERE,
          "A problem was encountered while executing the recipe: " + e.getMessage(),
          e);
    } catch (final IOException e) {
      logger.log(
          Level.SEVERE,
          "An IO Exception was encountered while executing the recipe: " + e.getMessage(),
          e);
      result = -2;
    }

    return result;
  }
Example #6
0
  private int checkServerStatus() throws Exception {
    log.debug("Checking RHQ server status");

    org.apache.commons.exec.CommandLine commandLine = getCommandLine("rhq-server", "status");
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(getBinDir());
    executor.setStreamHandler(new PumpStreamHandler());

    int rValue;
    try {
      rValue = executor.execute(commandLine);
    } catch (ExecuteException ee) {
      rValue = ee.getExitValue();
      if (rValue == RHQControl.EXIT_CODE_OK) {
        // if somehow we were told it was OK, change it to unknown since it can't be OK
        rValue = RHQControl.EXIT_CODE_STATUS_UNKNOWN;
      }
    }
    return rValue;
  }
Example #7
0
  /**
   * Executes a CommandLine, throwing an exception if anything fails.
   *
   * @param session
   * @param command
   * @param executor
   * @param environment
   * @throws MojoExecutionException
   */
  @SuppressWarnings("rawtypes")
  public static void execute(
      MavenSession session, CommandLine command, Executor executor, Map environment)
      throws MojoExecutionException {
    if (executor == null) {
      executor = getDefaultExecutor(session);
    }
    int status = 0;
    try {
      status = executor.execute(command, environment);
    } catch (ExecuteException e) {
      status = e.getExitValue();
    } catch (IOException e) {
      status = 1;
    }

    if (status != 0) {
      throw new MojoExecutionException("Execution of command failed.");
    }
  }
Example #8
0
  public void runScript(String command) {
    sCommandString = command;
    CommandLine oCmdLine = CommandLine.parse(sCommandString);

    oCmdLine.addArgument("sanga.txt");

    DefaultExecutor oDefaultExecutor = new DefaultExecutor();
    // oDefaultExecutor.setWorkingDirectory(new File(command.getWorkingDir()).getAbsoluteFile());
    // oDefaultExecutor.setExitValue(1);
    try {
      oDefaultExecutor.setWorkingDirectory(new File("/Users/212433329/bharshell"));
      iExitValue = oDefaultExecutor.execute(oCmdLine);
    } catch (ExecuteException e) {
      // TODO Auto-generated catch block
      System.err.println("Execution failed.");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      System.err.println("permission denied.");
      e.printStackTrace();
    }
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  protected int _exec() {
    int returnValue = 0;
    CommandLine cmdLine = getCommandLine();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ScriptExecuteWatchdog();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWorkingDirectory(currentDir);
    executor.setWatchdog(watchdog);
    if (terminal != null) {
      ExecuteStreamHandler monitorStreamHandler =
          new PumpStreamHandler(terminal.getOutputStream(), terminal.getErrorStream());
      executor.setStreamHandler(monitorStreamHandler);
    } else {
      ExecuteStreamHandler silentStreamHandler = new PumpStreamHandler();
      executor.setStreamHandler(silentStreamHandler);
    }

    Map procEnvironment = null;
    if (environment != null) {
      try {
        procEnvironment = EnvironmentUtils.getProcEnvironment();
        procEnvironment.putAll(environment);
      } catch (IOException e) {
        logger.error(e.getMessage());
        procEnvironment = null;
      }
    }

    try {
      executor.execute(cmdLine, procEnvironment, resultHandler);
      notifyStart();
    } catch (Exception e) {
      logger.warn("[EXECUTOR] ERROR: {}", e.getMessage());

      notifyError(-1, e.getMessage());

      return 1;
    }

    try {
      if (resultHandler.hasResult()) {
        notifyRefresh();
      } else {
        logger.info("[EXECUTOR] RUNNING");
        while (!resultHandler.hasResult()) {
          resultHandler.waitFor(PrefUtil.getInt(PrefUtil.SCRIPT_RUN_REFRESH_TIME, 1000));
          notifyRefresh();
        }
      }
    } catch (InterruptedException e) {
      logger.warn("[EXECUTOR] INTERRUPTED");
      watchdog.destroyProcess();
    } finally {
      if (watchdog.killedProcess()) {
        logger.warn("[EXECUTOR] WAITING FOR KILL");
        try {
          resultHandler.waitFor(PrefUtil.getInt(PrefUtil.SCRIPT_WAIT_FOR_KILL_REFRESH_TIME, 5000));
        } catch (InterruptedException e) {
          logger.warn("[EXECUTOR] INTERRUPTED: {}", e.getMessage());
          notifyError(-1, e.getMessage());
        }
      }
      try {
        ExecuteException exception = resultHandler.getException();
        if (exception != null) {
          returnValue = resultHandler.getExitValue();
          logger.warn("[EXECUTOR] ERROR: {}", exception.getMessage());

          if (terminal != null) {
            // String error = terminal.getErrorStream().peekLines();
            // notifyError(returnValue, error);
            // error is empty
            notifyError(returnValue, exception.getMessage());
          } else {
            notifyError(returnValue, exception.getMessage());
          }
          service.shutdownNow();
        } else {
          returnValue = resultHandler.getExitValue();
          logger.info("[EXECUTOR] FINISH: {}", returnValue);
          notifyFinish(resultHandler.getExitValue());
        }
      } catch (IllegalStateException e) {
        returnValue = -1;
        logger.warn("[EXECUTOR] INTERRUPTED: {}", e.getMessage());
        notifyError(returnValue, e.getMessage());
      }
    }
    if (!keepFileOnEnd) {
      internalDeleteOnEnd();
    }

    return returnValue;
  }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {

    try {
      File outputDir = getOutputDirectory().getCanonicalFile();
      if (!outputDir.exists()) {
        Files.createDirectories(outputDir.toPath());
      }
    } catch (IOException e) {
      throw new MojoFailureException(e.getMessage(), e);
    }

    CommandLine cl = new CommandLine("java");

    String cp = "";
    for (Object classpathElement : getClassPathElements()) {
      cp = cp + File.pathSeparator + classpathElement;
    }
    cp = cp + File.pathSeparator + getOutputDirectory().getAbsolutePath();

    cl.addArgument("-cp").addArgument(cp);

    cl.addArgument("frege.compiler.Main");
    cl.addArgument("-sp").addArgument(getSourcePath());

    // output dir
    cl.addArgument("-d").addArgument(getOutputDirectory().getAbsolutePath());

    if (hints) {
      cl.addArgument("-hints");
    }
    if (inline) {
      cl.addArgument("-inline");
    }
    if (make) {
      cl.addArgument("-make");
    }
    if (verbose) {
      cl.addArgument("-v");
    }
    if (skipCompile) {
      cl.addArgument("-j");
    }

    // source files
    final Set<File> sourceFiles = getSourceFiles();

    if (sourceFiles.isEmpty()) {
      getLog().info("No files to compile, skipping...");
    } else {

      for (File sourceFile : sourceFiles) {
        cl.addArgument(sourceFile.getAbsolutePath());
      }

      getLog().debug("Command line: " + cl.toString());

      Executor exec = new DefaultExecutor();
      Map<String, String> env = new HashMap<>(System.getenv());
      ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
      exec.setStreamHandler(handler);

      int status;
      try {
        status = exec.execute(cl, env);
      } catch (ExecuteException e) {
        status = e.getExitValue();
      } catch (IOException e) {
        status = 1;
      }

      if (status != 0) {
        throw new MojoExecutionException("Frege compilation failed.");
      }
    }
  }