Example #1
0
 @Override
 protected void refreshNode() {
   // db.getStats can be slow..
   // can't use driver's because doesnt use slaveOk
   CommandResult res = db.command(new BasicDBObject("dbstats", 1), db.getMongo().getOptions());
   //        CommandResult res = db.command(new BasicDBObject("profile", -1));
   res.throwOnError();
   stats = res;
   //        db.getCollection("foo").save(new BasicDBObject("a", 1));
 }
Example #2
0
 public void close() {
   if (db != null) {
     db.getMongo().close();
   }
 }
  /**
   * Factory method for creating a MongoDB provider within the plugin manager.
   *
   * @param collectionName The name of the MongoDB collection to which log events should be written.
   * @param writeConcernConstant The {@link WriteConcern} constant to control writing details,
   *     defaults to {@link WriteConcern#ACKNOWLEDGED}.
   * @param writeConcernConstantClassName The name of a class containing the aforementioned static
   *     WriteConcern constant. Defaults to {@link WriteConcern}.
   * @param databaseName The name of the MongoDB database containing the collection to which log
   *     events should be written. Mutually exclusive with {@code
   *     factoryClassName&factoryMethodName!=null}.
   * @param server The host name of the MongoDB server, defaults to localhost and mutually exclusive
   *     with {@code factoryClassName&factoryMethodName!=null}.
   * @param port The port the MongoDB server is listening on, defaults to the default MongoDB port
   *     and mutually exclusive with {@code factoryClassName&factoryMethodName!=null}.
   * @param userName The username to authenticate against the MongoDB server with.
   * @param password The password to authenticate against the MongoDB server with.
   * @param factoryClassName A fully qualified class name containing a static factory method capable
   *     of returning a {@link DB} or a {@link MongoClient}.
   * @param factoryMethodName The name of the public static factory method belonging to the
   *     aforementioned factory class.
   * @return a new MongoDB provider.
   */
  @PluginFactory
  public static MongoDbProvider createNoSqlProvider(
      @PluginAttribute("collectionName") final String collectionName,
      @PluginAttribute("writeConcernConstant") final String writeConcernConstant,
      @PluginAttribute("writeConcernConstantClass") final String writeConcernConstantClassName,
      @PluginAttribute("databaseName") final String databaseName,
      @PluginAttribute(value = "server", defaultString = "localhost") @ValidHost
          final String server,
      @PluginAttribute(value = "port", defaultString = "" + DEFAULT_PORT) @ValidPort
          final String port,
      @PluginAttribute("userName") final String userName,
      @PluginAttribute(value = "password", sensitive = true) final String password,
      @PluginAttribute("factoryClassName") final String factoryClassName,
      @PluginAttribute("factoryMethodName") final String factoryMethodName) {
    DB database;
    String description;
    if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) {
      try {
        final Class<?> factoryClass = LoaderUtil.loadClass(factoryClassName);
        final Method method = factoryClass.getMethod(factoryMethodName);
        final Object object = method.invoke(null);

        if (object instanceof DB) {
          database = (DB) object;
        } else if (object instanceof MongoClient) {
          if (Strings.isNotEmpty(databaseName)) {
            database = ((MongoClient) object).getDB(databaseName);
          } else {
            LOGGER.error(
                "The factory method [{}.{}()] returned a MongoClient so the database name is "
                    + "required.",
                factoryClassName,
                factoryMethodName);
            return null;
          }
        } else if (object == null) {
          LOGGER.error(
              "The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName);
          return null;
        } else {
          LOGGER.error(
              "The factory method [{}.{}()] returned an unsupported type [{}].",
              factoryClassName,
              factoryMethodName,
              object.getClass().getName());
          return null;
        }

        description = "database=" + database.getName();
        final List<ServerAddress> addresses = database.getMongo().getAllAddress();
        if (addresses.size() == 1) {
          description +=
              ", server=" + addresses.get(0).getHost() + ", port=" + addresses.get(0).getPort();
        } else {
          description += ", servers=[";
          for (final ServerAddress address : addresses) {
            description += " { " + address.getHost() + ", " + address.getPort() + " } ";
          }
          description += "]";
        }
      } catch (final ClassNotFoundException e) {
        LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e);
        return null;
      } catch (final NoSuchMethodException e) {
        LOGGER.error(
            "The factory class [{}] does not have a no-arg method named [{}].",
            factoryClassName,
            factoryMethodName,
            e);
        return null;
      } catch (final Exception e) {
        LOGGER.error(
            "The factory method [{}.{}()] could not be invoked.",
            factoryClassName,
            factoryMethodName,
            e);
        return null;
      }
    } else if (Strings.isNotEmpty(databaseName)) {
      final List<MongoCredential> credentials = new ArrayList<>();
      description = "database=" + databaseName;
      if (Strings.isNotEmpty(userName) && Strings.isNotEmpty(password)) {
        description +=
            ", username="******", passwordHash="
                + NameUtil.md5(password + MongoDbProvider.class.getName());
        credentials.add(
            MongoCredential.createCredential(userName, databaseName, password.toCharArray()));
      }
      try {
        final int portInt = TypeConverters.convert(port, int.class, DEFAULT_PORT);
        description += ", server=" + server + ", port=" + portInt;
        database =
            new MongoClient(new ServerAddress(server, portInt), credentials).getDB(databaseName);
      } catch (final Exception e) {
        LOGGER.error(
            "Failed to obtain a database instance from the MongoClient at server [{}] and "
                + "port [{}].",
            server,
            port);
        return null;
      }
    } else {
      LOGGER.error("No factory method was provided so the database name is required.");
      return null;
    }

    try {
      database.getCollectionNames(); // Check if the database actually requires authentication
    } catch (final Exception e) {
      LOGGER.error(
          "The database is not up, or you are not authenticated, try supplying a username and password to the MongoDB provider.",
          e);
      return null;
    }

    final WriteConcern writeConcern =
        toWriteConcern(writeConcernConstant, writeConcernConstantClassName);

    return new MongoDbProvider(database, writeConcern, collectionName, description);
  }
Example #4
0
 @Override
 public void shutDown() {
   hashDB.getMongo().close();
 }
  protected boolean assignCollections() {
    DB adminDb = mongo.getDB(MongoDBRiver.MONGODB_ADMIN_DATABASE);
    oplogDb = mongo.getDB(MongoDBRiver.MONGODB_LOCAL_DATABASE);

    if (!definition.getMongoAdminUser().isEmpty()
        && !definition.getMongoAdminPassword().isEmpty()) {
      logger.info(
          "Authenticate {} with {}",
          MongoDBRiver.MONGODB_ADMIN_DATABASE,
          definition.getMongoAdminUser());

      CommandResult cmd =
          adminDb.authenticateCommand(
              definition.getMongoAdminUser(), definition.getMongoAdminPassword().toCharArray());
      if (!cmd.ok()) {
        logger.error(
            "Autenticatication failed for {}: {}",
            MongoDBRiver.MONGODB_ADMIN_DATABASE,
            cmd.getErrorMessage());
        // Can still try with mongoLocal credential if provided.
        // return false;
      }
      oplogDb = adminDb.getMongo().getDB(MongoDBRiver.MONGODB_LOCAL_DATABASE);
    }

    if (!definition.getMongoLocalUser().isEmpty()
        && !definition.getMongoLocalPassword().isEmpty()
        && !oplogDb.isAuthenticated()) {
      logger.info(
          "Authenticate {} with {}",
          MongoDBRiver.MONGODB_LOCAL_DATABASE,
          definition.getMongoLocalUser());
      CommandResult cmd =
          oplogDb.authenticateCommand(
              definition.getMongoLocalUser(), definition.getMongoLocalPassword().toCharArray());
      if (!cmd.ok()) {
        logger.error(
            "Autenticatication failed for {}: {}",
            MongoDBRiver.MONGODB_LOCAL_DATABASE,
            cmd.getErrorMessage());
        return false;
      }
    }

    Set<String> collections = oplogDb.getCollectionNames();
    if (!collections.contains(MongoDBRiver.OPLOG_COLLECTION)) {
      logger.error(
          "Cannot find "
              + MongoDBRiver.OPLOG_COLLECTION
              + " collection. Please check this link: http://goo.gl/2x5IW");
      return false;
    }
    oplogCollection = oplogDb.getCollection(MongoDBRiver.OPLOG_COLLECTION);

    slurpedDb = mongo.getDB(definition.getMongoDb());
    if (!definition.getMongoAdminUser().isEmpty()
        && !definition.getMongoAdminPassword().isEmpty()
        && adminDb.isAuthenticated()) {
      slurpedDb = adminDb.getMongo().getDB(definition.getMongoDb());
    }

    // Not necessary as local user has access to all databases.
    // http://docs.mongodb.org/manual/reference/local-database/
    // if (!mongoDbUser.isEmpty() && !mongoDbPassword.isEmpty()
    // && !slurpedDb.isAuthenticated()) {
    // logger.info("Authenticate {} with {}", mongoDb, mongoDbUser);
    // CommandResult cmd = slurpedDb.authenticateCommand(mongoDbUser,
    // mongoDbPassword.toCharArray());
    // if (!cmd.ok()) {
    // logger.error("Authentication failed for {}: {}",
    // mongoDb, cmd.getErrorMessage());
    // return false;
    // }
    // }
    // slurpedCollection =
    // slurpedDb.getCollection(definition.getMongoCollection());
    // if (definition.isImportAllCollections()) {
    // for (String collection : slurpedDb.getCollectionNames()) {
    // slurpedCollections.put(collection,
    // slurpedDb.getCollection(collection));
    // }
    // } else {
    // slurpedCollections.put(definition.getMongoCollection(),
    // slurpedDb.getCollection(definition.getMongoCollection()));
    // }

    return true;
  }