Пример #1
0
  /**
   * Create user on the system. Synchronized to prevent multiple threads from trying to create user
   * at the same time.
   *
   * @param user user id
   * @param group group id
   * @throws GenieException If there is any problem.
   */
  protected synchronized void createUser(final String user, final String group)
      throws GenieException {

    // First check if user already exists
    final CommandLine idCheckCommandLine =
        new CommandLine("id").addArgument("-u").addArgument(user);

    try {
      this.executor.execute(idCheckCommandLine);
      log.debug("User already exists");
    } catch (final IOException ioe) {
      log.debug("User does not exist. Creating it now.");

      // Determine if the group is valid by checking that its not null and not same as user.
      final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user);

      // Create the group for the user if its not the same as the user.
      if (isGroupValid) {
        log.debug("Group and User are different so creating group now.");
        final CommandLine groupCreateCommandLine =
            new CommandLine("sudo").addArgument("groupadd").addArgument(group);

        // We create the group and ignore the error as it will fail if group already exists.
        // If the failure is due to some other reason, then user creation will fail and we catch
        // that.
        try {
          log.debug(
              "Running command to create group:  [" + groupCreateCommandLine.toString() + "]");
          this.executor.execute(groupCreateCommandLine);
        } catch (IOException ioexception) {
          log.debug("Group creation threw an error as it might already exist");
        }
      }

      final CommandLine userCreateCommandLine =
          new CommandLine("sudo").addArgument("useradd").addArgument(user);
      if (isGroupValid) {
        userCreateCommandLine.addArgument("-G").addArgument(group);
      }
      userCreateCommandLine.addArgument("-M");

      try {
        log.debug("Running command to create user: [" + userCreateCommandLine.toString() + "]");
        this.executor.execute(userCreateCommandLine);
      } catch (IOException ioexception) {
        throw new GenieServerException(
            "Could not create user " + user + " with exception " + ioexception);
      }
    }
  }
Пример #2
0
  public static String sync_getVerificationOutput(
      String lolaBinPath,
      String modelToVerify,
      String propertyToVerify,
      boolean useCoverabilitySearch,
      final int timeoutInSeconds)
      throws Exception {

    int cores = Runtime.getRuntime().availableProcessors();
    String filePath =
        System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola";
    IOUtils.writeFile(modelToVerify.getBytes(), filePath, false);
    // IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = new CommandLine(lolaBinPath);

    cmdLine.addArgument("--nolog");

    // cmdLine.addArgument("--formula="+filePath+".ctl", false);
    cmdLine.addArgument("--formula=" + propertyToVerify, false);
    cmdLine.addArgument("--threads=" + cores);
    if (useCoverabilitySearch) cmdLine.addArgument("--search=cover");
    cmdLine.addArgument("-p");
    // cmdLine.addArgument("--path=\""+filePath+".out\"", false);
    // cmdLine.addArgument("--state=\""+filePath+".out\"", false);
    cmdLine.addArgument(filePath, false);

    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds);

    exec.setWatchdog(watchdog);
    exec.setStreamHandler(streamHandler);
    exec.setExitValues(new int[] {0, 1, 2, 139, 35584});
    int exitVal = exec.execute(cmdLine);

    String output = outputStream.toString();

    if (watchdog.killedProcess())
      throw new Exception(
          "ERROR: Timeout occurred. LOLA has reached the execution time limit of "
              + timeoutInSeconds
              + " seconds, so it has been aborted.\nPartial Output:\n"
              + output);

    if (exitVal != 0 || output.equals("") || output.contains("aborting [#"))
      throw new Exception(
          "ERROR: LOLA internal error\nExit code:"
              + exitVal
              + "\nExec: "
              + cmdLine.toString()
              + "\nOutput:\n"
              + output);
    new File(filePath).delete();
    return output;
  }
Пример #3
0
  /**
   * @param printJobTimeout the printJobTimeout (ms) before the watchdog terminates the print
   *     process
   * @param printInBackground printing done in the background or blocking
   * @param streamHandler
   * @return a print result handler (implementing a future)
   * @throws IOException the test failed
   */
  public static PrintResultHandler executeProgram(
      CommandLine commandLine,
      String workingDirectory,
      long printJobTimeout,
      boolean printInBackground,
      int successExitValue,
      ExecuteStreamHandler streamHandler)
      throws IOException {
    ExecuteWatchdog watchdog = null;
    PrintResultHandler resultHandler;

    // Create the executor and consider the successExitValue as success
    Executor executor = new DefaultExecutor();
    executor.setExitValue(successExitValue);

    if (StringHelper.isNotEmpty(workingDirectory)) {
      executor.setWorkingDirectory(new File(workingDirectory));
    }

    // Redirect streams if needed
    if (streamHandler != null) {
      executor.setStreamHandler(streamHandler);
    }

    // Create a watchdog if requested
    if (printJobTimeout > 0) {
      watchdog = new ExecuteWatchdog(printJobTimeout);
      executor.setWatchdog(watchdog);
    }

    // Pass a "ExecuteResultHandler" when doing background printing
    if (printInBackground) {
      log.debug(String.format("Executing non-blocking process %s", commandLine.toString()));
      resultHandler = new PrintResultHandler(watchdog);
      executor.execute(commandLine, resultHandler);
    } else {
      log.debug(String.format("Executing blocking process %s", commandLine.toString()));
      successExitValue = executor.execute(commandLine);
      resultHandler = new PrintResultHandler(successExitValue);
    }

    return resultHandler;
  }
  public int retrievePageCount(File source) {

    File target =
        new File(
            System.getProperty("java.io.tmpdir"),
            FilenameUtils.removeExtension(source.getName()) + ".pdf");

    Map<String, Object> args = newHashMap();
    args.put("source", source);
    args.put("targetDir", target.getParentFile());

    CommandLine cmd = new CommandLine("loffice");
    cmd.addArgument("--headless");
    cmd.addArgument("--convert-to");
    cmd.addArgument("pdf");
    cmd.addArgument("--outdir");
    cmd.addArgument("${targetDir}");
    cmd.addArgument("${source}");
    cmd.setSubstitutionMap(args);

    try {
      DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

      ExecuteWatchdog watchdog = new ExecuteWatchdog(10L * 1000L);
      executor.setWatchdog(watchdog);
      logger.trace("About to execute command {}", cmd.toString());
      executor.execute(cmd, resultHandler);

      resultHandler.waitFor();
      final int exitValue = resultHandler.getExitValue();

      if (exitValue != 0) {
        logger.error(
            "Unable to convert Microsoft Word file {} to PDF. Exit code = {}",
            source.getAbsolutePath(),
            exitValue);
        return -1;
      }
      final int pageCount = pdfDocumentInspector.retrievePageCount(target);
      deleteFileIfNeeded(target);
      return pageCount;

    } catch (IOException | InterruptedException e) {
      logger.error("Unable to create a PDF from {}", source.getAbsolutePath(), e);
      deleteFileIfNeeded(target);
      return -1;
    }
  }
Пример #5
0
  public String getDockerHostIpAddress(Map<String, String> environment) {
    String ipAddress = LOCALHOST; // Default of localhost
    String dockerMachineName = getDockerMachineName(environment);

    if (!dockerMachineName.isEmpty()) {
      LOG.debug("Docker machine name = " + dockerMachineName);
      CommandLine commandline = CommandLine.parse(DOCKER_MACHINE_IP);
      commandline.addArgument(dockerMachineName);
      LOG.debug("Running exec: " + commandline.toString());
      try {
        ipAddress = StringUtils.strip(runCommand(commandline));
      } catch (IOException e) {
        LOG.error("Unable to run exec command to find ip address.", e);
      }
    } else {
      ipAddress = getDocker0AdapterIPAddress();
    }
    LOG.debug("Returned IP address: " + ipAddress);
    return ipAddress;
  }
  public String toString() {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
      final String arg = args.get(i);
      final Boolean isFile = argIsFile.get(i);
      if (isFile) {
        String key = "file" + fileNumber;
        map.put(key, new File(arg));
        cmdLine.addArgument("${" + key + "}", false);
        fileNumber++;
      } else {
        cmdLine.addArgument(arg);
      }
    }
    cmdLine.setSubstitutionMap(map);
    return cmdLine.toString();
  }
Пример #7
0
  public int 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);
    }

    ExecuteWatchdog 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());
    return exec.execute(cmd);
  }
Пример #8
0
  public static boolean executeProgram(
      CommandLine commandLine,
      String workingDirectory,
      boolean executeInBackground,
      int successExitValue,
      OutputStream outputStream) {
    long printJobTimeout = PRINT_JOB_TIMEOUT;

    ExecuteStreamHandler streamHandler = null;
    if (outputStream != null) {
      streamHandler = new PumpStreamHandler(outputStream);
    }

    PrintResultHandler printResult = null;
    try {
      log.debug(String.format("Preparing to start process %s", commandLine.toString()));
      printResult =
          executeProgram(
              commandLine,
              workingDirectory,
              printJobTimeout,
              executeInBackground,
              successExitValue,
              streamHandler);
      log.debug(String.format("Successfully start process %s", commandLine.toString()));
    } catch (Exception ex) {
      log.trace(String.format("Problem during starting process %s", commandLine.toString()), ex);
      ex.printStackTrace();
      return false;
    }

    // come back to check the print result
    log.debug(String.format("Waiting for the proces %s finish", commandLine.toString()));
    try {
      if (printResult == null) {
        return false;
      }
      printResult.waitFor();
    } catch (InterruptedException ex) {
      log.error(String.format("Problem during process execution %s", commandLine.toString()), ex);
    }

    log.debug(String.format("Process %s has finished", commandLine.toString()));

    return true;
  }
  public static CommandExecutorResult execute(String commandString, int expectedExitValue)
      throws Exception {
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    ByteArrayOutputStream stout = new ByteArrayOutputStream();
    CommandLine cmd = CommandLine.parse(commandString);
    try {
      DefaultExecutor executor = new DefaultExecutor();
      executor.setExitValue(expectedExitValue);
      executor.setStreamHandler(new PumpStreamHandler(stout, error));
      // if exit value != expectedExitValue => Exception
      int exitValue = executor.execute(cmd);
      return new CommandExecutorResult(exitValue, stout.toString(), error.toString());

    } catch (Exception e) {
      int exitValue = -1;
      if (e instanceof ExecuteException) {
        exitValue = ((ExecuteException) e).getExitValue();
      }
      throw new CommandExecutorException(
          "error in command " + cmd.toString(),
          new CommandExecutorResult(exitValue, stout.toString(), error.toString()));
    }
  }
  @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.");
      }
    }
  }