本文整理汇总了C++中BSONObjBuilder::subarrayStart方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONObjBuilder::subarrayStart方法的具体用法?C++ BSONObjBuilder::subarrayStart怎么用?C++ BSONObjBuilder::subarrayStart使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONObjBuilder
的用法示例。
在下文中一共展示了BSONObjBuilder::subarrayStart方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: appendReplicationInfo
void appendReplicationInfo(OperationContext* opCtx, BSONObjBuilder& result, int level) {
ReplicationCoordinator* replCoord = ReplicationCoordinator::get(opCtx);
if (replCoord->getSettings().usingReplSets()) {
IsMasterResponse isMasterResponse;
replCoord->fillIsMasterForReplSet(&isMasterResponse);
result.appendElements(isMasterResponse.toBSON());
if (level) {
replCoord->appendSlaveInfoData(&result);
}
return;
}
result.appendBool("ismaster",
ReplicationCoordinator::get(opCtx)->isMasterForReportingPurposes());
if (level) {
BSONObjBuilder sources(result.subarrayStart("sources"));
int n = 0;
list<BSONObj> src;
{
const NamespaceString localSources{"local.sources"};
AutoGetCollectionForReadCommand ctx(opCtx, localSources);
auto exec = InternalPlanner::collectionScan(
opCtx, localSources.ns(), ctx.getCollection(), PlanExecutor::NO_YIELD);
BSONObj obj;
PlanExecutor::ExecState state;
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
src.push_back(obj.getOwned());
}
// Non-yielding collection scans from InternalPlanner will never error.
invariant(PlanExecutor::IS_EOF == state);
}
for (list<BSONObj>::const_iterator i = src.begin(); i != src.end(); i++) {
BSONObj s = *i;
BSONObjBuilder bb;
bb.append(s["host"]);
string sourcename = s["source"].valuestr();
if (sourcename != "main")
bb.append(s["source"]);
{
BSONElement e = s["syncedTo"];
BSONObjBuilder t(bb.subobjStart("syncedTo"));
t.appendDate("time", e.timestampTime());
t.append("inc", e.timestampInc());
t.done();
}
if (level > 1) {
invariant(!opCtx->lockState()->isLocked());
// note: there is no so-style timeout on this connection; perhaps we should have
// one.
ScopedDbConnection conn(s["host"].valuestr());
DBClientConnection* cliConn = dynamic_cast<DBClientConnection*>(&conn.conn());
if (cliConn && replAuthenticate(cliConn)) {
BSONObj first = conn->findOne((string) "local.oplog.$" + sourcename,
Query().sort(BSON("$natural" << 1)));
BSONObj last = conn->findOne((string) "local.oplog.$" + sourcename,
Query().sort(BSON("$natural" << -1)));
bb.appendDate("masterFirst", first["ts"].timestampTime());
bb.appendDate("masterLast", last["ts"].timestampTime());
const auto lag = (last["ts"].timestampTime() - s["syncedTo"].timestampTime());
bb.append("lagSeconds", durationCount<Milliseconds>(lag) / 1000.0);
}
conn.done();
}
sources.append(BSONObjBuilder::numStr(n++), bb.obj());
}
sources.done();
replCoord->appendSlaveInfoData(&result);
}
}
示例2: queryOrB
Query ConfigDiffTracker<ValType,ShardType>::
configDiffQuery( const set<ChunkVersion>& extraMinorVersions ) const
{
verifyAttached();
//
// Basic idea behind the query is to find all the chunks $gt the current max version, and
// then also update chunks that we need minor versions - splits and (2.0) max chunks on
// shards
//
static const int maxMinorVersionClauses = 50;
BSONObjBuilder queryB;
int numStaleMinorClauses = extraMinorVersions.size() + _maxShardVersions->size();
#ifdef _DEBUG
// In debug builds, randomly trigger full reloads to exercise both codepaths
if( rand() % 2 ) numStaleMinorClauses = maxMinorVersionClauses;
#endif
queryB.append(ChunkType::ns(), _ns);
//
// If we have only a few minor versions to refresh, we can be more selective in our query
//
if( numStaleMinorClauses < maxMinorVersionClauses ) {
//
// Get any version changes higher than we know currently
//
BSONArrayBuilder queryOrB( queryB.subarrayStart( "$or" ) );
{
BSONObjBuilder queryNewB( queryOrB.subobjStart() );
{
BSONObjBuilder ts(queryNewB.subobjStart(ChunkType::DEPRECATED_lastmod()));
// We should *always* pull at least a single chunk back, this lets us quickly
// detect if our collection was unsharded (and most of the time if it was
// resharded) in the meantime
ts.appendTimestamp( "$gte", _maxVersion->toLong() );
ts.done();
}
queryNewB.done();
}
// Get any shard version changes higher than we know currently
// Needed since there could have been a split of the max version chunk of any shard
// TODO: Ideally, we shouldn't care about these
for( typename map<ShardType, ChunkVersion>::const_iterator it = _maxShardVersions->begin(); it != _maxShardVersions->end(); it++ ) {
BSONObjBuilder queryShardB( queryOrB.subobjStart() );
queryShardB.append(ChunkType::shard(), nameFrom( it->first ) );
{
BSONObjBuilder ts(queryShardB.subobjStart(ChunkType::DEPRECATED_lastmod()));
ts.appendTimestamp( "$gt", it->second.toLong() );
ts.done();
}
queryShardB.done();
}
// Get any minor version changes we've marked as interesting
// TODO: Ideally we shouldn't care about these
for( set<ChunkVersion>::const_iterator it = extraMinorVersions.begin(); it != extraMinorVersions.end(); it++ ) {
BSONObjBuilder queryShardB( queryOrB.subobjStart() );
{
BSONObjBuilder ts(queryShardB.subobjStart(ChunkType::DEPRECATED_lastmod()));
ts.appendTimestamp( "$gt", it->toLong() );
ts.appendTimestamp( "$lt",
ChunkVersion( it->majorVersion() + 1, 0, OID() ).toLong() );
ts.done();
}
queryShardB.done();
}
queryOrB.done();
}
BSONObj query = queryB.obj();
LOG(2) << "major version query from " << *_maxVersion << " and over "
<< _maxShardVersions->size() << " shards is " << query << endl;
//
// NOTE: IT IS IMPORTANT FOR CONSISTENCY THAT WE SORT BY ASC VERSION, TO HANDLE
// CURSOR YIELDING BETWEEN CHUNKS BEING MIGRATED.
//
// This ensures that changes to chunk version (which will always be higher) will always
// come *after* our current position in the chunk cursor.
//
Query queryObj(query);
queryObj.sort(BSON( "lastmod" << 1 ));
return Query( query );
}
示例3: run
//.........这里部分代码省略.........
BSONElement eDistanceMultiplier = cmdObj["distanceMultiplier"];
if (!eDistanceMultiplier.eoo()) {
uassert(17296, "distanceMultiplier must be a number", eDistanceMultiplier.isNumber());
distanceMultiplier = eDistanceMultiplier.number();
uassert(17297, "distanceMultiplier must be non-negative", distanceMultiplier >= 0);
}
BSONObj projObj = BSON("$pt" << BSON("$meta" << LiteParsedQuery::metaGeoNearPoint) << "$dis"
<< BSON("$meta" << LiteParsedQuery::metaGeoNearDistance));
const ExtensionsCallbackReal extensionsCallback(txn, &nss);
auto statusWithCQ = CanonicalQuery::canonicalize(
nss, rewritten, BSONObj(), projObj, 0, numWanted, BSONObj(), extensionsCallback);
if (!statusWithCQ.isOK()) {
errmsg = "Can't parse filter / create query";
return false;
}
unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());
// Prevent chunks from being cleaned up during yields - this allows us to only check the
// version on initial entry into geoNear.
RangePreserver preserver(collection);
auto statusWithPlanExecutor =
getExecutor(txn, collection, std::move(cq), PlanExecutor::YIELD_AUTO, 0);
if (!statusWithPlanExecutor.isOK()) {
errmsg = "can't get query executor";
return false;
}
unique_ptr<PlanExecutor> exec = std::move(statusWithPlanExecutor.getValue());
double totalDistance = 0;
BSONObjBuilder resultBuilder(result.subarrayStart("results"));
double farthestDist = 0;
BSONObj currObj;
long long results = 0;
PlanExecutor::ExecState state;
while (PlanExecutor::ADVANCED == (state = exec->getNext(&currObj, NULL))) {
// Come up with the correct distance.
double dist = currObj["$dis"].number() * distanceMultiplier;
totalDistance += dist;
if (dist > farthestDist) {
farthestDist = dist;
}
// Strip out '$dis' and '$pt' from the result obj. The rest gets added as 'obj'
// in the command result.
BSONObjIterator resIt(currObj);
BSONObjBuilder resBob;
while (resIt.more()) {
BSONElement elt = resIt.next();
if (!mongoutils::str::equals("$pt", elt.fieldName()) &&
!mongoutils::str::equals("$dis", elt.fieldName())) {
resBob.append(elt);
}
}
BSONObj resObj = resBob.obj();
// Don't make a too-big result object.
if (resultBuilder.len() + resObj.objsize() > BSONObjMaxUserSize) {
warning() << "Too many geoNear results for query " << rewritten.toString()
<< ", truncating output.";
break;
}
示例4: handleSpecialNamespaces
bool handleSpecialNamespaces( Request& r , QueryMessage& q ) {
const char * ns = r.getns();
ns = strstr( r.getns() , ".$cmd.sys." );
if ( ! ns )
return false;
ns += 10;
r.checkAuth( Auth::WRITE );
BSONObjBuilder b;
vector<Shard> shards;
if ( strcmp( ns , "inprog" ) == 0 ) {
Shard::getAllShards( shards );
BSONArrayBuilder arr( b.subarrayStart( "inprog" ) );
for ( unsigned i=0; i<shards.size(); i++ ) {
Shard shard = shards[i];
ScopedDbConnection conn( shard );
BSONObj temp = conn->findOne( r.getns() , BSONObj() );
if ( temp["inprog"].isABSONObj() ) {
BSONObjIterator i( temp["inprog"].Obj() );
while ( i.more() ) {
BSONObjBuilder x;
BSONObjIterator j( i.next().Obj() );
while( j.more() ) {
BSONElement e = j.next();
if ( str::equals( e.fieldName() , "opid" ) ) {
stringstream ss;
ss << shard.getName() << ':' << e.numberInt();
x.append( "opid" , ss.str() );
}
else if ( str::equals( e.fieldName() , "client" ) ) {
x.appendAs( e , "client_s" );
}
else {
x.append( e );
}
}
arr.append( x.obj() );
}
}
conn.done();
}
arr.done();
}
else if ( strcmp( ns , "killop" ) == 0 ) {
BSONElement e = q.query["op"];
if ( strstr( r.getns() , "admin." ) == 0 ) {
b.append( "err" , "unauthorized" );
}
else if ( e.type() != String ) {
b.append( "err" , "bad op" );
b.append( e );
}
else {
b.append( e );
string s = e.String();
string::size_type i = s.find( ':' );
if ( i == string::npos ) {
b.append( "err" , "bad opid" );
}
else {
string shard = s.substr( 0 , i );
int opid = atoi( s.substr( i + 1 ).c_str() );
b.append( "shard" , shard );
b.append( "shardid" , opid );
log() << "want to kill op: " << e << endl;
Shard s(shard);
ScopedDbConnection conn( s );
conn->findOne( r.getns() , BSON( "op" << opid ) );
conn.done();
}
}
}
else if ( strcmp( ns , "unlock" ) == 0 ) {
b.append( "err" , "can't do unlock through mongos" );
}
else {
log( LL_WARNING ) << "unknown sys command [" << ns << "]" << endl;
return false;
}
BSONObj x = b.done();
replyToQuery(0, r.p(), r.m(), x);
return true;
}
示例5: run
bool run(OperationContext* txn,
const std::string& db,
BSONObj& cmdObj,
int options,
std::string& errmsg,
BSONObjBuilder& result) final {
const bool includeAll = cmdObj["$all"].trueValue();
const bool ownOpsOnly = cmdObj["$ownOps"].trueValue();
// Filter the output
BSONObj filter;
{
BSONObjBuilder b;
BSONObjIterator i(cmdObj);
invariant(i.more());
i.next(); // skip {currentOp: 1} which is required to be the first element
while (i.more()) {
BSONElement e = i.next();
if (str::equals("$all", e.fieldName())) {
continue;
} else if (str::equals("$ownOps", e.fieldName())) {
continue;
}
b.append(e);
}
filter = b.obj();
}
// We use ExtensionsCallbackReal here instead of ExtensionsCallbackNoop in order to support
// the use case of having a $where filter with currentOp. However, since we don't have a
// collection, we pass in a fake collection name (and this is okay, because $where parsing
// only relies on the database part of the namespace).
const NamespaceString fakeNS(db, "$cmd");
const CollatorInterface* collator = nullptr;
const Matcher matcher(filter, ExtensionsCallbackReal(txn, &fakeNS), collator);
BSONArrayBuilder inprogBuilder(result.subarrayStart("inprog"));
for (ServiceContext::LockedClientsCursor cursor(txn->getClient()->getServiceContext());
Client* client = cursor.next();) {
invariant(client);
stdx::lock_guard<Client> lk(*client);
if (ownOpsOnly &&
!AuthorizationSession::get(txn->getClient())->isCoauthorizedWithClient(client)) {
continue;
}
const OperationContext* opCtx = client->getOperationContext();
if (!includeAll) {
// Skip over inactive connections.
if (!opCtx)
continue;
}
BSONObjBuilder infoBuilder;
// The client information
client->reportState(infoBuilder);
const auto& clientMetadata =
ClientMetadataIsMasterState::get(txn->getClient()).getClientMetadata();
if (clientMetadata) {
auto appName = clientMetadata.get().getApplicationName();
if (!appName.empty()) {
infoBuilder.append("appName", appName);
}
}
// Operation context specific information
infoBuilder.appendBool("active", static_cast<bool>(opCtx));
if (opCtx) {
infoBuilder.append("opid", opCtx->getOpID());
if (opCtx->isKillPending()) {
infoBuilder.append("killPending", true);
}
CurOp::get(opCtx)->reportState(&infoBuilder);
// LockState
Locker::LockerInfo lockerInfo;
opCtx->lockState()->getLockerInfo(&lockerInfo);
fillLockerInfo(lockerInfo, infoBuilder);
}
infoBuilder.done();
const BSONObj info = infoBuilder.obj();
if (includeAll || matcher.matches(info)) {
inprogBuilder.append(info);
}
}
inprogBuilder.done();
if (lockedForWriting()) {
//.........这里部分代码省略.........
示例6: handleSpecialNamespaces
bool handleSpecialNamespaces( Request& r , QueryMessage& q ) {
const char * ns = strstr( r.getns() , ".$cmd.sys." );
if ( ! ns )
return false;
ns += 10;
BSONObjBuilder b;
vector<Shard> shards;
ClientBasic* client = ClientBasic::getCurrent();
AuthorizationSession* authSession = client->getAuthorizationSession();
if ( strcmp( ns , "inprog" ) == 0 ) {
const bool isAuthorized = authSession->isAuthorizedForActionsOnResource(
ResourcePattern::forClusterResource(), ActionType::inprog);
audit::logInProgAuthzCheck(
client, q.query, isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized);
uassert(ErrorCodes::Unauthorized, "not authorized to run inprog", isAuthorized);
Shard::getAllShards( shards );
BSONArrayBuilder arr( b.subarrayStart( "inprog" ) );
for ( unsigned i=0; i<shards.size(); i++ ) {
Shard shard = shards[i];
ScopedDbConnection conn(shard.getConnString());
BSONObj temp = conn->findOne( r.getns() , q.query );
if ( temp["inprog"].isABSONObj() ) {
BSONObjIterator i( temp["inprog"].Obj() );
while ( i.more() ) {
BSONObjBuilder x;
BSONObjIterator j( i.next().Obj() );
while( j.more() ) {
BSONElement e = j.next();
if ( str::equals( e.fieldName() , "opid" ) ) {
stringstream ss;
ss << shard.getName() << ':' << e.numberInt();
x.append( "opid" , ss.str() );
}
else if ( str::equals( e.fieldName() , "client" ) ) {
x.appendAs( e , "client_s" );
}
else {
x.append( e );
}
}
arr.append( x.obj() );
}
}
conn.done();
}
arr.done();
}
else if ( strcmp( ns , "killop" ) == 0 ) {
const bool isAuthorized = authSession->isAuthorizedForActionsOnResource(
ResourcePattern::forClusterResource(), ActionType::killop);
audit::logKillOpAuthzCheck(
client,
q.query,
isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized);
uassert(ErrorCodes::Unauthorized, "not authorized to run killop", isAuthorized);
BSONElement e = q.query["op"];
if ( e.type() != String ) {
b.append( "err" , "bad op" );
b.append( e );
}
else {
b.append( e );
string s = e.String();
string::size_type i = s.find( ':' );
if ( i == string::npos ) {
b.append( "err" , "bad opid" );
}
else {
string shard = s.substr( 0 , i );
int opid = atoi( s.substr( i + 1 ).c_str() );
b.append( "shard" , shard );
b.append( "shardid" , opid );
log() << "want to kill op: " << e << endl;
Shard s(shard);
ScopedDbConnection conn(s.getConnString());
conn->findOne( r.getns() , BSON( "op" << opid ) );
conn.done();
}
}
}
else if ( strcmp( ns , "unlock" ) == 0 ) {
b.append( "err" , "can't do unlock through mongos" );
}
else {
warning() << "unknown sys command [" << ns << "]" << endl;
return false;
}
BSONObj x = b.done();
replyToQuery(0, r.p(), r.m(), x);
//.........这里部分代码省略.........
示例7: _run
/*
* Runs the command object cmdobj on the db with name dbname and puts result in result.
* @param dbname, name of db
* @param cmdobj, object that contains entire command
* @param options
* @param errmsg, reference to error message
* @param result, reference to builder for result
* @param fromRepl
* @return true if successful, false otherwise
*/
bool FTSCommand::_run(const string& dbname,
BSONObj& cmdObj,
int cmdOptions,
const string& ns,
const string& searchString,
string language, // "" for not-set
int limit,
BSONObj& filter,
BSONObj& projection,
string& errmsg,
BSONObjBuilder& result ) {
Timer comm;
scoped_ptr<Projection> pr;
if ( !projection.isEmpty() ) {
pr.reset( new Projection() );
pr->init( projection );
}
// priority queue for results
Results results;
Database* db = cc().database();
Collection* collection = db->getCollection( ns );
if ( !collection ) {
errmsg = "can't find ns";
return false;
}
vector<int> idxMatches;
collection->details()->findIndexByType( INDEX_NAME, idxMatches );
if ( idxMatches.size() == 0 ) {
errmsg = str::stream() << "no text index for: " << ns;
return false;
}
if ( idxMatches.size() > 1 ) {
errmsg = str::stream() << "too many text indexes for: " << ns;
return false;
}
BSONObj indexPrefix;
IndexDescriptor* descriptor = collection->getIndexCatalog()->getDescriptor(idxMatches[0]);
auto_ptr<FTSAccessMethod> fam(new FTSAccessMethod(descriptor));
if ( language == "" ) {
language = fam->getSpec().defaultLanguage().str();
}
Status s = fam->getSpec().getIndexPrefix( filter, &indexPrefix );
if ( !s.isOK() ) {
errmsg = s.toString();
return false;
}
FTSQuery query;
if ( !query.parse( searchString, language ).isOK() ) {
errmsg = "can't parse search";
return false;
}
result.append( "queryDebugString", query.debugString() );
result.append( "language", language );
FTSSearch search(descriptor, fam->getSpec(), indexPrefix, query, filter );
search.go( &results, limit );
// grab underlying container inside priority queue
vector<ScoredLocation> r( results.dangerous() );
// sort results by score (not always in correct order, especially w.r.t. multiterm)
sort( r.begin(), r.end() );
// build the results bson array shown to user
BSONArrayBuilder a( result.subarrayStart( "results" ) );
int tempSize = 1024 * 1024; // leave a mb for other things
long long numReturned = 0;
for ( unsigned n = 0; n < r.size(); n++ ) {
BSONObj obj = BSONObj::make(r[n].rec);
BSONObj toSendBack = obj;
if ( pr ) {
toSendBack = pr->transform(obj);
}
if ( ( tempSize + toSendBack.objsize() ) >= BSONObjMaxUserSize ) {
break;
}
//.........这里部分代码省略.........
示例8: run
//.........这里部分代码省略.........
BSONObj rewritten = queryBob.obj();
// cout << "rewritten query: " << rewritten.toString() << endl;
int numWanted = 100;
const char* limitName = !cmdObj["num"].eoo() ? "num" : "limit";
BSONElement eNumWanted = cmdObj[limitName];
if (!eNumWanted.eoo()) {
uassert(17303, "limit must be number", eNumWanted.isNumber());
numWanted = eNumWanted.numberInt();
uassert(17302, "limit must be >=0", numWanted >= 0);
}
bool includeLocs = false;
if (!cmdObj["includeLocs"].eoo()) {
includeLocs = cmdObj["includeLocs"].trueValue();
}
double distanceMultiplier = 1.0;
BSONElement eDistanceMultiplier = cmdObj["distanceMultiplier"];
if (!eDistanceMultiplier.eoo()) {
uassert(17296, "distanceMultiplier must be a number", eDistanceMultiplier.isNumber());
distanceMultiplier = eDistanceMultiplier.number();
uassert(17297, "distanceMultiplier must be non-negative", distanceMultiplier >= 0);
}
BSONObj projObj = BSON("$pt" << BSON("$meta" << LiteParsedQuery::metaGeoNearPoint) <<
"$dis" << BSON("$meta" << LiteParsedQuery::metaGeoNearDistance));
CanonicalQuery* cq;
if (!CanonicalQuery::canonicalize(ns, rewritten, BSONObj(), projObj, 0, numWanted, BSONObj(), &cq).isOK()) {
errmsg = "Can't parse filter / create query";
return false;
}
Runner* rawRunner;
if (!getRunner(cq, &rawRunner, 0).isOK()) {
errmsg = "can't get query runner";
return false;
}
auto_ptr<Runner> runner(rawRunner);
double totalDistance = 0;
BSONObjBuilder resultBuilder(result.subarrayStart("results"));
double farthestDist = 0;
BSONObj currObj;
int results = 0;
while ((results < numWanted) && Runner::RUNNER_ADVANCED == runner->getNext(&currObj, NULL)) {
// cout << "result is " << currObj.toString() << endl;
double dist = currObj["$dis"].number() * distanceMultiplier;
// cout << std::setprecision(10) << "HK GEON mul'd dist is " << dist << " raw dist is " << currObj["$dis"].number() << endl;
totalDistance += dist;
if (dist > farthestDist) { farthestDist = dist; }
BSONObjBuilder oneResultBuilder(
resultBuilder.subobjStart(BSONObjBuilder::numStr(results)));
oneResultBuilder.append("dis", dist);
if (includeLocs) {
oneResultBuilder.appendAs(currObj["$pt"], "loc");
}
// strip out '$dis' and '$pt' and the rest gets added as 'obj'.
BSONObjIterator resIt(currObj);
BSONObjBuilder resBob;
while (resIt.more()) {
BSONElement elt = resIt.next();
if (!mongoutils::str::equals("$pt", elt.fieldName())
&& !mongoutils::str::equals("$dis", elt.fieldName())) {
resBob.append(elt);
}
}
oneResultBuilder.append("obj", resBob.obj());
oneResultBuilder.done();
++results;
}
resultBuilder.done();
// Fill out the stats subobj.
BSONObjBuilder stats(result.subobjStart("stats"));
// Fill in nscanned from the explain.
TypeExplain* bareExplain;
Status res = runner->getExplainPlan(&bareExplain);
if (res.isOK()) {
auto_ptr<TypeExplain> explain(bareExplain);
stats.append("nscanned", explain->getNScanned());
stats.append("objectsLoaded", explain->getNScannedObjects());
}
stats.append("avgDistance", totalDistance / results);
stats.append("maxDistance", farthestDist);
stats.append("time", cc().curop()->elapsedMillis());
stats.done();
return true;
}
示例9: formatSingleField
//.........这里部分代码省略.........
builder.append(fieldName,values);
break;
}
case FieldDescriptor::CPPTYPE_STRING: { //= 9, // TYPE_STRING, TYPE_BYTES
std::vector<std::string> values;
values.reserve(fieldsize);
for (int i = 0; i < fieldsize; ++i) {
values.push_back(reflection->GetRepeatedString(message,field,i));
}
builder.append(fieldName,values);
break;
}
case FieldDescriptor::CPPTYPE_ENUM: { //= 8, // TYPE_ENUM
std::vector<std::string> values;
values.reserve(fieldsize);
for (int i = 0; i < fieldsize; ++i) {
values.push_back(reflection->GetRepeatedEnum(message,field,i)->name());
}
builder.append(fieldName,values);
break;
}
case FieldDescriptor::CPPTYPE_MESSAGE: { //= 10, // TYPE_MESSAGE, TYPE_GROUP
BSONObjBuilder sub(builder.subarrayStart(fieldName));
for (int i = 0; i < fieldsize; ++i) {
char number[16] = {0};
sprintf(number, "%d", i);
BSONObjBuilder obj(sub.subobjStart(number));
formatMessage(reflection->GetRepeatedMessage(message, field, i), obj);
obj.done();
}
sub.done();
break;
}
default: {
break;
}
}// end switch
}
else { //not repeated
switch (/*cppType*/field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: { //= 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32
builder.append(fieldName, reflection->GetInt32(message,field));
break;
}
case FieldDescriptor::CPPTYPE_INT64: { //= 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64
builder.append(fieldName,
static_cast<long long>(reflection->GetInt64(message,field)));
break;
}
示例10: run
bool run(const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
_runCalled = true;
long long start = Listener::getElapsedTimeMillis();
BSONObjBuilder timeBuilder(256);
const ClientBasic* myClientBasic = ClientBasic::getCurrent();
AuthorizationManager* authManager = myClientBasic->getAuthorizationManager();
// --- basic fields that are global
result.append("host", prettyHostName() );
result.append("version", versionString);
result.append("process",cmdLine.binaryName);
result.append("pid", (int)getpid());
result.append("uptime",(double) (time(0)-cmdLine.started));
result.append("uptimeMillis", (long long)(curTimeMillis64()-_started));
result.append("uptimeEstimate",(double) (start/1000));
result.appendDate( "localTime" , jsTime() );
timeBuilder.appendNumber( "after basic" , Listener::getElapsedTimeMillis() - start );
// --- all sections
for ( SectionMap::const_iterator i = _sections->begin(); i != _sections->end(); ++i ) {
ServerStatusSection* section = i->second;
std::vector<Privilege> requiredPrivileges;
section->addRequiredPrivileges(&requiredPrivileges);
if (!authManager->checkAuthForPrivileges(requiredPrivileges).isOK())
continue;
bool include = section->includeByDefault();
BSONElement e = cmdObj[section->getSectionName()];
if ( e.type() ) {
include = e.trueValue();
}
if ( ! include )
continue;
BSONObj data = section->generateSection(e);
if ( data.isEmpty() )
continue;
result.append( section->getSectionName(), data );
timeBuilder.appendNumber( static_cast<string>(str::stream() << "after " << section->getSectionName()),
Listener::getElapsedTimeMillis() - start );
}
// --- counters
if ( MetricTree::theMetricTree ) {
MetricTree::theMetricTree->appendTo( result );
}
// --- some hard coded global things hard to pull out
{
RamLog* rl = RamLog::get( "warnings" );
massert(15880, "no ram log for warnings?" , rl);
if (rl->lastWrite() >= time(0)-(10*60)){ // only show warnings from last 10 minutes
vector<const char*> lines;
rl->get( lines );
BSONArrayBuilder arr( result.subarrayStart( "warnings" ) );
for ( unsigned i=std::max(0,(int)lines.size()-10); i<lines.size(); i++ )
arr.append( lines[i] );
arr.done();
}
}
timeBuilder.appendNumber( "at end" , Listener::getElapsedTimeMillis() - start );
if ( Listener::getElapsedTimeMillis() - start > 1000 ) {
BSONObj t = timeBuilder.obj();
log() << "serverStatus was very slow: " << t << endl;
result.append( "timing" , t );
}
return true;
}
示例11: appendReplicationInfo
void appendReplicationInfo(OperationContext* txn, BSONObjBuilder& result, int level) {
ReplicationCoordinator* replCoord = getGlobalReplicationCoordinator();
if (replCoord->getSettings().usingReplSets()) {
IsMasterResponse isMasterResponse;
replCoord->fillIsMasterForReplSet(&isMasterResponse);
result.appendElements(isMasterResponse.toBSON());
if (level) {
replCoord->appendSlaveInfoData(&result);
}
return;
}
// TODO(dannenberg) replAllDead is bad and should be removed when master slave is removed
if (replAllDead) {
result.append("ismaster", 0);
string s = string("dead: ") + replAllDead;
result.append("info", s);
} else {
result.appendBool("ismaster",
getGlobalReplicationCoordinator()->isMasterForReportingPurposes());
}
if (level) {
BSONObjBuilder sources(result.subarrayStart("sources"));
int n = 0;
list<BSONObj> src;
{
const char* localSources = "local.sources";
AutoGetCollectionForRead ctx(txn, localSources);
unique_ptr<PlanExecutor> exec(
InternalPlanner::collectionScan(txn, localSources, ctx.getCollection()));
BSONObj obj;
PlanExecutor::ExecState state;
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
src.push_back(obj);
}
}
for (list<BSONObj>::const_iterator i = src.begin(); i != src.end(); i++) {
BSONObj s = *i;
BSONObjBuilder bb;
bb.append(s["host"]);
string sourcename = s["source"].valuestr();
if (sourcename != "main")
bb.append(s["source"]);
{
BSONElement e = s["syncedTo"];
BSONObjBuilder t(bb.subobjStart("syncedTo"));
t.appendDate("time", e.timestampTime());
t.append("inc", e.timestampInc());
t.done();
}
if (level > 1) {
wassert(!txn->lockState()->isLocked());
// note: there is no so-style timeout on this connection; perhaps we should have
// one.
ScopedDbConnection conn(s["host"].valuestr());
DBClientConnection* cliConn = dynamic_cast<DBClientConnection*>(&conn.conn());
if (cliConn && replAuthenticate(cliConn)) {
BSONObj first = conn->findOne((string) "local.oplog.$" + sourcename,
Query().sort(BSON("$natural" << 1)));
BSONObj last = conn->findOne((string) "local.oplog.$" + sourcename,
Query().sort(BSON("$natural" << -1)));
bb.appendDate("masterFirst", first["ts"].timestampTime());
bb.appendDate("masterLast", last["ts"].timestampTime());
const auto lag = (last["ts"].timestampTime() - s["syncedTo"].timestampTime());
bb.append("lagSeconds", durationCount<Milliseconds>(lag) / 1000.0);
}
conn.done();
}
sources.append(BSONObjBuilder::numStr(n++), bb.obj());
}
sources.done();
replCoord->appendSlaveInfoData(&result);
}
}
示例12: toBSON
BSONObj ReplSetConfig::toBSON() const {
BSONObjBuilder configBuilder;
configBuilder.append(kIdFieldName, _replSetName);
configBuilder.appendIntOrLL(kVersionFieldName, _version);
if (_configServer) {
// Only include "configsvr" field if true
configBuilder.append(kConfigServerFieldName, _configServer);
}
// Only include writeConcernMajorityJournalDefault if it is not the default version for this
// ProtocolVersion to prevent breaking cross version-3.2.1 compatibilty of ReplSetConfigs.
if (_protocolVersion > 0) {
configBuilder.append(kProtocolVersionFieldName, _protocolVersion);
// Only include writeConcernMajorityJournalDefault if it is not the default version for this
// ProtocolVersion to prevent breaking cross version-3.2.1 compatibilty of
// ReplSetConfigs.
if (!_writeConcernMajorityJournalDefault) {
configBuilder.append(kWriteConcernMajorityJournalDefaultFieldName,
_writeConcernMajorityJournalDefault);
}
} else if (_writeConcernMajorityJournalDefault) {
configBuilder.append(kWriteConcernMajorityJournalDefaultFieldName,
_writeConcernMajorityJournalDefault);
}
BSONArrayBuilder members(configBuilder.subarrayStart(kMembersFieldName));
for (MemberIterator mem = membersBegin(); mem != membersEnd(); mem++) {
members.append(mem->toBSON(getTagConfig()));
}
members.done();
BSONObjBuilder settingsBuilder(configBuilder.subobjStart(kSettingsFieldName));
settingsBuilder.append(kChainingAllowedFieldName, _chainingAllowed);
settingsBuilder.appendIntOrLL(kHeartbeatIntervalFieldName,
durationCount<Milliseconds>(_heartbeatInterval));
settingsBuilder.appendIntOrLL(kHeartbeatTimeoutFieldName,
durationCount<Seconds>(_heartbeatTimeoutPeriod));
settingsBuilder.appendIntOrLL(kElectionTimeoutFieldName,
durationCount<Milliseconds>(_electionTimeoutPeriod));
settingsBuilder.appendIntOrLL(kCatchUpTimeoutFieldName,
durationCount<Milliseconds>(_catchUpTimeoutPeriod));
settingsBuilder.appendIntOrLL(kCatchUpTakeoverDelayFieldName,
durationCount<Milliseconds>(_catchUpTakeoverDelay));
BSONObjBuilder gleModes(settingsBuilder.subobjStart(kGetLastErrorModesFieldName));
for (StringMap<ReplSetTagPattern>::const_iterator mode = _customWriteConcernModes.begin();
mode != _customWriteConcernModes.end();
++mode) {
if (mode->first[0] == '$') {
// Filter out internal modes
continue;
}
BSONObjBuilder modeBuilder(gleModes.subobjStart(mode->first));
for (ReplSetTagPattern::ConstraintIterator itr = mode->second.constraintsBegin();
itr != mode->second.constraintsEnd();
itr++) {
modeBuilder.append(_tagConfig.getTagKey(ReplSetTag(itr->getKeyIndex(), 0)),
itr->getMinCount());
}
modeBuilder.done();
}
gleModes.done();
settingsBuilder.append(kGetLastErrorDefaultsFieldName, _defaultWriteConcern.toBSON());
if (_replicaSetId.isSet()) {
settingsBuilder.append(kReplicaSetIdFieldName, _replicaSetId);
}
settingsBuilder.done();
return configBuilder.obj();
}
示例13: queryGeo
bool run2DSphereGeoNear(const IndexDetails &id, BSONObj& cmdObj, string& errmsg,
BSONObjBuilder& result) {
S2IndexType *idxType = static_cast<S2IndexType*>(id.getSpec().getType());
verify(&id == idxType->getDetails());
// We support both "num" and "limit" options to control limit
int numWanted = 100;
const char* limitName = cmdObj["num"].isNumber() ? "num" : "limit";
if (cmdObj[limitName].isNumber()) {
numWanted = cmdObj[limitName].numberInt();
verify(numWanted >= 0);
}
// Don't count any docs twice. Isn't this default behavior? Or will yields screw this up?
//bool uniqueDocs = false;
//if (!cmdObj["uniqueDocs"].eoo()) uniqueDocs = cmdObj["uniqueDocs"].trueValue();
// Add the location information to each result as a field with name 'loc'.
bool includeLocs = false;
if (!cmdObj["includeLocs"].eoo()) includeLocs = cmdObj["includeLocs"].trueValue();
// The actual query point
uassert(16551, "'near' param missing/invalid", !cmdObj["near"].eoo());
BSONObj nearObj = cmdObj["near"].embeddedObject();
// nearObj must be a point.
uassert(16571, "near must be called with a point, called with " + nearObj.toString(),
GeoParser::isPoint(nearObj));
// The non-near query part.
BSONObj query;
if (cmdObj["query"].isABSONObj())
query = cmdObj["query"].embeddedObject();
// The farthest away we're willing to look.
double maxDistance = numeric_limits<double>::max();
if (cmdObj["maxDistance"].isNumber())
maxDistance = cmdObj["maxDistance"].number();
vector<string> geoFieldNames;
idxType->getGeoFieldNames(&geoFieldNames);
uassert(16552, "geoNear called but no indexed geo fields?", 1 == geoFieldNames.size());
QueryGeometry queryGeo(geoFieldNames[0]);
uassert(16553, "geoNear couldn't parse geo: " + nearObj.toString(), queryGeo.parseFrom(nearObj));
vector<QueryGeometry> regions;
regions.push_back(queryGeo);
scoped_ptr<S2NearCursor> cursor(new S2NearCursor(idxType->keyPattern(), idxType->getDetails(),
query, regions, idxType->getParams(),
numWanted, maxDistance));
double totalDistance = 0;
int results = 0;
BSONObjBuilder resultBuilder(result.subarrayStart("results"));
double farthestDist = 0;
while (cursor->ok()) {
double dist = cursor->currentDistance();
totalDistance += dist;
if (dist > farthestDist) { farthestDist = dist; }
BSONObjBuilder oneResultBuilder(resultBuilder.subobjStart(BSONObjBuilder::numStr(results)));
oneResultBuilder.append("dis", dist);
if (includeLocs) {
BSONElementSet geoFieldElements;
cursor->current().getFieldsDotted(geoFieldNames[0], geoFieldElements, false);
for (BSONElementSet::iterator oi = geoFieldElements.begin();
oi != geoFieldElements.end(); ++oi) {
if (oi->isABSONObj()) {
oneResultBuilder.appendAs(*oi, "loc");
}
}
}
oneResultBuilder.append("obj", cursor->current());
oneResultBuilder.done();
++results;
cursor->advance();
}
resultBuilder.done();
BSONObjBuilder stats(result.subobjStart("stats"));
stats.append("time", cc().curop()->elapsedMillis());
stats.appendNumber("nscanned", cursor->nscanned());
stats.append("avgDistance", totalDistance / results);
stats.append("maxDistance", farthestDist);
stats.done();
return true;
}
示例14: shardCollection
Status CatalogManagerReplicaSet::shardCollection(OperationContext* txn,
const string& ns,
const ShardKeyPattern& fieldsAndOrder,
bool unique,
const vector<BSONObj>& initPoints,
const set<ShardId>& initShardIds) {
// Lock the collection globally so that no other mongos can try to shard or drop the collection
// at the same time.
auto scopedDistLock = getDistLockManager()->lock(ns, "shardCollection");
if (!scopedDistLock.isOK()) {
return scopedDistLock.getStatus();
}
auto status = getDatabase(txn, nsToDatabase(ns));
if (!status.isOK()) {
return status.getStatus();
}
ShardId dbPrimaryShardId = status.getValue().value.getPrimary();
const auto primaryShard = grid.shardRegistry()->getShard(txn, dbPrimaryShardId);
{
// In 3.0 and prior we include this extra safety check that the collection is not getting
// sharded concurrently by two different mongos instances. It is not 100%-proof, but it
// reduces the chance that two invocations of shard collection will step on each other's
// toes. Now we take the distributed lock so going forward this check won't be necessary
// but we leave it around for compatibility with other mongoses from 3.0.
// TODO(spencer): Remove this after 3.2 ships.
auto countStatus = _runCountCommandOnConfig(
txn, NamespaceString(ChunkType::ConfigNS), BSON(ChunkType::ns(ns)));
if (!countStatus.isOK()) {
return countStatus.getStatus();
}
if (countStatus.getValue() > 0) {
return Status(ErrorCodes::AlreadyInitialized,
str::stream() << "collection " << ns << " already sharded with "
<< countStatus.getValue() << " chunks.");
}
}
// Record start in changelog
{
BSONObjBuilder collectionDetail;
collectionDetail.append("shardKey", fieldsAndOrder.toBSON());
collectionDetail.append("collection", ns);
collectionDetail.append("primary", primaryShard->toString());
{
BSONArrayBuilder initialShards(collectionDetail.subarrayStart("initShards"));
for (const ShardId& shardId : initShardIds) {
initialShards.append(shardId);
}
}
collectionDetail.append("numChunks", static_cast<int>(initPoints.size() + 1));
logChange(txn,
txn->getClient()->clientAddress(true),
"shardCollection.start",
ns,
collectionDetail.obj());
}
shared_ptr<ChunkManager> manager(new ChunkManager(ns, fieldsAndOrder, unique));
manager->createFirstChunks(txn, dbPrimaryShardId, &initPoints, &initShardIds);
manager->loadExistingRanges(txn, nullptr);
CollectionInfo collInfo;
collInfo.useChunkManager(manager);
collInfo.save(txn, ns);
manager->reload(txn, true);
// Tell the primary mongod to refresh its data
// TODO: Think the real fix here is for mongos to just
// assume that all collections are sharded, when we get there
SetShardVersionRequest ssv = SetShardVersionRequest::makeForVersioningNoPersist(
grid.shardRegistry()->getConfigServerConnectionString(),
dbPrimaryShardId,
primaryShard->getConnString(),
NamespaceString(ns),
manager->getVersion(),
true);
auto ssvStatus = grid.shardRegistry()->runCommandWithNotMasterRetries(
txn, dbPrimaryShardId, "admin", ssv.toBSON());
if (!ssvStatus.isOK()) {
warning() << "could not update initial version of " << ns << " on shard primary "
<< dbPrimaryShardId << ssvStatus.getStatus();
}
logChange(txn,
txn->getClient()->clientAddress(true),
"shardCollection",
ns,
BSON("version" << manager->getVersion().toString()));
return Status::OK();
}
示例15: run
//.........这里部分代码省略.........
BSONElement eDistanceMultiplier = cmdObj["distanceMultiplier"];
if (!eDistanceMultiplier.eoo()) {
uassert(17296, "distanceMultiplier must be a number", eDistanceMultiplier.isNumber());
distanceMultiplier = eDistanceMultiplier.number();
uassert(17297, "distanceMultiplier must be non-negative", distanceMultiplier >= 0);
}
BSONObj projObj = BSON("$pt" << BSON("$meta" << LiteParsedQuery::metaGeoNearPoint) <<
"$dis" << BSON("$meta" << LiteParsedQuery::metaGeoNearDistance));
CanonicalQuery* cq;
const NamespaceString nss(dbname);
const WhereCallbackReal whereCallback(txn, nss.db());
if (!CanonicalQuery::canonicalize(ns,
rewritten,
BSONObj(),
projObj,
0,
numWanted,
BSONObj(),
&cq,
whereCallback).isOK()) {
errmsg = "Can't parse filter / create query";
return false;
}
PlanExecutor* rawExec;
if (!getExecutor(txn, collection, cq, &rawExec, 0).isOK()) {
errmsg = "can't get query runner";
return false;
}
auto_ptr<PlanExecutor> exec(rawExec);
const ScopedExecutorRegistration safety(exec.get());
double totalDistance = 0;
BSONObjBuilder resultBuilder(result.subarrayStart("results"));
double farthestDist = 0;
BSONObj currObj;
int results = 0;
while ((results < numWanted) && PlanExecutor::ADVANCED == exec->getNext(&currObj, NULL)) {
// Come up with the correct distance.
double dist = currObj["$dis"].number() * distanceMultiplier;
totalDistance += dist;
if (dist > farthestDist) { farthestDist = dist; }
// Strip out '$dis' and '$pt' from the result obj. The rest gets added as 'obj'
// in the command result.
BSONObjIterator resIt(currObj);
BSONObjBuilder resBob;
while (resIt.more()) {
BSONElement elt = resIt.next();
if (!mongoutils::str::equals("$pt", elt.fieldName())
&& !mongoutils::str::equals("$dis", elt.fieldName())) {
resBob.append(elt);
}
}
BSONObj resObj = resBob.obj();
// Don't make a too-big result object.
if (resultBuilder.len() + resObj.objsize()> BSONObjMaxUserSize) {
warning() << "Too many geoNear results for query " << rewritten.toString()
<< ", truncating output.";
break;
}
// Add the next result to the result builder.
BSONObjBuilder oneResultBuilder(
resultBuilder.subobjStart(BSONObjBuilder::numStr(results)));
oneResultBuilder.append("dis", dist);
if (includeLocs) {
oneResultBuilder.appendAs(currObj["$pt"], "loc");
}
oneResultBuilder.append("obj", resObj);
oneResultBuilder.done();
++results;
}
resultBuilder.done();
// Fill out the stats subobj.
BSONObjBuilder stats(result.subobjStart("stats"));
// Fill in nscanned from the explain.
PlanSummaryStats summary;
Explain::getSummaryStats(exec.get(), &summary);
stats.appendNumber("nscanned", summary.totalKeysExamined);
stats.appendNumber("objectsLoaded", summary.totalDocsExamined);
stats.append("avgDistance", totalDistance / results);
stats.append("maxDistance", farthestDist);
stats.append("time", txn->getCurOp()->elapsedMillis());
stats.done();
return true;
}