Пример #1
0
  /** {@inheritDoc} */
  @Override
  public void addTaskAttributes(List<RawAttribute> attributes) {
    // Required attributes
    attributes.add(new LDAPAttribute(ATTR_TASK_EXPORT_LDIF_FILE, ldifFile.getValue()));
    attributes.add(new LDAPAttribute(ATTR_TASK_EXPORT_BACKEND_ID, backendID.getValue()));

    // Optional attributes
    addAttribute(attributes, ATTR_TASK_EXPORT_APPEND_TO_LDIF, appendToLDIF);
    addAttribute(attributes, ATTR_TASK_EXPORT_COMPRESS_LDIF, compressLDIF);
    addAttribute(attributes, ATTR_TASK_EXPORT_ENCRYPT_LDIF, encryptLDIF);
    addAttribute(attributes, ATTR_TASK_EXPORT_SIGN_HASH, signHash);
    addAttribute(
        attributes, ATTR_TASK_EXPORT_INCLUDE_ATTRIBUTE, includeAttributeStrings.getValues());
    addAttribute(
        attributes, ATTR_TASK_EXPORT_EXCLUDE_ATTRIBUTE, excludeAttributeStrings.getValues());
    addAttribute(attributes, ATTR_TASK_EXPORT_INCLUDE_FILTER, includeFilterStrings.getValues());
    addAttribute(attributes, ATTR_TASK_EXPORT_EXCLUDE_FILTER, excludeFilterStrings.getValues());
    addAttribute(attributes, ATTR_TASK_EXPORT_INCLUDE_BRANCH, includeBranchStrings.getValues());
    addAttribute(attributes, ATTR_TASK_EXPORT_EXCLUDE_BRANCH, excludeBranchStrings.getValues());
    addAttribute(attributes, ATTR_TASK_EXPORT_WRAP_COLUMN, wrapColumn);

    if (excludeOperationalAttrs.isPresent()) {
      attributes.add(new LDAPAttribute(ATTR_TASK_EXPORT_INCLUDE_OPERATIONAL_ATTRIBUTES, "false"));
    }
  }
 /**
  * Commodity method that retrieves the password value analyzing the contents of a string argument
  * and of a file based argument. It assumes that the arguments have already been parsed and
  * validated. If the string is a dash, or no password is available, it will prompt for it on the
  * command line.
  *
  * @param bindPassword the string argument for the password.
  * @param bindPasswordFile the file based argument for the password.
  * @param bindDNValue the string value for the bindDN.
  * @param out stream to write message.
  * @param err stream to write error message.
  * @return the password value.
  * @throws ClientException if the password cannot be read
  */
 public static String getPasswordValue(
     StringArgument bindPassword,
     FileBasedArgument bindPasswordFile,
     String bindDNValue,
     PrintStream out,
     PrintStream err)
     throws ClientException {
   String bindPasswordValue = bindPassword.getValue();
   if ("-".equals(bindPasswordValue)
       || (!bindPasswordFile.isPresent() && bindDNValue != null && bindPasswordValue == null)) {
     // read the password from the stdin.
     out.print(INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDNValue));
     char[] pwChars = ConsoleApplication.readPassword();
     // As per rfc 4513(section-5.1.2) a client should avoid sending
     // an empty password to the server.
     while (pwChars.length == 0) {
       printWrappedText(err, INFO_LDAPAUTH_NON_EMPTY_PASSWORD.get());
       out.print(INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDNValue));
       pwChars = ConsoleApplication.readPassword();
     }
     return new String(pwChars);
   } else if (bindPasswordValue == null) {
     // Read from file if it exists.
     return bindPasswordFile.getValue();
   }
   return bindPasswordValue;
 }
 /**
  * Commodity method that retrieves the password value analyzing the contents of a string argument
  * and of a file based argument. It assumes that the arguments have already been parsed and
  * validated. If the string is a dash, or no password is available, it will prompt for it on the
  * command line.
  *
  * @param bindPwdArg the string argument for the password.
  * @param bindPwdFileArg the file based argument for the password.
  * @param bindDnArg the string argument for the bindDN.
  * @param out stream to write message.
  * @param err stream to write error message.
  * @return the password value.
  */
 public static String getPasswordValue(
     StringArgument bindPwdArg,
     FileBasedArgument bindPwdFileArg,
     StringArgument bindDnArg,
     PrintStream out,
     PrintStream err) {
   try {
     return getPasswordValue(bindPwdArg, bindPwdFileArg, bindDnArg.getValue(), out, err);
   } catch (Exception ex) {
     printWrappedText(err, ex.getMessage());
     return null;
   }
 }
Пример #4
0
  /**
   * Processes the command-line arguments and invokes the export process.
   *
   * @param args The command-line arguments provided to this program.
   * @param initializeServer Indicates whether to initialize the server.
   * @return The error code.
   */
  public int process(String[] args, boolean initializeServer) {
    if (initializeServer) {
      DirectoryServer.bootstrapClient();
    }
    JDKLogging.disableLogging();

    // Create the command-line argument parser for use with this program.
    LDAPConnectionArgumentParser argParser =
        new LDAPConnectionArgumentParser(
            "org.opends.server.tools.TaskInfo",
            INFO_TASKINFO_TOOL_DESCRIPTION.get(),
            false,
            null,
            alwaysSSL);
    argParser.setShortToolDescription(REF_SHORT_DESC_MANAGE_TASKS.get());

    // Initialize all the command-line argument types and register them with the
    // parser.
    try {

      StringArgument propertiesFileArgument =
          new StringArgument(
              "propertiesFilePath",
              null,
              OPTION_LONG_PROP_FILE_PATH,
              false,
              false,
              true,
              INFO_PROP_FILE_PATH_PLACEHOLDER.get(),
              null,
              null,
              INFO_DESCRIPTION_PROP_FILE_PATH.get());
      argParser.addArgument(propertiesFileArgument);
      argParser.setFilePropertiesArgument(propertiesFileArgument);

      BooleanArgument noPropertiesFileArgument =
          new BooleanArgument(
              "noPropertiesFileArgument",
              null,
              OPTION_LONG_NO_PROP_FILE,
              INFO_DESCRIPTION_NO_PROP_FILE.get());
      argParser.addArgument(noPropertiesFileArgument);
      argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);

      task =
          new StringArgument(
              "info",
              'i',
              "info",
              false,
              true,
              INFO_TASK_ID_PLACEHOLDER.get(),
              INFO_TASKINFO_TASK_ARG_DESCRIPTION.get());
      argParser.addArgument(task);

      cancel =
          new StringArgument(
              "cancel",
              'c',
              "cancel",
              false,
              true,
              INFO_TASK_ID_PLACEHOLDER.get(),
              INFO_TASKINFO_TASK_ARG_CANCEL.get());
      argParser.addArgument(cancel);

      summary =
          new BooleanArgument(
              "summary", 's', "summary", INFO_TASKINFO_SUMMARY_ARG_DESCRIPTION.get());
      argParser.addArgument(summary);

      noPrompt = CommonArguments.getNoPrompt();
      argParser.addArgument(noPrompt);

      BooleanArgument displayUsage = CommonArguments.getShowUsage();
      argParser.addArgument(displayUsage);
      argParser.setUsageArgument(displayUsage);
    } catch (ArgumentException ae) {
      LocalizableMessage message = ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
      println(message);
      return 1;
    }

    try {
      argParser.getArguments().initArgumentsWithConfiguration();
    } catch (ConfigException ce) {
      // Ignore.
    }

    // Parse the command-line arguments provided to this program.
    try {
      argParser.parseArguments(args);
      StaticUtils.checkOnlyOneArgPresent(task, summary, cancel);
    } catch (ArgumentException ae) {
      LocalizableMessage message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
      println(message);
      println(argParser.getUsageMessage());
      return 1;
    }

    if (!argParser.usageOrVersionDisplayed()) {
      // Checks the version - if upgrade required, the tool is unusable
      try {
        BuildVersion.checkVersionMismatch();
      } catch (InitializationException e) {
        println(e.getMessageObject());
        return 1;
      }

      try {
        LDAPConnectionConsoleInteraction ui =
            new LDAPConnectionConsoleInteraction(this, argParser.getArguments());

        taskClient = new TaskClient(argParser.connect(ui, getOutputStream(), getErrorStream()));

        if (isMenuDrivenMode()) {

          // Keep prompting the user until they specify quit of
          // there is a fatal exception
          while (true) {
            getOutputStream().println();
            Menu<Void> menu = getSummaryMenu();
            MenuResult<Void> result = menu.run();
            if (result.isQuit()) {
              return 0;
            }
          }

        } else if (task.isPresent()) {
          getOutputStream().println();
          MenuResult<TaskEntry> r = new PrintTaskInfo(task.getValue()).invoke(this);
          if (r.isAgain()) {
            return 1;
          }
        } else if (summary.isPresent()) {
          getOutputStream().println();
          printSummaryTable();
        } else if (cancel.isPresent()) {
          MenuResult<TaskEntry> r = new CancelTask(cancel.getValue()).invoke(this);
          if (r.isAgain()) {
            return 1;
          }
        } else if (!isInteractive()) {
          // no-prompt option
          getOutputStream().println();
          printSummaryTable();
          return 0;
        }

      } catch (LDAPConnectionException lce) {
        println(INFO_TASKINFO_LDAP_EXCEPTION.get(lce.getMessageObject()));
        return 1;
      } catch (Exception e) {
        println(LocalizableMessage.raw(StaticUtils.getExceptionMessage(e)));
        return 1;
      }
    }
    return 0;
  }
Пример #5
0
  /** {@inheritDoc} */
  @Override
  protected int processLocal(boolean initializeServer, PrintStream out, PrintStream err) {

    // Perform the initial bootstrap of the Directory Server and process the
    // configuration.
    DirectoryServer directoryServer = DirectoryServer.getInstance();
    if (initializeServer) {
      try {
        DirectoryServer.bootstrapClient();
        DirectoryServer.initializeJMX();
      } catch (Exception e) {
        printWrappedText(err, ERR_SERVER_BOOTSTRAP_ERROR.get(getExceptionMessage(e)));
        return 1;
      }

      try {
        directoryServer.initializeConfiguration(configClass.getValue(), configFile.getValue());
      } catch (InitializationException ie) {
        printWrappedText(err, ERR_CANNOT_LOAD_CONFIG.get(ie.getMessage()));
        return 1;
      } catch (Exception e) {
        printWrappedText(err, ERR_CANNOT_LOAD_CONFIG.get(getExceptionMessage(e)));
        return 1;
      }

      // Initialize the Directory Server schema elements.
      try {
        directoryServer.initializeSchema();
      } catch (ConfigException | InitializationException e) {
        printWrappedText(err, ERR_CANNOT_LOAD_SCHEMA.get(e.getMessage()));
        return 1;
      } catch (Exception e) {
        printWrappedText(err, ERR_CANNOT_LOAD_SCHEMA.get(getExceptionMessage(e)));
        return 1;
      }

      // Initialize the Directory Server core configuration.
      try {
        CoreConfigManager coreConfigManager =
            new CoreConfigManager(directoryServer.getServerContext());
        coreConfigManager.initializeCoreConfig();
      } catch (ConfigException | InitializationException e) {
        printWrappedText(err, ERR_CANNOT_INITIALIZE_CORE_CONFIG.get(e.getMessage()));
        return 1;
      } catch (Exception e) {
        printWrappedText(err, ERR_CANNOT_INITIALIZE_CORE_CONFIG.get(getExceptionMessage(e)));
        return 1;
      }

      // Initialize the Directory Server crypto manager.
      try {
        directoryServer.initializeCryptoManager();
      } catch (ConfigException | InitializationException e) {
        printWrappedText(err, ERR_CANNOT_INITIALIZE_CRYPTO_MANAGER.get(e.getMessage()));
        return 1;
      } catch (Exception e) {
        printWrappedText(err, ERR_CANNOT_INITIALIZE_CRYPTO_MANAGER.get(getExceptionMessage(e)));
        return 1;
      }

      try {
        ErrorLogPublisher errorLogPublisher =
            TextErrorLogPublisher.getToolStartupTextErrorPublisher(new TextWriter.STREAM(out));
        ErrorLogger.getInstance().addLogPublisher(errorLogPublisher);

        DebugLogger.getInstance().addPublisherIfRequired(new TextWriter.STREAM(out));
      } catch (Exception e) {
        err.println("Error installing the custom error logger: " + stackTraceToSingleLineString(e));
      }

      // Make sure that the Directory Server plugin initialization is performed.
      try {
        HashSet<PluginType> pluginTypes = new HashSet<>(1);
        pluginTypes.add(PluginType.LDIF_EXPORT);
        directoryServer.initializePlugins(pluginTypes);
      } catch (ConfigException | InitializationException e) {
        printWrappedText(err, ERR_LDIFEXPORT_CANNOT_INITIALIZE_PLUGINS.get(e.getMessage()));
        return 1;
      } catch (Exception e) {
        printWrappedText(err, ERR_LDIFEXPORT_CANNOT_INITIALIZE_PLUGINS.get(getExceptionMessage(e)));
        return 1;
      }
    }

    // See if there were any user-defined sets of include/exclude attributes or
    // filters.  If so, then process them.
    Set<AttributeType> excludeAttributes = toAttributeTypes(excludeAttributeStrings);
    Set<AttributeType> includeAttributes = toAttributeTypes(includeAttributeStrings);

    ArrayList<SearchFilter> excludeFilters;
    if (excludeFilterStrings == null) {
      excludeFilters = null;
    } else {
      excludeFilters = new ArrayList<>();
      for (String filterString : excludeFilterStrings.getValues()) {
        try {
          excludeFilters.add(SearchFilter.createFilterFromString(filterString));
        } catch (DirectoryException de) {
          logger.error(
              ERR_LDIFEXPORT_CANNOT_PARSE_EXCLUDE_FILTER, filterString, de.getMessageObject());
          return 1;
        } catch (Exception e) {
          logger.error(
              ERR_LDIFEXPORT_CANNOT_PARSE_EXCLUDE_FILTER, filterString, getExceptionMessage(e));
          return 1;
        }
      }
    }

    ArrayList<SearchFilter> includeFilters;
    if (includeFilterStrings == null) {
      includeFilters = null;
    } else {
      includeFilters = new ArrayList<>();
      for (String filterString : includeFilterStrings.getValues()) {
        try {
          includeFilters.add(SearchFilter.createFilterFromString(filterString));
        } catch (DirectoryException de) {
          logger.error(
              ERR_LDIFEXPORT_CANNOT_PARSE_INCLUDE_FILTER, filterString, de.getMessageObject());
          return 1;
        } catch (Exception e) {
          logger.error(
              ERR_LDIFEXPORT_CANNOT_PARSE_INCLUDE_FILTER, filterString, getExceptionMessage(e));
          return 1;
        }
      }
    }

    // Get information about the backends defined in the server.  Iterate
    // through them, finding the one backend that should be used for the export,
    // and also finding backends with subordinate base DNs that should be
    // excluded from the export.
    Backend backend = null;
    List<DN> baseDNList = null;
    List<DN> defaultIncludeBranches = null;
    ArrayList<DN> excludeBranches = null;

    ArrayList<Backend> backendList = new ArrayList<>();
    ArrayList<BackendCfg> entryList = new ArrayList<>();
    ArrayList<List<DN>> dnList = new ArrayList<>();
    BackendToolUtils.getBackends(backendList, entryList, dnList);

    int numBackends = backendList.size();
    for (int i = 0; i < numBackends; i++) {
      Backend b = backendList.get(i);
      if (!backendID.getValue().equals(b.getBackendID())) {
        continue;
      }

      if (backend == null) {
        backend = b;
        baseDNList = dnList.get(i);
        defaultIncludeBranches = dnList.get(i);
      } else {
        logger.error(ERR_LDIFEXPORT_MULTIPLE_BACKENDS_FOR_ID, backendID.getValue());
        return 1;
      }
    }

    if (backend == null) {
      logger.error(ERR_LDIFEXPORT_NO_BACKENDS_FOR_ID, backendID.getValue());
      return 1;
    } else if (!backend.supports(BackendOperation.RESTORE)) {
      logger.error(ERR_LDIFEXPORT_CANNOT_EXPORT_BACKEND, backendID.getValue());
      return 1;
    }

    if (excludeBranchStrings.isPresent()) {
      excludeBranches = new ArrayList<>();
      for (String s : excludeBranchStrings.getValues()) {
        DN excludeBranch;
        try {
          excludeBranch = DN.valueOf(s);
        } catch (DirectoryException de) {
          logger.error(ERR_LDIFEXPORT_CANNOT_DECODE_EXCLUDE_BASE, s, de.getMessageObject());
          return 1;
        } catch (Exception e) {
          logger.error(ERR_LDIFEXPORT_CANNOT_DECODE_EXCLUDE_BASE, s, getExceptionMessage(e));
          return 1;
        }

        if (!excludeBranches.contains(excludeBranch)) {
          excludeBranches.add(excludeBranch);
        }
      }
    }

    List<DN> includeBranches;
    if (includeBranchStrings.isPresent()) {
      includeBranches = new ArrayList<>();
      for (String s : includeBranchStrings.getValues()) {
        DN includeBranch;
        try {
          includeBranch = DN.valueOf(s);
        } catch (DirectoryException de) {
          logger.error(ERR_LDIFIMPORT_CANNOT_DECODE_INCLUDE_BASE, s, de.getMessageObject());
          return 1;
        } catch (Exception e) {
          logger.error(ERR_LDIFIMPORT_CANNOT_DECODE_INCLUDE_BASE, s, getExceptionMessage(e));
          return 1;
        }

        if (!Backend.handlesEntry(includeBranch, defaultIncludeBranches, excludeBranches)) {
          logger.error(ERR_LDIFEXPORT_INVALID_INCLUDE_BASE, s, backendID.getValue());
          return 1;
        }

        includeBranches.add(includeBranch);
      }
    } else {
      includeBranches = defaultIncludeBranches;
    }

    // Create the LDIF export configuration to use when reading the LDIF.
    ExistingFileBehavior existingBehavior;
    if (appendToLDIF.isPresent()) {
      existingBehavior = ExistingFileBehavior.APPEND;
    } else {
      existingBehavior = ExistingFileBehavior.OVERWRITE;
    }

    LDIFExportConfig exportConfig = new LDIFExportConfig(ldifFile.getValue(), existingBehavior);
    exportConfig.setCompressData(compressLDIF.isPresent());
    exportConfig.setEncryptData(encryptLDIF.isPresent());
    exportConfig.setExcludeAttributes(excludeAttributes);
    exportConfig.setExcludeBranches(excludeBranches);
    exportConfig.setExcludeFilters(excludeFilters);
    exportConfig.setIncludeAttributes(includeAttributes);
    exportConfig.setIncludeBranches(includeBranches);
    exportConfig.setIncludeFilters(includeFilters);
    exportConfig.setSignHash(signHash.isPresent());
    exportConfig.setIncludeOperationalAttributes(!excludeOperationalAttrs.isPresent());

    // FIXME -- Should this be conditional?
    exportConfig.setInvokeExportPlugins(true);

    try {
      exportConfig.setWrapColumn(wrapColumn.getIntValue());
    } catch (ArgumentException ae) {
      logger.error(ERR_LDIFEXPORT_CANNOT_DECODE_WRAP_COLUMN_AS_INTEGER, wrapColumn.getValue());
      return 1;
    }

    // Get the set of base DNs for the backend as an array.
    DN[] baseDNs = new DN[baseDNList.size()];
    baseDNList.toArray(baseDNs);

    // Acquire a shared lock for the backend.
    try {
      String lockFile = LockFileManager.getBackendLockFileName(backend);
      StringBuilder failureReason = new StringBuilder();
      if (!LockFileManager.acquireSharedLock(lockFile, failureReason)) {
        logger.error(ERR_LDIFEXPORT_CANNOT_LOCK_BACKEND, backend.getBackendID(), failureReason);
        return 1;
      }
    } catch (Exception e) {
      logger.error(
          ERR_LDIFEXPORT_CANNOT_LOCK_BACKEND, backend.getBackendID(), getExceptionMessage(e));
      return 1;
    }

    boolean errorOccurred = false;

    // Launch the export.
    try {
      backend.exportLDIF(exportConfig);
    } catch (DirectoryException de) {
      logger.error(ERR_LDIFEXPORT_ERROR_DURING_EXPORT, de.getMessageObject());
      errorOccurred = true;
    } catch (Exception e) {
      logger.error(ERR_LDIFEXPORT_ERROR_DURING_EXPORT, getExceptionMessage(e));
      errorOccurred = true;
    }

    // Release the shared lock on the backend.
    try {
      String lockFile = LockFileManager.getBackendLockFileName(backend);
      StringBuilder failureReason = new StringBuilder();
      if (!LockFileManager.releaseLock(lockFile, failureReason)) {
        logger.warn(WARN_LDIFEXPORT_CANNOT_UNLOCK_BACKEND, backend.getBackendID(), failureReason);
      }
    } catch (Exception e) {
      logger.warn(
          WARN_LDIFEXPORT_CANNOT_UNLOCK_BACKEND, backend.getBackendID(), getExceptionMessage(e));
    }

    // Clean up after the export by closing the export config.
    exportConfig.close();
    return !errorOccurred ? 0 : 1;
  }