Example usage for com.mongodb CommandResult containsField

List of usage examples for com.mongodb CommandResult containsField

Introduction

In this page you can find the example usage for com.mongodb CommandResult containsField.

Prototype

public boolean containsField(final String field) 

Source Link

Document

Checks if this object contains a given field

Usage

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

public Topology discoverTopology() throws Exception {

    final String host = getStringProp(DB_HOST_PROP);
    final int port = getIntProp(DB_PORT_PROP);

    logger.log(Level.INFO, "Discovering Topology for host: {0}:{1}", new Object[] { host, port });

    final CommandResult master = dbAdminCmd(host, port, "isMaster");

    // ismaster returns true for a standalone mongod instance, a mongos
    // instance, a mongod shard node, or a primary in a replica set
    if (master.getBoolean("ismaster") || master.containsField("primary")) {

        boolean isReplicaSet = false;
        if (master.containsField("primary")) {
            isReplicaSet = true;// www  .  jav  a 2  s  .co m
        }

        if (isInShardCluster(master)) {
            topology = new ShardCluster(props, host, port, logger);
            topology.discoverServers(getClusterNodeType());
        } else if (isReplicaSet(master)) {
            topology = new ReplicaSet(props, host, port, logger);
            topology.discoverServers("doesn't matter");
        } else {
            topology = new StandaloneMongod(props, host, port, logger);
            topology.discoverServers("doesn't matter");
        }
    }
    logger.log(Level.INFO, "Topology: {0}", topology);
    return topology;
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private boolean isInShardCluster(final CommandResult cr) throws Exception {

    MongoServer ms = new MongoServer(getMyself(cr));
    final String host = ms.getHost();
    final int port = ms.getPort();

    boolean sharded = false;

    final String msg = cr.getString("msg");
    if ((msg != null) && msg.contains("isdbgrid")) {
        sharded = true;/*from  ww w.  java 2s  . c o m*/
    } else if (cr.getBoolean("ismaster")) {
        final CommandResult shardState = dbAdminCmd(host, port, "shardingState");
        // shardingState command only returns OK when server is in a sharded
        // cluster
        if (shardState.ok()) {
            if (shardState.getBoolean("enabled")) {
                sharded = true;
            }
        }
    } else if (cr.containsField("primary")) {
        // we are in a replica set but not the primary,
        // check the primary to see if it is a shard member
        final String primary = cr.getString("primary");
        ms = new MongoServer(primary);
        final CommandResult priIsMaster = dbAdminCmd(ms.getHost(), ms.getPort(), "isMaster");
        sharded = isInShardCluster(priIsMaster);
    }
    return sharded;
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private boolean isReplicaSet(final CommandResult cr) {
    return cr.containsField("primary");
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

/**
 * This method is to check to see if a node is in a replica set despite
 * not being the primary member.//from w w w  .j  a  v a  2s .c  o  m
 */
private boolean isReplicaMember(final CommandResult cr) {
    boolean isReplMember = false;
    if (cr.containsField("primary")) {
        if (cr.getBoolean("secondary") || cr.getBoolean("passive") || cr.getBoolean("arbiterOnly")) {
            isReplMember = true;
        }
    }
    return isReplMember;
}

From source file:com.ca.apm.mongo.ShardCluster.java

License:Open Source License

private List<String> getConfigServersFromShard(final String host, final int port) throws Exception {

    final List<String> cfgServers = new ArrayList<String>();

    String cHost = host;/* ww w.j a  v  a2 s.  c  o m*/
    int cPort = port;

    final CommandResult isMaster = dbAdminCmd(cHost, cPort, "isMaster");

    // we can't run the DB command "shardingState" from a node
    // which isn't a master.  This should only apply to non-primary
    // replica members, so find the primary and run the command on it.
    if (!isMaster.getBoolean("ismaster")) {
        if (isMaster.containsField("primary")) {
            final String primary = isMaster.getString("primary");
            final MongoServer ms = new MongoServer(primary);
            cHost = ms.getHost();
            cPort = ms.getPort();
        }
    }

    CommandResult shardState = dbAdminCmd(cHost, cPort, "shardingState");

    if (shardState.ok()) {
        final String cfgSrvs = shardState.getString("configServer");
        addCommaSeparatedHosts(cfgServers, cfgSrvs);
    }
    return cfgServers;
}

From source file:com.ca.apm.mongo.Topology.java

License:Open Source License

protected List<String> discoverReplicas(final String host, final int port) throws Exception {

    List<String> replicas = new ArrayList<String>();

    final CommandResult cr = dbAdminCmd(host, port, "isMaster");

    replicas.addAll((List<String>) cr.get("hosts"));
    // hidden replicas are replicas that cannot become primaries and
    // are hidden to the client app
    if (cr.getBoolean("hidden")) {
        // TODO: We can't assume we're the master here....
        replicas.add(cr.getString("me"));
    }//ww  w .  j  a v a2 s.c  o  m
    // passives are replicas that cannot become primaries because
    // their priority is set to 0
    if (cr.containsField("passives")) {
        replicas.addAll((List<String>) cr.get("passives"));
    }
    // arbiters exist only to vote in master elections.  They don't
    // actually hold replica data.
    if (cr.containsField("arbiters")) {
        replicas.addAll((List<String>) cr.get("arbiters"));
    }
    return replicas;
}

From source file:com.edgytech.umongo.MongoNode.java

License:Apache License

@Override
protected void populateChildren() {
    // first ask list of db, will also trigger discovery of nodes
    List<String> dbnames = new ArrayList<String>();
    try {//from w  w w. j  av  a  2s  .c o m
        dbnames = mongo.getDatabaseNames();
    } catch (Exception e) {
        getLogger().log(Level.WARNING, e.getMessage(), e);
    }

    List<ServerAddress> addrs = mongo.getServerAddressList();

    if (addrs.size() <= 1) {
        // check if mongos
        boolean added = false;
        ServerAddress addr = addrs.get(0);
        ServerNode node = new ServerNode(mongo, false, false);
        try {
            CommandResult res = node.getServerDB().command("isdbgrid");
            if (res.ok()) {
                addChild(new RouterNode(addr, mongo));
                added = true;
            }
        } catch (Exception e) {
            getLogger().log(Level.INFO, e.getMessage(), e);
        }

        if (mongo.getReplicaSetStatus() != null) {
            // could be replset of 1, check
            try {
                CommandResult res = node.getServerDB().command(new BasicDBObject("isMaster", 1),
                        mongo.getOptions());
                if (res.containsField("setName")) {
                    addChild(new ReplSetNode(mongo.getReplicaSetStatus().getName(), mongo, null));
                    added = true;
                }
            } catch (Exception e) {
                getLogger().log(Level.INFO, e.getMessage(), e);
            }
        }

        if (!added)
            addChild(node);
    } else {
        addChild(new ReplSetNode(mongo.getReplicaSetStatus().getName(), mongo, null));
    }

    if (specifiedDb) {
        // user specified list of DB
        dbnames = dbs;
    } else {
        dbs = dbnames;
        if (dbnames.isEmpty()) {
            // could not get any dbs, add test at least
            dbnames.add("test");
        }
    }

    if (dbnames != null) {
        // get all DBs to populate map
        for (String dbname : dbnames) {
            addChild(new DbNode(mongo.getDB(dbname)));
        }
    }
}

From source file:com.ikanow.infinit.e.api.knowledge.SearchHandler.java

License:Open Source License

/**
 * Sends a geonear command to the feature.geo database.  Returns back
 * a list of the nearest 10 locations/*from w w w  .  j  av  a 2  s.  co m*/
 *  
 * @param lat
 * @param lon
 * @return
 */
private BasicDBList runGeoNear(Double lat, Double lon) {
    String location = null;
    BasicDBObject command = new BasicDBObject("geoNear", "geo");
    Double[] coordinates = { lat, lon };
    command.put("near", coordinates);
    command.put("maxDistance", MAXIMUM_DISTANCE_IN_METERS);
    CommandResult commandResult = MongoDbManager.getDB("feature").command(command);
    if (commandResult.ok() && commandResult.containsField("results")) {
        BasicDBList results = (BasicDBList) commandResult.get("results");
        return results;
    }

    return null;
}

From source file:com.zjy.mongo.splitter.StandaloneMongoSplitter.java

License:Apache License

@Override
public List<InputSplit> calculateSplits() throws SplitFailedException {
    final DBObject splitKey = MongoConfigUtil.getInputSplitKey(getConfiguration());
    final DBObject splitKeyMax = MongoConfigUtil.getMaxSplitKey(getConfiguration());
    final DBObject splitKeyMin = MongoConfigUtil.getMinSplitKey(getConfiguration());
    final int splitSize = MongoConfigUtil.getSplitSize(getConfiguration());
    final MongoClientURI inputURI;
    DBCollection inputCollection = null;
    final ArrayList<InputSplit> returnVal;
    try {// w ww  .  ja  v  a 2s.c o  m
        inputURI = MongoConfigUtil.getInputURI(getConfiguration());
        MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration());
        if (authURI != null) {
            inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI);
        } else {
            inputCollection = MongoConfigUtil.getCollection(inputURI);
        }

        returnVal = new ArrayList<InputSplit>();
        final String ns = inputCollection.getFullName();

        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Running splitVector on namespace: %s.%s; hosts: %s",
                    inputURI.getDatabase(), inputURI.getCollection(), inputURI.getHosts()));
        }
        final DBObject cmd = BasicDBObjectBuilder.start("splitVector", ns).add("keyPattern", splitKey)
                .add("min", splitKeyMin).add("max", splitKeyMax)
                // force:True is misbehaving it seems
                .add("force", false).add("maxChunkSize", splitSize).get();

        CommandResult data;
        boolean ok = true;
        try {
            data = inputCollection.getDB().getSisterDB(inputURI.getDatabase()).command(cmd,
                    ReadPreference.primary());
        } catch (final MongoException e) { // 2.0 servers throw exceptions rather than info in a CommandResult
            data = null;
            LOG.info(e.getMessage(), e);
            if (e.getMessage().contains("unrecognized command: splitVector")) {
                ok = false;
            } else {
                throw e;
            }
        }

        if (data != null) {
            if (data.containsField("$err")) {
                throw new SplitFailedException("Error calculating splits: " + data);
            } else if (!data.get("ok").equals(1.0)) {
                ok = false;
            }
        }

        if (!ok) {
            final CommandResult stats = inputCollection.getStats();
            if (stats.containsField("primary")) {
                final DBCursor shards = inputCollection.getDB().getSisterDB("config").getCollection("shards")
                        .find(new BasicDBObject("_id", stats.getString("primary")));
                try {
                    if (shards.hasNext()) {
                        final DBObject shard = shards.next();
                        final String host = ((String) shard.get("host")).replace(shard.get("_id") + "/", "");
                        final MongoClientURI shardHost;
                        if (authURI != null) {
                            shardHost = new MongoClientURIBuilder(authURI).host(host).build();
                        } else {
                            shardHost = new MongoClientURIBuilder(inputURI).host(host).build();
                        }
                        MongoClient shardClient = null;
                        try {
                            shardClient = new MongoClient(shardHost);
                            data = shardClient.getDB(shardHost.getDatabase()).command(cmd,
                                    ReadPreference.primary());
                        } catch (final Exception e) {
                            LOG.error(e.getMessage(), e);
                        } finally {
                            if (shardClient != null) {
                                shardClient.close();
                            }
                        }
                    }
                } finally {
                    shards.close();
                }
            }
            if (data != null && !data.get("ok").equals(1.0)) {
                throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg"));
            }

        }

        // Comes in a format where "min" and "max" are implicit
        // and each entry is just a boundary key; not ranged
        final BasicDBList splitData = (BasicDBList) data.get("splitKeys");

        if (splitData.size() == 0) {
            LOG.warn(
                    "WARNING: No Input Splits were calculated by the split code. Proceeding with a *single* split. Data may be too"
                            + " small, try lowering 'mongo.input.split_size' if this is undesirable.");
        }

        BasicDBObject lastKey = null; // Lower boundary of the first min split

        // If splitKeyMin was given, use it as first boundary.
        if (!splitKeyMin.toMap().isEmpty()) {
            lastKey = new BasicDBObject(splitKeyMin.toMap());
        }
        for (final Object aSplitData : splitData) {
            final BasicDBObject currentKey = (BasicDBObject) aSplitData;
            returnVal.add(createSplitFromBounds(lastKey, currentKey));
            lastKey = currentKey;
        }

        BasicDBObject maxKey = null;
        // If splitKeyMax was given, use it as last boundary.
        if (!splitKeyMax.toMap().isEmpty()) {
            maxKey = new BasicDBObject(splitKeyMax.toMap());
        }
        // Last max split
        final MongoInputSplit lastSplit = createSplitFromBounds(lastKey, maxKey);
        returnVal.add(lastSplit);
    } finally {
        if (inputCollection != null) {
            MongoConfigUtil.close(inputCollection.getDB().getMongo());
        }
    }

    return returnVal;
}

From source file:org.mule.module.mongo.tools.OplogCollection.java

License:Open Source License

private boolean isMaster() throws IOException {
    // Validate we are on master or replica
    CommandResult commandResult = admin.command(new BasicDBObject(IS_MASTER_FIELD, 1));
    boolean isMaster = commandResult.getBoolean(IS_MASTER_FIELD, false);

    // Replica set member
    if (commandResult.containsField("hosts")) {
        return false;
    } else {//  w  w w  . ja  v  a  2  s  .  co  m
        if (!isMaster) {
            throw new IOException("oplog mode is only supported on master or replica set member");
        }
        return true;
    }

}