summaryrefslogtreecommitdiff
path: root/shell
diff options
context:
space:
mode:
Diffstat (limited to 'shell')
-rw-r--r--shell/collection.js844
-rw-r--r--shell/db.js827
-rw-r--r--shell/dbshell.cpp815
-rw-r--r--shell/mongo.js95
-rw-r--r--shell/mongo_vstudio.cpp4020
-rw-r--r--shell/mr.js95
-rwxr-xr-xshell/msvc/mongo.icobin1078 -> 0 bytes
-rw-r--r--shell/msvc/mongo.sln20
-rw-r--r--shell/msvc/mongo.vcxproj262
-rw-r--r--shell/msvc/mongo.vcxproj.filters288
-rw-r--r--shell/query.js317
-rwxr-xr-xshell/servers.js2052
-rw-r--r--shell/shell_utils.cpp959
-rw-r--r--shell/utils.h46
-rw-r--r--shell/utils.js1694
-rw-r--r--shell/utils_sh.js114
16 files changed, 0 insertions, 12448 deletions
diff --git a/shell/collection.js b/shell/collection.js
deleted file mode 100644
index 1b8e4880564..00000000000
--- a/shell/collection.js
+++ /dev/null
@@ -1,844 +0,0 @@
-// @file collection.js - DBCollection support in the mongo shell
-// db.colName is a DBCollection object
-// or db["colName"]
-
-if ( ( typeof DBCollection ) == "undefined" ){
- DBCollection = function( mongo , db , shortName , fullName ){
- this._mongo = mongo;
- this._db = db;
- this._shortName = shortName;
- this._fullName = fullName;
-
- this.verify();
- }
-}
-
-DBCollection.prototype.verify = function(){
- assert( this._fullName , "no fullName" );
- assert( this._shortName , "no shortName" );
- assert( this._db , "no db" );
-
- assert.eq( this._fullName , this._db._name + "." + this._shortName , "name mismatch" );
-
- assert( this._mongo , "no mongo in DBCollection" );
-}
-
-DBCollection.prototype.getName = function(){
- return this._shortName;
-}
-
-DBCollection.prototype.help = function () {
- var shortName = this.getName();
- print("DBCollection help");
- print("\tdb." + shortName + ".find().help() - show DBCursor help");
- print("\tdb." + shortName + ".count()");
- print("\tdb." + shortName + ".dataSize()");
- print("\tdb." + shortName + ".distinct( key ) - eg. db." + shortName + ".distinct( 'x' )");
- print("\tdb." + shortName + ".drop() drop the collection");
- print("\tdb." + shortName + ".dropIndex(name)");
- print("\tdb." + shortName + ".dropIndexes()");
- print("\tdb." + shortName + ".ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups");
- print("\tdb." + shortName + ".reIndex()");
- print("\tdb." + shortName + ".find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.");
- print("\t e.g. db." + shortName + ".find( {x:77} , {name:1, x:1} )");
- print("\tdb." + shortName + ".find(...).count()");
- print("\tdb." + shortName + ".find(...).limit(n)");
- print("\tdb." + shortName + ".find(...).skip(n)");
- print("\tdb." + shortName + ".find(...).sort(...)");
- print("\tdb." + shortName + ".findOne([query])");
- print("\tdb." + shortName + ".findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )");
- print("\tdb." + shortName + ".getDB() get DB object associated with collection");
- print("\tdb." + shortName + ".getIndexes()");
- print("\tdb." + shortName + ".group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )");
- print("\tdb." + shortName + ".mapReduce( mapFunction , reduceFunction , <optional params> )");
- print("\tdb." + shortName + ".remove(query)");
- print("\tdb." + shortName + ".renameCollection( newName , <dropTarget> ) renames the collection.");
- print("\tdb." + shortName + ".runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name");
- print("\tdb." + shortName + ".save(obj)");
- print("\tdb." + shortName + ".stats()");
- print("\tdb." + shortName + ".storageSize() - includes free space allocated to this collection");
- print("\tdb." + shortName + ".totalIndexSize() - size in bytes of all the indexes");
- print("\tdb." + shortName + ".totalSize() - storage allocated for all data and indexes");
- print("\tdb." + shortName + ".update(query, object[, upsert_bool, multi_bool])");
- print("\tdb." + shortName + ".validate( <full> ) - SLOW");;
- print("\tdb." + shortName + ".getShardVersion() - only for use with sharding");
- print("\tdb." + shortName + ".getShardDistribution() - prints statistics about data distribution in the cluster");
- return __magicNoPrint;
-}
-
-DBCollection.prototype.getFullName = function(){
- return this._fullName;
-}
-DBCollection.prototype.getMongo = function(){
- return this._db.getMongo();
-}
-DBCollection.prototype.getDB = function(){
- return this._db;
-}
-
-DBCollection.prototype._dbCommand = function( cmd , params ){
- if ( typeof( cmd ) == "object" )
- return this._db._dbCommand( cmd );
-
- var c = {};
- c[cmd] = this.getName();
- if ( params )
- Object.extend( c , params );
- return this._db._dbCommand( c );
-}
-
-DBCollection.prototype.runCommand = DBCollection.prototype._dbCommand;
-
-DBCollection.prototype._massageObject = function( q ){
- if ( ! q )
- return {};
-
- var type = typeof q;
-
- if ( type == "function" )
- return { $where : q };
-
- if ( q.isObjectId )
- return { _id : q };
-
- if ( type == "object" )
- return q;
-
- if ( type == "string" ){
- if ( q.length == 24 )
- return { _id : q };
-
- return { $where : q };
- }
-
- throw "don't know how to massage : " + type;
-
-}
-
-
-DBCollection.prototype._validateObject = function( o ){
- if ( o._ensureSpecial && o._checkModify )
- throw "can't save a DBQuery object";
-}
-
-DBCollection._allowedFields = { $id : 1 , $ref : 1 , $db : 1 , $MinKey : 1, $MaxKey : 1 };
-
-DBCollection.prototype._validateForStorage = function( o ){
- this._validateObject( o );
- for ( var k in o ){
- if ( k.indexOf( "." ) >= 0 ) {
- throw "can't have . in field names [" + k + "]" ;
- }
-
- if ( k.indexOf( "$" ) == 0 && ! DBCollection._allowedFields[k] ) {
- throw "field names cannot start with $ [" + k + "]";
- }
-
- if ( o[k] !== null && typeof( o[k] ) === "object" ) {
- this._validateForStorage( o[k] );
- }
- }
-};
-
-
-DBCollection.prototype.find = function( query , fields , limit , skip ){
- return new DBQuery( this._mongo , this._db , this ,
- this._fullName , this._massageObject( query ) , fields , limit , skip );
-}
-
-DBCollection.prototype.findOne = function( query , fields ){
- var cursor = this._mongo.find( this._fullName , this._massageObject( query ) || {} , fields ,
- -1 /* limit */ , 0 /* skip*/, 0 /* batchSize */ , 0 /* options */ );
- if ( ! cursor.hasNext() )
- return null;
- var ret = cursor.next();
- if ( cursor.hasNext() ) throw "findOne has more than 1 result!";
- if ( ret.$err )
- throw "error " + tojson( ret );
- return ret;
-}
-
-DBCollection.prototype.insert = function( obj , _allow_dot ){
- if ( ! obj )
- throw "no object passed to insert!";
- if ( ! _allow_dot ) {
- this._validateForStorage( obj );
- }
- if ( typeof( obj._id ) == "undefined" ){
- var tmp = obj; // don't want to modify input
- obj = {_id: new ObjectId()};
- for (var key in tmp){
- obj[key] = tmp[key];
- }
- }
- this._mongo.insert( this._fullName , obj );
- this._lastID = obj._id;
-}
-
-DBCollection.prototype.remove = function( t , justOne ){
- for ( var k in t ){
- if ( k == "_id" && typeof( t[k] ) == "undefined" ){
- throw "can't have _id set to undefined in a remove expression"
- }
- }
- this._mongo.remove( this._fullName , this._massageObject( t ) , justOne ? true : false );
-}
-
-DBCollection.prototype.update = function( query , obj , upsert , multi ){
- assert( query , "need a query" );
- assert( obj , "need an object" );
-
- var firstKey = null;
- for (var k in obj) { firstKey = k; break; }
-
- if (firstKey != null && firstKey[0] == '$') {
- // for mods we only validate partially, for example keys may have dots
- this._validateObject( obj );
- } else {
- // we're basically inserting a brand new object, do full validation
- this._validateForStorage( obj );
- }
- this._mongo.update( this._fullName , query , obj , upsert ? true : false , multi ? true : false );
-}
-
-DBCollection.prototype.save = function( obj ){
- if ( obj == null || typeof( obj ) == "undefined" )
- throw "can't save a null";
-
- if ( typeof( obj ) == "number" || typeof( obj) == "string" )
- throw "can't save a number or string"
-
- if ( typeof( obj._id ) == "undefined" ){
- obj._id = new ObjectId();
- return this.insert( obj );
- }
- else {
- return this.update( { _id : obj._id } , obj , true );
- }
-}
-
-DBCollection.prototype._genIndexName = function( keys ){
- var name = "";
- for ( var k in keys ){
- var v = keys[k];
- if ( typeof v == "function" )
- continue;
-
- if ( name.length > 0 )
- name += "_";
- name += k + "_";
-
- if ( typeof v == "number" )
- name += v;
- }
- return name;
-}
-
-DBCollection.prototype._indexSpec = function( keys, options ) {
- var ret = { ns : this._fullName , key : keys , name : this._genIndexName( keys ) };
-
- if ( ! options ){
- }
- else if ( typeof ( options ) == "string" )
- ret.name = options;
- else if ( typeof ( options ) == "boolean" )
- ret.unique = true;
- else if ( typeof ( options ) == "object" ){
- if ( options.length ){
- var nb = 0;
- for ( var i=0; i<options.length; i++ ){
- if ( typeof ( options[i] ) == "string" )
- ret.name = options[i];
- else if ( typeof( options[i] ) == "boolean" ){
- if ( options[i] ){
- if ( nb == 0 )
- ret.unique = true;
- if ( nb == 1 )
- ret.dropDups = true;
- }
- nb++;
- }
- }
- }
- else {
- Object.extend( ret , options );
- }
- }
- else {
- throw "can't handle: " + typeof( options );
- }
- /*
- return ret;
-
- var name;
- var nTrue = 0;
-
- if ( ! isObject( options ) ) {
- options = [ options ];
- }
-
- if ( options.length ){
- for( var i = 0; i < options.length; ++i ) {
- var o = options[ i ];
- if ( isString( o ) ) {
- ret.name = o;
- } else if ( typeof( o ) == "boolean" ) {
- if ( o ) {
- ++nTrue;
- }
- }
- }
- if ( nTrue > 0 ) {
- ret.unique = true;
- }
- if ( nTrue > 1 ) {
- ret.dropDups = true;
- }
- }
-*/
- return ret;
-}
-
-DBCollection.prototype.createIndex = function( keys , options ){
- var o = this._indexSpec( keys, options );
- this._db.getCollection( "system.indexes" ).insert( o , true );
-}
-
-DBCollection.prototype.ensureIndex = function( keys , options ){
- var name = this._indexSpec( keys, options ).name;
- this._indexCache = this._indexCache || {};
- if ( this._indexCache[ name ] ){
- return;
- }
-
- this.createIndex( keys , options );
- if ( this.getDB().getLastError() == "" ) {
- this._indexCache[name] = true;
- }
-}
-
-DBCollection.prototype.resetIndexCache = function(){
- this._indexCache = {};
-}
-
-DBCollection.prototype.reIndex = function() {
- return this._db.runCommand({ reIndex: this.getName() });
-}
-
-DBCollection.prototype.dropIndexes = function(){
- this.resetIndexCache();
-
- var res = this._db.runCommand( { deleteIndexes: this.getName(), index: "*" } );
- assert( res , "no result from dropIndex result" );
- if ( res.ok )
- return res;
-
- if ( res.errmsg.match( /not found/ ) )
- return res;
-
- throw "error dropping indexes : " + tojson( res );
-}
-
-
-DBCollection.prototype.drop = function(){
- if ( arguments.length > 0 )
- throw "drop takes no argument";
- this.resetIndexCache();
- var ret = this._db.runCommand( { drop: this.getName() } );
- if ( ! ret.ok ){
- if ( ret.errmsg == "ns not found" )
- return false;
- throw "drop failed: " + tojson( ret );
- }
- return true;
-}
-
-DBCollection.prototype.findAndModify = function(args){
- var cmd = { findandmodify: this.getName() };
- for (var key in args){
- cmd[key] = args[key];
- }
-
- var ret = this._db.runCommand( cmd );
- if ( ! ret.ok ){
- if (ret.errmsg == "No matching object found"){
- return null;
- }
- throw "findAndModifyFailed failed: " + tojson( ret.errmsg );
- }
- return ret.value;
-}
-
-DBCollection.prototype.renameCollection = function( newName , dropTarget ){
- return this._db._adminCommand( { renameCollection : this._fullName ,
- to : this._db._name + "." + newName ,
- dropTarget : dropTarget } )
-}
-
-DBCollection.prototype.validate = function(full) {
- var cmd = { validate: this.getName() };
-
- if (typeof(full) == 'object') // support arbitrary options here
- Object.extend(cmd, full);
- else
- cmd.full = full;
-
- var res = this._db.runCommand( cmd );
-
- if (typeof(res.valid) == 'undefined') {
- // old-style format just put everything in a string. Now using proper fields
-
- res.valid = false;
-
- var raw = res.result || res.raw;
-
- if ( raw ){
- var str = "-" + tojson( raw );
- res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );
-
- var p = /lastExtentSize:(\d+)/;
- var r = p.exec( str );
- if ( r ){
- res.lastExtentSize = Number( r[1] );
- }
- }
- }
-
- return res;
-}
-
-DBCollection.prototype.getShardVersion = function(){
- return this._db._adminCommand( { getShardVersion : this._fullName } );
-}
-
-DBCollection.prototype.getIndexes = function(){
- return this.getDB().getCollection( "system.indexes" ).find( { ns : this.getFullName() } ).toArray();
-}
-
-DBCollection.prototype.getIndices = DBCollection.prototype.getIndexes;
-DBCollection.prototype.getIndexSpecs = DBCollection.prototype.getIndexes;
-
-DBCollection.prototype.getIndexKeys = function(){
- return this.getIndexes().map(
- function(i){
- return i.key;
- }
- );
-}
-
-
-DBCollection.prototype.count = function( x ){
- return this.find( x ).count();
-}
-
-/**
- * Drop free lists. Normally not used.
- * Note this only does the collection itself, not the namespaces of its indexes (see cleanAll).
- */
-DBCollection.prototype.clean = function() {
- return this._dbCommand( { clean: this.getName() } );
-}
-
-
-
-/**
- * <p>Drop a specified index.</p>
- *
- * <p>
- * Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to
- * see example data.)
- * </p>
- *
- * <p>Note : alpha: space is not reclaimed </p>
- * @param {String} name of index to delete.
- * @return A result object. result.ok will be true if successful.
- */
-DBCollection.prototype.dropIndex = function(index) {
- assert(index , "need to specify index to dropIndex" );
-
- if ( ! isString( index ) && isObject( index ) )
- index = this._genIndexName( index );
-
- var res = this._dbCommand( "deleteIndexes" ,{ index: index } );
- this.resetIndexCache();
- return res;
-}
-
-DBCollection.prototype.copyTo = function( newName ){
- return this.getDB().eval(
- function( collName , newName ){
- var from = db[collName];
- var to = db[newName];
- to.ensureIndex( { _id : 1 } );
- var count = 0;
-
- var cursor = from.find();
- while ( cursor.hasNext() ){
- var o = cursor.next();
- count++;
- to.save( o );
- }
-
- return count;
- } , this.getName() , newName
- );
-}
-
-DBCollection.prototype.getCollection = function( subName ){
- return this._db.getCollection( this._shortName + "." + subName );
-}
-
-DBCollection.prototype.stats = function( scale ){
- return this._db.runCommand( { collstats : this._shortName , scale : scale } );
-}
-
-DBCollection.prototype.dataSize = function(){
- return this.stats().size;
-}
-
-DBCollection.prototype.storageSize = function(){
- return this.stats().storageSize;
-}
-
-DBCollection.prototype.totalIndexSize = function( verbose ){
- var stats = this.stats();
- if (verbose){
- for (var ns in stats.indexSizes){
- print( ns + "\t" + stats.indexSizes[ns] );
- }
- }
- return stats.totalIndexSize;
-}
-
-
-DBCollection.prototype.totalSize = function(){
- var total = this.storageSize();
- var mydb = this._db;
- var shortName = this._shortName;
- this.getIndexes().forEach(
- function( spec ){
- var coll = mydb.getCollection( shortName + ".$" + spec.name );
- var mysize = coll.storageSize();
- //print( coll + "\t" + mysize + "\t" + tojson( coll.validate() ) );
- total += coll.dataSize();
- }
- );
- return total;
-}
-
-
-DBCollection.prototype.convertToCapped = function( bytes ){
- if ( ! bytes )
- throw "have to specify # of bytes";
- return this._dbCommand( { convertToCapped : this._shortName , size : bytes } )
-}
-
-DBCollection.prototype.exists = function(){
- return this._db.system.namespaces.findOne( { name : this._fullName } );
-}
-
-DBCollection.prototype.isCapped = function(){
- var e = this.exists();
- return ( e && e.options && e.options.capped ) ? true : false;
-}
-
-DBCollection.prototype._distinct = function( keyString , query ){
- return this._dbCommand( { distinct : this._shortName , key : keyString , query : query || {} } );
- if ( ! res.ok )
- throw "distinct failed: " + tojson( res );
- return res.values;
-}
-
-DBCollection.prototype.distinct = function( keyString , query ){
- var res = this._distinct( keyString , query );
- if ( ! res.ok )
- throw "distinct failed: " + tojson( res );
- return res.values;
-}
-
-
-DBCollection.prototype.group = function( params ){
- params.ns = this._shortName;
- return this._db.group( params );
-}
-
-DBCollection.prototype.groupcmd = function( params ){
- params.ns = this._shortName;
- return this._db.groupcmd( params );
-}
-
-MapReduceResult = function( db , o ){
- Object.extend( this , o );
- this._o = o;
- this._keys = Object.keySet( o );
- this._db = db;
- if ( this.result != null ) {
- this._coll = this._db.getCollection( this.result );
- }
-}
-
-MapReduceResult.prototype._simpleKeys = function(){
- return this._o;
-}
-
-MapReduceResult.prototype.find = function(){
- if ( this.results )
- return this.results;
- return DBCollection.prototype.find.apply( this._coll , arguments );
-}
-
-MapReduceResult.prototype.drop = function(){
- if ( this._coll ) {
- return this._coll.drop();
- }
-}
-
-/**
-* just for debugging really
-*/
-MapReduceResult.prototype.convertToSingleObject = function(){
- var z = {};
- var it = this.results != null ? this.results : this._coll.find();
- it.forEach( function(a){ z[a._id] = a.value; } );
- return z;
-}
-
-DBCollection.prototype.convertToSingleObject = function(valueField){
- var z = {};
- this.find().forEach( function(a){ z[a._id] = a[valueField]; } );
- return z;
-}
-
-/**
-* @param optional object of optional fields;
-*/
-DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString ){
- var c = { mapreduce : this._shortName , map : map , reduce : reduce };
- assert( optionsOrOutString , "need to supply an optionsOrOutString" )
-
- if ( typeof( optionsOrOutString ) == "string" )
- c["out"] = optionsOrOutString;
- else
- Object.extend( c , optionsOrOutString );
-
- var raw = this._db.runCommand( c );
- if ( ! raw.ok ){
- __mrerror__ = raw;
- throw "map reduce failed:" + tojson(raw);
- }
- return new MapReduceResult( this._db , raw );
-
-}
-
-DBCollection.prototype.toString = function(){
- return this.getFullName();
-}
-
-DBCollection.prototype.toString = function(){
- return this.getFullName();
-}
-
-
-DBCollection.prototype.tojson = DBCollection.prototype.toString;
-
-DBCollection.prototype.shellPrint = DBCollection.prototype.toString;
-
-DBCollection.autocomplete = function(obj){
- var colls = DB.autocomplete(obj.getDB());
- var ret = [];
- for (var i=0; i<colls.length; i++){
- var c = colls[i];
- if (c.length <= obj.getName().length) continue;
- if (c.slice(0,obj.getName().length+1) != obj.getName()+'.') continue;
-
- ret.push(c.slice(obj.getName().length+1));
- }
- return ret;
-}
-
-
-// Sharding additions
-
-/*
-Usage :
-
-mongo <mongos>
-> load('path-to-file/shardingAdditions.js')
-Loading custom sharding extensions...
-true
-
-> var collection = db.getMongo().getCollection("foo.bar")
-> collection.getShardDistribution() // prints statistics related to the collection's data distribution
-
-> collection.getSplitKeysForChunks() // generates split points for all chunks in the collection, based on the
- // default maxChunkSize or alternately a specified chunk size
-> collection.getSplitKeysForChunks( 10 ) // Mb
-
-> var splitter = collection.getSplitKeysForChunks() // by default, the chunks are not split, the keys are just
- // found. A splitter function is returned which will actually
- // do the splits.
-
-> splitter() // ! Actually executes the splits on the cluster !
-
-*/
-
-DBCollection.prototype.getShardDistribution = function(){
-
- var stats = this.stats()
-
- if( ! stats.sharded ){
- print( "Collection " + this + " is not sharded." )
- return
- }
-
- var config = this.getMongo().getDB("config")
-
- var numChunks = 0
-
- for( var shard in stats.shards ){
-
- var shardDoc = config.shards.findOne({ _id : shard })
-
- print( "\nShard " + shard + " at " + shardDoc.host )
-
- var shardStats = stats.shards[ shard ]
-
- var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray()
-
- numChunks += chunks.length
-
- var estChunkData = shardStats.size / chunks.length
- var estChunkCount = Math.floor( shardStats.count / chunks.length )
-
- print( " data : " + sh._dataFormat( shardStats.size ) +
- " docs : " + shardStats.count +
- " chunks : " + chunks.length )
- print( " estimated data per chunk : " + sh._dataFormat( estChunkData ) )
- print( " estimated docs per chunk : " + estChunkCount )
-
- }
-
- print( "\nTotals" )
- print( " data : " + sh._dataFormat( stats.size ) +
- " docs : " + stats.count +
- " chunks : " + numChunks )
- for( var shard in stats.shards ){
-
- var shardStats = stats.shards[ shard ]
-
- var estDataPercent = Math.floor( shardStats.size / stats.size * 10000 ) / 100
- var estDocPercent = Math.floor( shardStats.count / stats.count * 10000 ) / 100
-
- print( " Shard " + shard + " contains " + estDataPercent + "% data, " + estDocPercent + "% docs in cluster, " +
- "avg obj size on shard : " + sh._dataFormat( stats.shards[ shard ].avgObjSize ) )
- }
-
- print( "\n" )
-
-}
-
-// In testing phase, use with caution
-DBCollection.prototype._getSplitKeysForChunks = function( chunkSize ){
-
- var stats = this.stats()
-
- if( ! stats.sharded ){
- print( "Collection " + this + " is not sharded." )
- return
- }
-
- var config = this.getMongo().getDB("config")
-
- if( ! chunkSize ){
- chunkSize = config.settings.findOne({ _id : "chunksize" }).value
- print( "Chunk size not set, using default of " + chunkSize + "Mb" )
- }
- else{
- print( "Using chunk size of " + chunkSize + "Mb" )
- }
-
- var shardDocs = config.shards.find().toArray()
-
- var allSplitPoints = {}
- var numSplits = 0
-
- for( var i = 0; i < shardDocs.length; i++ ){
-
- var shardDoc = shardDocs[i]
- var shard = shardDoc._id
- var host = shardDoc.host
- var sconn = new Mongo( host )
-
- var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray()
-
- print( "\nGetting split points for chunks on shard " + shard + " at " + host )
-
- var splitPoints = []
-
- for( var j = 0; j < chunks.length; j++ ){
- var chunk = chunks[j]
- var result = sconn.getDB("admin").runCommand({ splitVector : this + "", min : chunk.min, max : chunk.max, maxChunkSize : chunkSize })
- if( ! result.ok ){
- print( " Had trouble getting split keys for chunk " + sh._pchunk( chunk ) + " :\n" )
- printjson( result )
- }
- else{
- splitPoints = splitPoints.concat( result.splitKeys )
-
- if( result.splitKeys.length > 0 )
- print( " Added " + result.splitKeys.length + " split points for chunk " + sh._pchunk( chunk ) )
- }
- }
-
- print( "Total splits for shard " + shard + " : " + splitPoints.length )
-
- numSplits += splitPoints.length
- allSplitPoints[ shard ] = splitPoints
-
- }
-
- // Get most recent migration
- var migration = config.changelog.find({ what : /^move.*/ }).sort({ time : -1 }).limit( 1 ).toArray()
- if( migration.length == 0 )
- print( "\nNo migrations found in changelog." )
- else {
- migration = migration[0]
- print( "\nMost recent migration activity was on " + migration.ns + " at " + migration.time )
- }
-
- var admin = this.getMongo().getDB("admin")
- var coll = this
- var splitFunction = function(){
-
- // Turn off the balancer, just to be safe
- print( "Turning off balancer..." )
- config.settings.update({ _id : "balancer" }, { $set : { stopped : true } }, true )
- print( "Sleeping for 30s to allow balancers to detect change. To be extra safe, check config.changelog" +
- " for recent migrations." )
- sleep( 30000 )
-
- for( shard in allSplitPoints ){
- for( var i = 0; i < allSplitPoints[ shard ].length; i++ ){
- var splitKey = allSplitPoints[ shard ][i]
- print( "Splitting at " + tojson( splitKey ) )
- printjson( admin.runCommand({ split : coll + "", middle : splitKey }) )
- }
- }
-
- print( "Turning the balancer back on." )
- config.settings.update({ _id : "balancer" }, { $set : { stopped : false } } )
- sleep( 1 )
- }
-
- print( "\nGenerated " + numSplits + " split keys, run output function to perform splits.\n" +
- " ex : \n" +
- " > var splitter = <collection>.getSplitKeysForChunks()\n" +
- " > splitter() // Execute splits on cluster !\n" )
-
- return splitFunction
-
-}
-
-
-
-
diff --git a/shell/db.js b/shell/db.js
deleted file mode 100644
index 28923598ae7..00000000000
--- a/shell/db.js
+++ /dev/null
@@ -1,827 +0,0 @@
-// db.js
-
-if ( typeof DB == "undefined" ){
- DB = function( mongo , name ){
- this._mongo = mongo;
- this._name = name;
- }
-}
-
-DB.prototype.getMongo = function(){
- assert( this._mongo , "why no mongo!" );
- return this._mongo;
-}
-
-DB.prototype.getSiblingDB = function( name ){
- return this.getMongo().getDB( name );
-}
-
-DB.prototype.getSisterDB = DB.prototype.getSiblingDB;
-
-DB.prototype.getName = function(){
- return this._name;
-}
-
-DB.prototype.stats = function(scale){
- return this.runCommand( { dbstats : 1 , scale : scale } );
-}
-
-DB.prototype.getCollection = function( name ){
- return new DBCollection( this._mongo , this , name , this._name + "." + name );
-}
-
-DB.prototype.commandHelp = function( name ){
- var c = {};
- c[name] = 1;
- c.help = true;
- var res = this.runCommand( c );
- if ( ! res.ok )
- throw res.errmsg;
- return res.help;
-}
-
-DB.prototype.runCommand = function( obj ){
- if ( typeof( obj ) == "string" ){
- var n = {};
- n[obj] = 1;
- obj = n;
- }
- return this.getCollection( "$cmd" ).findOne( obj );
-}
-
-DB.prototype._dbCommand = DB.prototype.runCommand;
-
-DB.prototype.adminCommand = function( obj ){
- if ( this._name == "admin" )
- return this.runCommand( obj );
- return this.getSiblingDB( "admin" ).runCommand( obj );
-}
-
-DB.prototype._adminCommand = DB.prototype.adminCommand; // alias old name
-
-DB.prototype.addUser = function( username , pass, readOnly ){
- if ( pass == null || pass.length == 0 )
- throw "password can't be empty";
-
- readOnly = readOnly || false;
- var c = this.getCollection( "system.users" );
-
- var u = c.findOne( { user : username } ) || { user : username };
- u.readOnly = readOnly;
- u.pwd = hex_md5( username + ":mongo:" + pass );
-
- c.save( u );
- var le = this.getLastErrorObj();
- printjson( le )
- if ( le.err )
- throw "couldn't add user: " + le.err
- print( tojson( u ) );
-}
-
-DB.prototype.logout = function(){
- return this.runCommand({logout : 1});
-}
-
-DB.prototype.removeUser = function( username ){
- this.getCollection( "system.users" ).remove( { user : username } );
-}
-
-DB.prototype.__pwHash = function( nonce, username, pass ) {
- return hex_md5( nonce + username + hex_md5( username + ":mongo:" + pass ) );
-}
-
-DB.prototype.auth = function( username , pass ){
- var n = this.runCommand( { getnonce : 1 } );
-
- var a = this.runCommand(
- {
- authenticate : 1 ,
- user : username ,
- nonce : n.nonce ,
- key : this.__pwHash( n.nonce, username, pass )
- }
- );
-
- return a.ok;
-}
-
-/**
- Create a new collection in the database. Normally, collection creation is automatic. You would
- use this function if you wish to specify special options on creation.
-
- If the collection already exists, no action occurs.
-
- <p>Options:</p>
- <ul>
- <li>
- size: desired initial extent size for the collection. Must be <= 1000000000.
- for fixed size (capped) collections, this size is the total/max size of the
- collection.
- </li>
- <li>
- capped: if true, this is a capped collection (where old data rolls out).
- </li>
- <li> max: maximum number of objects if capped (optional).</li>
- </ul>
-
- <p>Example: </p>
-
- <code>db.createCollection("movies", { size: 10 * 1024 * 1024, capped:true } );</code>
-
- * @param {String} name Name of new collection to create
- * @param {Object} options Object with options for call. Options are listed above.
- * @return SOMETHING_FIXME
-*/
-DB.prototype.createCollection = function(name, opt) {
- var options = opt || {};
- var cmd = { create: name, capped: options.capped, size: options.size, max: options.max };
- if (options.autoIndexId != undefined)
- cmd.autoIndexId = options.autoIndexId;
- var res = this._dbCommand(cmd);
- return res;
-}
-
-/**
- * @deprecated use getProfilingStatus
- * Returns the current profiling level of this database
- * @return SOMETHING_FIXME or null on error
- */
-DB.prototype.getProfilingLevel = function() {
- var res = this._dbCommand( { profile: -1 } );
- return res ? res.was : null;
-}
-
-/**
- * @return the current profiling status
- * example { was : 0, slowms : 100 }
- * @return SOMETHING_FIXME or null on error
- */
-DB.prototype.getProfilingStatus = function() {
- var res = this._dbCommand( { profile: -1 } );
- if ( ! res.ok )
- throw "profile command failed: " + tojson( res );
- delete res.ok
- return res;
-}
-
-
-/**
- Erase the entire database. (!)
-
- * @return Object returned has member ok set to true if operation succeeds, false otherwise.
-*/
-DB.prototype.dropDatabase = function() {
- if ( arguments.length )
- throw "dropDatabase doesn't take arguments";
- return this._dbCommand( { dropDatabase: 1 } );
-}
-
-/**
- * Shuts down the database. Must be run while using the admin database.
- * @param opts Options for shutdown. Possible options are:
- * - force: (boolean) if the server should shut down, even if there is no
- * up-to-date slave
- * - timeoutSecs: (number) the server will continue checking over timeoutSecs
- * if any other servers have caught up enough for it to shut down.
- */
-DB.prototype.shutdownServer = function(opts) {
- if( "admin" != this._name ){
- return "shutdown command only works with the admin database; try 'use admin'";
- }
-
- cmd = {"shutdown" : 1};
- opts = opts || {};
- for (var o in opts) {
- cmd[o] = opts[o];
- }
-
- try {
- var res = this.runCommand(cmd);
- if( res )
- throw "shutdownServer failed: " + res.errmsg;
- throw "shutdownServer failed";
- }
- catch ( e ){
- assert( tojson( e ).indexOf( "error doing query: failed" ) >= 0 , "unexpected error: " + tojson( e ) );
- print( "server should be down..." );
- }
-}
-
-/**
- Clone database on another server to here.
- <p>
- Generally, you should dropDatabase() first as otherwise the cloned information will MERGE
- into whatever data is already present in this database. (That is however a valid way to use
- clone if you are trying to do something intentionally, such as union three non-overlapping
- databases into one.)
- <p>
- This is a low level administrative function will is not typically used.
-
- * @param {String} from Where to clone from (dbhostname[:port]). May not be this database
- (self) as you cannot clone to yourself.
- * @return Object returned has member ok set to true if operation succeeds, false otherwise.
- * See also: db.copyDatabase()
-*/
-DB.prototype.cloneDatabase = function(from) {
- assert( isString(from) && from.length );
- //this.resetIndexCache();
- return this._dbCommand( { clone: from } );
-}
-
-
-/**
- Clone collection on another server to here.
- <p>
- Generally, you should drop() first as otherwise the cloned information will MERGE
- into whatever data is already present in this collection. (That is however a valid way to use
- clone if you are trying to do something intentionally, such as union three non-overlapping
- collections into one.)
- <p>
- This is a low level administrative function is not typically used.
-
- * @param {String} from mongod instance from which to clnoe (dbhostname:port). May
- not be this mongod instance, as clone from self is not allowed.
- * @param {String} collection name of collection to clone.
- * @param {Object} query query specifying which elements of collection are to be cloned.
- * @return Object returned has member ok set to true if operation succeeds, false otherwise.
- * See also: db.cloneDatabase()
- */
-DB.prototype.cloneCollection = function(from, collection, query) {
- assert( isString(from) && from.length );
- assert( isString(collection) && collection.length );
- collection = this._name + "." + collection;
- query = query || {};
- //this.resetIndexCache();
- return this._dbCommand( { cloneCollection:collection, from:from, query:query } );
-}
-
-
-/**
- Copy database from one server or name to another server or name.
-
- Generally, you should dropDatabase() first as otherwise the copied information will MERGE
- into whatever data is already present in this database (and you will get duplicate objects
- in collections potentially.)
-
- For security reasons this function only works when executed on the "admin" db. However,
- if you have access to said db, you can copy any database from one place to another.
-
- This method provides a way to "rename" a database by copying it to a new db name and
- location. Additionally, it effectively provides a repair facility.
-
- * @param {String} fromdb database name from which to copy.
- * @param {String} todb database name to copy to.
- * @param {String} fromhost hostname of the database (and optionally, ":port") from which to
- copy the data. default if unspecified is to copy from self.
- * @return Object returned has member ok set to true if operation succeeds, false otherwise.
- * See also: db.clone()
-*/
-DB.prototype.copyDatabase = function(fromdb, todb, fromhost, username, password) {
- assert( isString(fromdb) && fromdb.length );
- assert( isString(todb) && todb.length );
- fromhost = fromhost || "";
- if ( username && password ) {
- var n = this._adminCommand( { copydbgetnonce : 1, fromhost:fromhost } );
- return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb, username:username, nonce:n.nonce, key:this.__pwHash( n.nonce, username, password ) } );
- } else {
- return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb } );
- }
-}
-
-/**
- Repair database.
-
- * @return Object returned has member ok set to true if operation succeeds, false otherwise.
-*/
-DB.prototype.repairDatabase = function() {
- return this._dbCommand( { repairDatabase: 1 } );
-}
-
-
-DB.prototype.help = function() {
- print("DB methods:");
- print("\tdb.addUser(username, password[, readOnly=false])");
- print("\tdb.auth(username, password)");
- print("\tdb.cloneDatabase(fromhost)");
- print("\tdb.commandHelp(name) returns the help for the command");
- print("\tdb.copyDatabase(fromdb, todb, fromhost)");
- print("\tdb.createCollection(name, { size : ..., capped : ..., max : ... } )");
- print("\tdb.currentOp() displays the current operation in the db");
- print("\tdb.dropDatabase()");
- print("\tdb.eval(func, args) run code server-side");
- print("\tdb.getCollection(cname) same as db['cname'] or db.cname");
- print("\tdb.getCollectionNames()");
- print("\tdb.getLastError() - just returns the err msg string");
- print("\tdb.getLastErrorObj() - return full status object");
- print("\tdb.getMongo() get the server connection object");
- print("\tdb.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair");
- print("\tdb.getName()");
- print("\tdb.getPrevError()");
- print("\tdb.getProfilingLevel() - deprecated");
- print("\tdb.getProfilingStatus() - returns if profiling is on and slow threshold ");
- print("\tdb.getReplicationInfo()");
- print("\tdb.getSiblingDB(name) get the db at the same server as this one");
- print("\tdb.isMaster() check replica primary status");
- print("\tdb.killOp(opid) kills the current operation in the db");
- print("\tdb.listCommands() lists all the db commands");
- print("\tdb.logout()");
- print("\tdb.printCollectionStats()");
- print("\tdb.printReplicationInfo()");
- print("\tdb.printSlaveReplicationInfo()");
- print("\tdb.printShardingStatus()");
- print("\tdb.removeUser(username)");
- print("\tdb.repairDatabase()");
- print("\tdb.resetError()");
- print("\tdb.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }");
- print("\tdb.serverStatus()");
- print("\tdb.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all");
- print("\tdb.shutdownServer()");
- print("\tdb.stats()");
- print("\tdb.version() current version of the server");
- print("\tdb.getMongo().setSlaveOk() allow queries on a replication slave server");
- print("\tdb.fsyncLock() flush data to disk and lock server for backups");
- print("\tdb.fsyncUnock() unlocks server following a db.fsyncLock()");
-
- return __magicNoPrint;
-}
-
-DB.prototype.printCollectionStats = function(){
- var mydb = this;
- this.getCollectionNames().forEach(
- function(z){
- print( z );
- printjson( mydb.getCollection(z).stats() );
- print( "---" );
- }
- );
-}
-
-/**
- * <p> Set profiling level for your db. Profiling gathers stats on query performance. </p>
- *
- * <p>Default is off, and resets to off on a database restart -- so if you want it on,
- * turn it on periodically. </p>
- *
- * <p>Levels :</p>
- * <ul>
- * <li>0=off</li>
- * <li>1=log very slow operations; optional argument slowms specifies slowness threshold</li>
- * <li>2=log all</li>
- * @param {String} level Desired level of profiling
- * @param {String} slowms For slow logging, query duration that counts as slow (default 100ms)
- * @return SOMETHING_FIXME or null on error
- */
-DB.prototype.setProfilingLevel = function(level,slowms) {
-
- if (level < 0 || level > 2) {
- throw { dbSetProfilingException : "input level " + level + " is out of range [0..2]" };
- }
-
- var cmd = { profile: level };
- if ( slowms )
- cmd["slowms"] = slowms;
- return this._dbCommand( cmd );
-}
-
-
-/**
- * <p> Evaluate a js expression at the database server.</p>
- *
- * <p>Useful if you need to touch a lot of data lightly; in such a scenario
- * the network transfer of the data could be a bottleneck. A good example
- * is "select count(*)" -- can be done server side via this mechanism.
- * </p>
- *
- * <p>
- * If the eval fails, an exception is thrown of the form:
- * </p>
- * <code>{ dbEvalException: { retval: functionReturnValue, ok: num [, errno: num] [, errmsg: str] } }</code>
- *
- * <p>Example: </p>
- * <code>print( "mycount: " + db.eval( function(){db.mycoll.find({},{_id:ObjId()}).length();} );</code>
- *
- * @param {Function} jsfunction Javascript function to run on server. Note this it not a closure, but rather just "code".
- * @return result of your function, or null if error
- *
- */
-DB.prototype.eval = function(jsfunction) {
- var cmd = { $eval : jsfunction };
- if ( arguments.length > 1 ) {
- cmd.args = argumentsToArray( arguments ).slice(1);
- }
-
- var res = this._dbCommand( cmd );
-
- if (!res.ok)
- throw tojson( res );
-
- return res.retval;
-}
-
-DB.prototype.dbEval = DB.prototype.eval;
-
-
-/**
- *
- * <p>
- * Similar to SQL group by. For example: </p>
- *
- * <code>select a,b,sum(c) csum from coll where active=1 group by a,b</code>
- *
- * <p>
- * corresponds to the following in 10gen:
- * </p>
- *
- * <code>
- db.group(
- {
- ns: "coll",
- key: { a:true, b:true },
- // keyf: ...,
- cond: { active:1 },
- reduce: function(obj,prev) { prev.csum += obj.c; } ,
- initial: { csum: 0 }
- });
- </code>
- *
- *
- * <p>
- * An array of grouped items is returned. The array must fit in RAM, thus this function is not
- * suitable when the return set is extremely large.
- * </p>
- * <p>
- * To order the grouped data, simply sort it client side upon return.
- * <p>
- Defaults
- cond may be null if you want to run against all rows in the collection
- keyf is a function which takes an object and returns the desired key. set either key or keyf (not both).
- * </p>
-*/
-DB.prototype.groupeval = function(parmsObj) {
-
- var groupFunction = function() {
- var parms = args[0];
- var c = db[parms.ns].find(parms.cond||{});
- var map = new Map();
- var pks = parms.key ? Object.keySet( parms.key ) : null;
- var pkl = pks ? pks.length : 0;
- var key = {};
-
- while( c.hasNext() ) {
- var obj = c.next();
- if ( pks ) {
- for( var i=0; i<pkl; i++ ){
- var k = pks[i];
- key[k] = obj[k];
- }
- }
- else {
- key = parms.$keyf(obj);
- }
-
- var aggObj = map.get(key);
- if( aggObj == null ) {
- var newObj = Object.extend({}, key); // clone
- aggObj = Object.extend(newObj, parms.initial)
- map.put( key , aggObj );
- }
- parms.$reduce(obj, aggObj);
- }
-
- return map.values();
- }
-
- return this.eval(groupFunction, this._groupFixParms( parmsObj ));
-}
-
-DB.prototype.groupcmd = function( parmsObj ){
- var ret = this.runCommand( { "group" : this._groupFixParms( parmsObj ) } );
- if ( ! ret.ok ){
- throw "group command failed: " + tojson( ret );
- }
- return ret.retval;
-}
-
-DB.prototype.group = DB.prototype.groupcmd;
-
-DB.prototype._groupFixParms = function( parmsObj ){
- var parms = Object.extend({}, parmsObj);
-
- if( parms.reduce ) {
- parms.$reduce = parms.reduce; // must have $ to pass to db
- delete parms.reduce;
- }
-
- if( parms.keyf ) {
- parms.$keyf = parms.keyf;
- delete parms.keyf;
- }
-
- return parms;
-}
-
-DB.prototype.resetError = function(){
- return this.runCommand( { reseterror : 1 } );
-}
-
-DB.prototype.forceError = function(){
- return this.runCommand( { forceerror : 1 } );
-}
-
-DB.prototype.getLastError = function( w , wtimeout ){
- var res = this.getLastErrorObj( w , wtimeout );
- if ( ! res.ok )
- throw "getlasterror failed: " + tojson( res );
- return res.err;
-}
-DB.prototype.getLastErrorObj = function( w , wtimeout ){
- var cmd = { getlasterror : 1 };
- if ( w ){
- cmd.w = w;
- if ( wtimeout )
- cmd.wtimeout = wtimeout;
- }
- var res = this.runCommand( cmd );
-
- if ( ! res.ok )
- throw "getlasterror failed: " + tojson( res );
- return res;
-}
-DB.prototype.getLastErrorCmd = DB.prototype.getLastErrorObj;
-
-
-/* Return the last error which has occurred, even if not the very last error.
-
- Returns:
- { err : <error message>, nPrev : <how_many_ops_back_occurred>, ok : 1 }
-
- result.err will be null if no error has occurred.
- */
-DB.prototype.getPrevError = function(){
- return this.runCommand( { getpreverror : 1 } );
-}
-
-DB.prototype.getCollectionNames = function(){
- var all = [];
-
- var nsLength = this._name.length + 1;
-
- var c = this.getCollection( "system.namespaces" ).find();
- while ( c.hasNext() ){
- var name = c.next().name;
-
- if ( name.indexOf( "$" ) >= 0 && name.indexOf( ".oplog.$" ) < 0 )
- continue;
-
- all.push( name.substring( nsLength ) );
- }
-
- return all.sort();
-}
-
-DB.prototype.tojson = function(){
- return this._name;
-}
-
-DB.prototype.toString = function(){
- return this._name;
-}
-
-DB.prototype.isMaster = function () { return this.runCommand("isMaster"); }
-
-DB.prototype.currentOp = function( arg ){
- var q = {}
- if ( arg ) {
- if ( typeof( arg ) == "object" )
- Object.extend( q , arg );
- else if ( arg )
- q["$all"] = true;
- }
- return db.$cmd.sys.inprog.findOne( q );
-}
-DB.prototype.currentOP = DB.prototype.currentOp;
-
-DB.prototype.killOp = function(op) {
- if( !op )
- throw "no opNum to kill specified";
- return db.$cmd.sys.killop.findOne({'op':op});
-}
-DB.prototype.killOP = DB.prototype.killOp;
-
-DB.tsToSeconds = function(x){
- if ( x.t && x.i )
- return x.t / 1000;
- return x / 4294967296; // low 32 bits are ordinal #s within a second
-}
-
-/**
- Get a replication log information summary.
- <p>
- This command is for the database/cloud administer and not applicable to most databases.
- It is only used with the local database. One might invoke from the JS shell:
- <pre>
- use local
- db.getReplicationInfo();
- </pre>
- It is assumed that this database is a replication master -- the information returned is
- about the operation log stored at local.oplog.$main on the replication master. (It also
- works on a machine in a replica pair: for replica pairs, both machines are "masters" from
- an internal database perspective.
- <p>
- * @return Object timeSpan: time span of the oplog from start to end if slave is more out
- * of date than that, it can't recover without a complete resync
-*/
-DB.prototype.getReplicationInfo = function() {
- var db = this.getSiblingDB("local");
-
- var result = { };
- var oplog;
- if (db.system.namespaces.findOne({name:"local.oplog.rs"}) != null) {
- oplog = 'oplog.rs';
- }
- else if (db.system.namespaces.findOne({name:"local.oplog.$main"}) != null) {
- oplog = 'oplog.$main';
- }
- else {
- result.errmsg = "neither master/slave nor replica set replication detected";
- return result;
- }
-
- var ol_entry = db.system.namespaces.findOne({name:"local."+oplog});
- if( ol_entry && ol_entry.options ) {
- result.logSizeMB = ol_entry.options.size / ( 1024 * 1024 );
- } else {
- result.errmsg = "local."+oplog+", or its options, not found in system.namespaces collection";
- return result;
- }
- ol = db.getCollection(oplog);
-
- result.usedMB = ol.stats().size / ( 1024 * 1024 );
- result.usedMB = Math.ceil( result.usedMB * 100 ) / 100;
-
- var firstc = ol.find().sort({$natural:1}).limit(1);
- var lastc = ol.find().sort({$natural:-1}).limit(1);
- if( !firstc.hasNext() || !lastc.hasNext() ) {
- result.errmsg = "objects not found in local.oplog.$main -- is this a new and empty db instance?";
- result.oplogMainRowCount = ol.count();
- return result;
- }
-
- var first = firstc.next();
- var last = lastc.next();
- {
- var tfirst = first.ts;
- var tlast = last.ts;
-
- if( tfirst && tlast ) {
- tfirst = DB.tsToSeconds( tfirst );
- tlast = DB.tsToSeconds( tlast );
- result.timeDiff = tlast - tfirst;
- result.timeDiffHours = Math.round(result.timeDiff / 36)/100;
- result.tFirst = (new Date(tfirst*1000)).toString();
- result.tLast = (new Date(tlast*1000)).toString();
- result.now = Date();
- }
- else {
- result.errmsg = "ts element not found in oplog objects";
- }
- }
-
- return result;
-};
-
-DB.prototype.printReplicationInfo = function() {
- var result = this.getReplicationInfo();
- if( result.errmsg ) {
- if (!this.isMaster().ismaster) {
- print("this is a slave, printing slave replication info.");
- this.printSlaveReplicationInfo();
- return;
- }
- print(tojson(result));
- return;
- }
- print("configured oplog size: " + result.logSizeMB + "MB");
- print("log length start to end: " + result.timeDiff + "secs (" + result.timeDiffHours + "hrs)");
- print("oplog first event time: " + result.tFirst);
- print("oplog last event time: " + result.tLast);
- print("now: " + result.now);
-}
-
-DB.prototype.printSlaveReplicationInfo = function() {
- function getReplLag(st) {
- var now = new Date();
- print("\t syncedTo: " + st.toString() );
- var ago = (now-st)/1000;
- var hrs = Math.round(ago/36)/100;
- print("\t\t = " + Math.round(ago) + " secs ago (" + hrs + "hrs)");
- };
-
- function g(x) {
- assert( x , "how could this be null (printSlaveReplicationInfo gx)" )
- print("source: " + x.host);
- if ( x.syncedTo ){
- var st = new Date( DB.tsToSeconds( x.syncedTo ) * 1000 );
- getReplLag(st);
- }
- else {
- print( "\t doing initial sync" );
- }
- };
-
- function r(x) {
- assert( x , "how could this be null (printSlaveReplicationInfo rx)" );
- if ( x.state == 1 ) {
- return;
- }
-
- print("source: " + x.name);
- if ( x.optime ) {
- getReplLag(x.optimeDate);
- }
- else {
- print( "\t no replication info, yet. State: " + x.stateStr );
- }
- };
-
- var L = this.getSiblingDB("local");
-
- if (L.system.replset.count() != 0) {
- var status = this.adminCommand({'replSetGetStatus' : 1});
- status.members.forEach(r);
- }
- else if( L.sources.count() != 0 ) {
- L.sources.find().forEach(g);
- }
- else {
- print("local.sources is empty; is this db a --slave?");
- return;
- }
-}
-
-DB.prototype.serverBuildInfo = function(){
- return this._adminCommand( "buildinfo" );
-}
-
-DB.prototype.serverStatus = function(){
- return this._adminCommand( "serverStatus" );
-}
-
-DB.prototype.serverCmdLineOpts = function(){
- return this._adminCommand( "getCmdLineOpts" );
-}
-
-DB.prototype.version = function(){
- return this.serverBuildInfo().version;
-}
-
-DB.prototype.serverBits = function(){
- return this.serverBuildInfo().bits;
-}
-
-DB.prototype.listCommands = function(){
- var x = this.runCommand( "listCommands" );
- for ( var name in x.commands ){
- var c = x.commands[name];
-
- var s = name + ": ";
-
- switch ( c.lockType ){
- case -1: s += "read-lock"; break;
- case 0: s += "no-lock"; break;
- case 1: s += "write-lock"; break;
- default: s += c.lockType;
- }
-
- if (c.adminOnly) s += " adminOnly ";
- if (c.adminOnly) s += " slaveOk ";
-
- s += "\n ";
- s += c.help.replace(/\n/g, '\n ');
- s += "\n";
-
- print( s );
- }
-}
-
-DB.prototype.printShardingStatus = function( verbose ){
- printShardingStatus( this.getSiblingDB( "config" ) , verbose );
-}
-
-DB.prototype.fsyncLock = function() {
- return db.adminCommand({fsync:1, lock:true});
-}
-
-DB.prototype.fsyncUnlock = function() {
- return db.getSiblingDB("admin").$cmd.sys.unlock.findOne()
-}
-
-DB.autocomplete = function(obj){
- var colls = obj.getCollectionNames();
- var ret=[];
- for (var i=0; i<colls.length; i++){
- if (colls[i].match(/^[a-zA-Z0-9_.\$]+$/))
- ret.push(colls[i]);
- }
- return ret;
-}
diff --git a/shell/dbshell.cpp b/shell/dbshell.cpp
deleted file mode 100644
index 34f2a346436..00000000000
--- a/shell/dbshell.cpp
+++ /dev/null
@@ -1,815 +0,0 @@
-// dbshell.cpp
-/*
- * Copyright 2010 10gen Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "pch.h"
-#include <stdio.h>
-#include <string.h>
-
-
-#define USE_LINENOISE
-#include "../third_party/linenoise/linenoise.h"
-
-#include "../scripting/engine.h"
-#include "../client/dbclient.h"
-#include "../util/unittest.h"
-#include "../db/cmdline.h"
-#include "utils.h"
-#include "../util/password.h"
-#include "../util/version.h"
-#include "../util/goodies.h"
-#include "../db/repl/rs_member.h"
-
-using namespace std;
-using namespace boost::filesystem;
-using namespace mongo;
-
-string historyFile;
-bool gotInterrupted = 0;
-bool inMultiLine = 0;
-static volatile bool atPrompt = false; // can eval before getting to prompt
-bool autoKillOp = false;
-
-
-#if defined(USE_LINENOISE) && !defined(__freebsd__) && !defined(__openbsd__) && !defined(_WIN32)
-// this is for ctrl-c handling
-#include <setjmp.h>
-jmp_buf jbuf;
-#endif
-
-#if defined(USE_LINENOISE)
-#define USE_TABCOMPLETION
-#endif
-
-
-namespace mongo {
-
- Scope * shellMainScope;
-
- extern bool dbexitCalled;
-}
-
-void generateCompletions( const string& prefix , vector<string>& all ) {
- if ( prefix.find( '"' ) != string::npos )
- return;
-
- BSONObj args = BSON("0" << prefix);
- shellMainScope->invokeSafe("function(x) {shellAutocomplete(x)}", &args, 0, 1000);
- BSONObjBuilder b;
- shellMainScope->append( b , "" , "__autocomplete__" );
- BSONObj res = b.obj();
- BSONObj arr = res.firstElement().Obj();
-
- BSONObjIterator i(arr);
- while ( i.more() ) {
- BSONElement e = i.next();
- all.push_back( e.String() );
- }
-
-}
-
-#ifdef USE_TABCOMPLETION
-void completionHook(const char* text , linenoiseCompletions* lc ) {
- vector<string> all;
- generateCompletions( text , all );
-
- for ( unsigned i=0; i<all.size(); i++ )
- linenoiseAddCompletion( lc , (char*)all[i].c_str() );
-
-}
-#endif
-
-void shellHistoryInit() {
-#ifdef USE_LINENOISE
- stringstream ss;
- char * h = getenv( "HOME" );
- if ( h )
- ss << h << "/";
- ss << ".dbshell";
- historyFile = ss.str();
-
- linenoiseHistoryLoad( (char*)historyFile.c_str() );
-#ifdef USE_TABCOMPLETION
- linenoiseSetCompletionCallback( completionHook );
-#endif
-
-#else
- //cout << "type \"exit\" to exit" << endl;
-#endif
-}
-void shellHistoryDone() {
-#ifdef USE_LINENOISE
- linenoiseHistorySave( (char*)historyFile.c_str() );
-#endif
-}
-void shellHistoryAdd( const char * line ) {
-#ifdef USE_LINENOISE
- if ( line[0] == '\0' )
- return;
-
- // dont record duplicate lines
- static string lastLine;
- if (lastLine == line)
- return;
- lastLine = line;
-
- if ( strstr( line, ".auth") == NULL &&
- strstr( line, ".addUser") == NULL )
- {
- linenoiseHistoryAdd( line );
- }
-#endif
-}
-
-void intr( int sig ) {
-#ifdef CTRLC_HANDLE
- longjmp( jbuf , 1 );
-#endif
-}
-
-void killOps() {
- if ( mongo::shellUtils::_nokillop || mongo::shellUtils::_allMyUris.size() == 0 )
- return;
-
- if ( atPrompt )
- return;
-
- sleepmillis(10); // give current op a chance to finish
-
- for( map< string, set<string> >::const_iterator i = shellUtils::_allMyUris.begin(); i != shellUtils::_allMyUris.end(); ++i ) {
- string errmsg;
- ConnectionString cs = ConnectionString::parse(i->first, errmsg);
- if (!cs.isValid()) continue;
- boost::scoped_ptr<DBClientWithCommands> conn (cs.connect(errmsg));
- if (!conn) continue;
-
- const set<string>& uris = i->second;
-
- BSONObj inprog = conn->findOne("admin.$cmd.sys.inprog", Query())["inprog"].embeddedObject().getOwned();
- BSONForEach(op, inprog) {
- if ( uris.count(op["client"].String()) ) {
- ONCE if ( !autoKillOp ) {
- cout << endl << "do you want to kill the current op(s) on the server? (y/n): ";
- cout.flush();
-
- char yn;
- cin >> yn;
-
- if (yn != 'y' && yn != 'Y')
- return;
- }
-
- conn->findOne("admin.$cmd.sys.killop", QUERY("op"<< op["opid"]));
- }
- }
- }
-}
-
-void quitNicely( int sig ) {
- mongo::dbexitCalled = true;
- if ( sig == SIGINT && inMultiLine ) {
- gotInterrupted = 1;
- return;
- }
-
-#if !defined(_WIN32)
- if ( sig == SIGPIPE )
- mongo::rawOut( "mongo got signal SIGPIPE\n" );
-#endif
-
- killOps();
- shellHistoryDone();
- exit(0);
-}
-
-char * shellReadline( const char * prompt , int handlesigint = 0 ) {
-
- atPrompt = true;
-#ifdef USE_LINENOISE
-
-
-#ifdef CTRLC_HANDLE
- if ( ! handlesigint ) {
- char* ret = linenoise( prompt );
- atPrompt = false;
- return ret;
- }
- if ( setjmp( jbuf ) ) {
- gotInterrupted = 1;
- sigrelse(SIGINT);
- signal( SIGINT , quitNicely );
- return 0;
- }
- signal( SIGINT , intr );
-#endif
-
- char * ret = linenoise( prompt );
- signal( SIGINT , quitNicely );
- atPrompt = false;
- return ret;
-#else
- printf("%s", prompt); cout.flush();
- char * buf = new char[1024];
- char * l = fgets( buf , 1024 , stdin );
- int len = strlen( buf );
- if ( len )
- buf[len-1] = 0;
- atPrompt = false;
- return l;
-#endif
-}
-
-#ifdef _WIN32
-char * strsignal(int sig){
- switch (sig){
- case SIGINT: return "SIGINT";
- case SIGTERM: return "SIGTERM";
- case SIGABRT: return "SIGABRT";
- case SIGSEGV: return "SIGSEGV";
- case SIGFPE: return "SIGFPE";
- default: return "unknown";
- }
-}
-#endif
-
-void quitAbruptly( int sig ) {
- ostringstream ossSig;
- ossSig << "mongo got signal " << sig << " (" << strsignal( sig ) << "), stack trace: " << endl;
- mongo::rawOut( ossSig.str() );
-
- ostringstream ossBt;
- mongo::printStackTrace( ossBt );
- mongo::rawOut( ossBt.str() );
-
- mongo::shellUtils::KillMongoProgramInstances();
- exit(14);
-}
-
-// this will be called in certain c++ error cases, for example if there are two active
-// exceptions
-void myterminate() {
- mongo::rawOut( "terminate() called in shell, printing stack:" );
- mongo::printStackTrace();
- exit(14);
-}
-
-void setupSignals() {
- signal( SIGINT , quitNicely );
- signal( SIGTERM , quitNicely );
- signal( SIGABRT , quitAbruptly );
- signal( SIGSEGV , quitAbruptly );
- signal( SIGFPE , quitAbruptly );
-
-#if !defined(_WIN32) // surprisingly these are the only ones that don't work on windows
- signal( SIGPIPE , quitNicely ); // Maybe just log and continue?
- signal( SIGBUS , quitAbruptly );
-#endif
-
- set_terminate( myterminate );
-}
-
-string fixHost( string url , string host , string port ) {
- //cout << "fixHost url: " << url << " host: " << host << " port: " << port << endl;
-
- if ( host.size() == 0 && port.size() == 0 ) {
- if ( url.find( "/" ) == string::npos ) {
- // check for ips
- if ( url.find( "." ) != string::npos )
- return url + "/test";
-
- if ( url.rfind( ":" ) != string::npos &&
- isdigit( url[url.rfind(":")+1] ) )
- return url + "/test";
- }
- return url;
- }
-
- if ( url.find( "/" ) != string::npos ) {
- cerr << "url can't have host or port if you specify them individually" << endl;
- exit(-1);
- }
-
- if ( host.size() == 0 )
- host = "127.0.0.1";
-
- string newurl = host;
- if ( port.size() > 0 )
- newurl += ":" + port;
- else if (host.find(':') == string::npos) {
- // need to add port with IPv6 addresses
- newurl += ":27017";
- }
-
- newurl += "/" + url;
-
- return newurl;
-}
-
-static string OpSymbols = "~!%^&*-+=|:,<>/?.";
-
-bool isOpSymbol( char c ) {
- for ( size_t i = 0; i < OpSymbols.size(); i++ )
- if ( OpSymbols[i] == c ) return true;
- return false;
-}
-
-bool isBalanced( string code ) {
- int brackets = 0;
- int parens = 0;
- bool danglingOp = false;
-
- for ( size_t i=0; i<code.size(); i++ ) {
- switch( code[i] ) {
- case '/':
- if ( i+1 < code.size() && code[i+1] == '/' ) {
- while ( i<code.size() && code[i] != '\n' )
- i++;
- }
- continue;
- case '{': brackets++; break;
- case '}': if ( brackets <= 0 ) return true; brackets--; break;
- case '(': parens++; break;
- case ')': if ( parens <= 0 ) return true; parens--; break;
- case '"':
- i++;
- while ( i < code.size() && code[i] != '"' ) i++;
- break;
- case '\'':
- i++;
- while ( i < code.size() && code[i] != '\'' ) i++;
- break;
- case '\\':
- if ( i+1 < code.size() && code[i+1] == '/') i++;
- break;
- case '+':
- case '-':
- if ( i+1 < code.size() && code[i+1] == code[i]) {
- i++;
- continue; // postfix op (++/--) can't be a dangling op
- }
- break;
- }
-
- if ( isOpSymbol( code[i] )) danglingOp = true;
- else if (! std::isspace( code[i] )) danglingOp = false;
- }
-
- return brackets == 0 && parens == 0 && !danglingOp;
-}
-
-using mongo::asserted;
-
-struct BalancedTest : public mongo::UnitTest {
-public:
- void run() {
- assert( isBalanced( "x = 5" ) );
- assert( isBalanced( "function(){}" ) );
- assert( isBalanced( "function(){\n}" ) );
- assert( ! isBalanced( "function(){" ) );
- assert( isBalanced( "x = \"{\";" ) );
- assert( isBalanced( "// {" ) );
- assert( ! isBalanced( "// \n {" ) );
- assert( ! isBalanced( "\"//\" {" ) );
- assert( isBalanced( "{x:/x\\//}" ) );
- assert( ! isBalanced( "{ \\/// }" ) );
- assert( isBalanced( "x = 5 + y ") );
- assert( ! isBalanced( "x = ") );
- assert( ! isBalanced( "x = // hello") );
- assert( ! isBalanced( "x = 5 +") );
- assert( isBalanced( " x ++") );
- assert( isBalanced( "-- x") );
- assert( !isBalanced( "a.") );
- assert( !isBalanced( "a. ") );
- assert( isBalanced( "a.b") );
- }
-} balnaced_test;
-
-string finishCode( string code ) {
- while ( ! isBalanced( code ) ) {
- inMultiLine = 1;
- code += "\n";
- // cancel multiline if two blank lines are entered
- if ( code.find("\n\n\n") != string::npos )
- return ";";
- char * line = shellReadline("... " , 1 );
- if ( gotInterrupted )
- return "";
- if ( ! line )
- return "";
-
- while (startsWith(line, "... "))
- line += 4;
-
- code += line;
- }
- return code;
-}
-
-#include <boost/program_options.hpp>
-namespace po = boost::program_options;
-
-void show_help_text(const char* name, po::options_description options) {
- cout << "MongoDB shell version: " << mongo::versionString << endl;
- cout << "usage: " << name << " [options] [db address] [file names (ending in .js)]" << endl
- << "db address can be:" << endl
- << " foo foo database on local machine" << endl
- << " 192.169.0.5/foo foo database on 192.168.0.5 machine" << endl
- << " 192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999" << endl
- << options << endl
- << "file names: a list of files to run. files have to end in .js and will exit after "
- << "unless --shell is specified" << endl;
-};
-
-bool fileExists( string file ) {
- try {
- path p(file);
- return boost::filesystem::exists( file );
- }
- catch (...) {
- return false;
- }
-}
-
-namespace mongo {
- extern bool isShell;
- extern DBClientWithCommands *latestConn;
-}
-
-string sayReplSetMemberState() {
- try {
- if( latestConn ) {
- BSONObj info;
- if( latestConn->runCommand("admin", BSON( "replSetGetStatus" << 1 << "forShell" << 1 ) , info ) ) {
- stringstream ss;
- ss << info["set"].String() << ':';
- int s = info["myState"].Int();
- MemberState ms(s);
- return ms.toString();
- }
- else if( str::equals(info.getStringField("info"), "mongos") ) {
- return "mongos";
- }
- }
- }
- catch( std::exception& e ) {
- log(1) << "error in sayReplSetMemberState:" << e.what() << endl;
- }
- return "";
-}
-
-int _main(int argc, char* argv[]) {
- mongo::isShell = true;
- setupSignals();
-
- mongo::shellUtils::RecordMyLocation( argv[ 0 ] );
-
- string url = "test";
- string dbhost;
- string port;
- vector<string> files;
-
- string username;
- string password;
-
- bool runShell = false;
- bool nodb = false;
- bool norc = false;
-
- string script;
-
- po::options_description shell_options("options");
- po::options_description hidden_options("Hidden options");
- po::options_description cmdline_options("Command line options");
- po::positional_options_description positional_options;
-
- shell_options.add_options()
- ("shell", "run the shell after executing files")
- ("nodb", "don't connect to mongod on startup - no 'db address' arg expected")
- ("norc", "will not run the \".mongorc.js\" file on start up")
- ("quiet", "be less chatty" )
- ("port", po::value<string>(&port), "port to connect to")
- ("host", po::value<string>(&dbhost), "server to connect to")
- ("eval", po::value<string>(&script), "evaluate javascript")
- ("username,u", po::value<string>(&username), "username for authentication")
- ("password,p", new mongo::PasswordValue(&password),
- "password for authentication")
- ("help,h", "show this usage information")
- ("version", "show version information")
- ("verbose", "increase verbosity")
- ("ipv6", "enable IPv6 support (disabled by default)")
-#ifdef MONGO_SSL
- ("ssl", "use all for connections")
-#endif
- ;
-
- hidden_options.add_options()
- ("dbaddress", po::value<string>(), "dbaddress")
- ("files", po::value< vector<string> >(), "files")
- ("nokillop", "nokillop") // for testing, kill op will also be disabled automatically if the tests starts a mongo program
- ("autokillop", "autokillop") // for testing, will kill op without prompting
- ;
-
- positional_options.add("dbaddress", 1);
- positional_options.add("files", -1);
-
- cmdline_options.add(shell_options).add(hidden_options);
-
- po::variables_map params;
-
- /* using the same style as db.cpp uses because eventually we're going
- * to merge some of this stuff. */
- int command_line_style = (((po::command_line_style::unix_style ^
- po::command_line_style::allow_guessing) |
- po::command_line_style::allow_long_disguise) ^
- po::command_line_style::allow_sticky);
-
- try {
- po::store(po::command_line_parser(argc, argv).options(cmdline_options).
- positional(positional_options).
- style(command_line_style).run(), params);
- po::notify(params);
- }
- catch (po::error &e) {
- cout << "ERROR: " << e.what() << endl << endl;
- show_help_text(argv[0], shell_options);
- return mongo::EXIT_BADOPTIONS;
- }
-
- // hide password from ps output
- for (int i=0; i < (argc-1); ++i) {
- if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--password")) {
- char* arg = argv[i+1];
- while (*arg) {
- *arg++ = 'x';
- }
- }
- }
-
- if (params.count("shell")) {
- runShell = true;
- }
- if (params.count("nodb")) {
- nodb = true;
- }
- if (params.count("norc")) {
- norc = true;
- }
- if (params.count("help")) {
- show_help_text(argv[0], shell_options);
- return mongo::EXIT_CLEAN;
- }
- if (params.count("files")) {
- files = params["files"].as< vector<string> >();
- }
- if (params.count("version")) {
- cout << "MongoDB shell version: " << mongo::versionString << endl;
- return mongo::EXIT_CLEAN;
- }
- if (params.count("quiet")) {
- mongo::cmdLine.quiet = true;
- }
-#ifdef MONGO_SSL
- if (params.count("ssl")) {
- mongo::cmdLine.sslOnNormalPorts = true;
- }
-#endif
- if (params.count("nokillop")) {
- mongo::shellUtils::_nokillop = true;
- }
- if (params.count("autokillop")) {
- autoKillOp = true;
- }
-
-
-
- /* This is a bit confusing, here are the rules:
- *
- * if nodb is set then all positional parameters are files
- * otherwise the first positional parameter might be a dbaddress, but
- * only if one of these conditions is met:
- * - it contains no '.' after the last appearance of '\' or '/'
- * - it doesn't end in '.js' and it doesn't specify a path to an existing file */
- if (params.count("dbaddress")) {
- string dbaddress = params["dbaddress"].as<string>();
- if (nodb) {
- files.insert(files.begin(), dbaddress);
- }
- else {
- string basename = dbaddress.substr(dbaddress.find_last_of("/\\") + 1);
- if (basename.find_first_of('.') == string::npos ||
- (basename.find(".js", basename.size() - 3) == string::npos && !fileExists(dbaddress))) {
- url = dbaddress;
- }
- else {
- files.insert(files.begin(), dbaddress);
- }
- }
- }
- if (params.count("ipv6")) {
- mongo::enableIPv6();
- }
- if (params.count("verbose")) {
- logLevel = 1;
- }
-
- if ( ! mongo::cmdLine.quiet )
- cout << "MongoDB shell version: " << mongo::versionString << endl;
-
- mongo::UnitTest::runTests();
-
- if ( !nodb ) { // connect to db
- //if ( ! mongo::cmdLine.quiet ) cout << "url: " << url << endl;
-
- stringstream ss;
- if ( mongo::cmdLine.quiet )
- ss << "__quiet = true;";
- ss << "db = connect( \"" << fixHost( url , dbhost , port ) << "\")";
-
- mongo::shellUtils::_dbConnect = ss.str();
-
- if ( params.count( "password" )
- && ( password.empty() ) ) {
- password = mongo::askPassword();
- }
-
- if ( username.size() && password.size() ) {
- stringstream ss;
- ss << "if ( ! db.auth( \"" << username << "\" , \"" << password << "\" ) ){ throw 'login failed'; }";
- mongo::shellUtils::_dbAuth = ss.str();
- }
-
- }
-
- mongo::ScriptEngine::setConnectCallback( mongo::shellUtils::onConnect );
- mongo::ScriptEngine::setup();
- mongo::globalScriptEngine->setScopeInitCallback( mongo::shellUtils::initScope );
- auto_ptr< mongo::Scope > scope( mongo::globalScriptEngine->newScope() );
- shellMainScope = scope.get();
-
- if( runShell )
- cout << "type \"help\" for help" << endl;
-
- if ( !script.empty() ) {
- mongo::shellUtils::MongoProgramScope s;
- if ( ! scope->exec( script , "(shell eval)" , true , true , false ) )
- return -4;
- }
-
- for (size_t i = 0; i < files.size(); i++) {
- mongo::shellUtils::MongoProgramScope s;
-
- if ( files.size() > 1 )
- cout << "loading file: " << files[i] << endl;
-
- if ( ! scope->execFile( files[i] , false , true , false ) ) {
- cout << "failed to load: " << files[i] << endl;
- return -3;
- }
- }
-
- if ( files.size() == 0 && script.empty() ) {
- runShell = true;
- }
-
- if ( runShell ) {
-
- mongo::shellUtils::MongoProgramScope s;
-
- if (!norc) {
- string rcLocation;
-#ifndef _WIN32
- if ( getenv("HOME") != NULL )
- rcLocation = str::stream() << getenv("HOME") << "/.mongorc.js" ;
-#else
- if ( getenv("HOMEDRIVE") != NULL && getenv("HOMEPATH") != NULL )
- rcLocation = str::stream() << getenv("HOMEDRIVE") << getenv("HOMEPATH") << "\\.mongorc.js";
-#endif
- if ( !rcLocation.empty() && fileExists(rcLocation) ) {
- if ( ! scope->execFile( rcLocation , false , true , false , 0 ) ) {
- cout << "The \".mongorc.js\" file located in your home folder could not be executed" << endl;
- return -5;
- }
- }
- }
-
- shellHistoryInit();
-
- string prompt;
- int promptType;
-
- //v8::Handle<v8::Object> shellHelper = baseContext_->Global()->Get( v8::String::New( "shellHelper" ) )->ToObject();
-
- while ( 1 ) {
- inMultiLine = 0;
- gotInterrupted = 0;
-// shellMainScope->localConnect;
- //DBClientWithCommands *c = getConnection( JSContext *cx, JSObject *obj );
-
- promptType = scope->type("prompt");
- if (promptType == String){
- prompt = scope->getString("prompt");
- } else if (promptType == Code) {
- scope->exec("__prompt__ = prompt();", "", false, false, false, 0);
- prompt = scope->getString("__prompt__");
- } else {
- prompt = sayReplSetMemberState()+"> ";
- }
-
- char * line = shellReadline( prompt.c_str() );
-
- if ( line ) {
- while (startsWith(line, "> "))
- line += 2;
-
- while ( line[0] == ' ' )
- line++;
- }
-
- if ( ! line || ( strlen(line) == 4 && strstr( line , "exit" ) ) ) {
- cout << "bye" << endl;
- break;
- }
-
- string code = line;
- if ( code == "exit" || code == "exit;" ) {
- break;
- }
- if ( code.size() == 0 )
- continue;
-
- code = finishCode( code );
- if ( gotInterrupted ) {
- cout << endl;
- continue;
- }
-
- if ( code.size() == 0 )
- break;
-
- bool wascmd = false;
- {
- string cmd = line;
- if ( cmd.find( " " ) > 0 )
- cmd = cmd.substr( 0 , cmd.find( " " ) );
-
- if ( cmd.find( "\"" ) == string::npos ) {
- try {
- scope->exec( (string)"__iscmd__ = shellHelper[\"" + cmd + "\"];" , "(shellhelp1)" , false , true , true );
- if ( scope->getBoolean( "__iscmd__" ) ) {
- scope->exec( (string)"shellHelper( \"" + cmd + "\" , \"" + code.substr( cmd.size() ) + "\");" , "(shellhelp2)" , false , true , false );
- wascmd = true;
- }
- }
- catch ( std::exception& e ) {
- cout << "error2:" << e.what() << endl;
- wascmd = true;
- }
- }
-
- }
-
- if ( ! wascmd ) {
- try {
- if ( scope->exec( code.c_str() , "(shell)" , false , true , false ) )
- scope->exec( "shellPrintHelper( __lastres__ );" , "(shell2)" , true , true , false );
- }
- catch ( std::exception& e ) {
- cout << "error:" << e.what() << endl;
- }
- }
-
- shellHistoryAdd( line );
- }
-
- shellHistoryDone();
- }
-
- mongo::dbexitCalled = true;
- return 0;
-}
-
-int main(int argc, char* argv[]) {
- static mongo::StaticObserver staticObserver;
- try {
- return _main( argc , argv );
- }
- catch ( mongo::DBException& e ) {
- cerr << "exception: " << e.what() << endl;
- return -1;
- }
-}
-
-
diff --git a/shell/mongo.js b/shell/mongo.js
deleted file mode 100644
index 25357691c51..00000000000
--- a/shell/mongo.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// mongo.js
-
-// NOTE 'Mongo' may be defined here or in MongoJS.cpp. Add code to init, not to this constructor.
-if ( typeof Mongo == "undefined" ){
- Mongo = function( host ){
- this.init( host );
- }
-}
-
-if ( ! Mongo.prototype ){
- throw "Mongo.prototype not defined";
-}
-
-if ( ! Mongo.prototype.find )
- Mongo.prototype.find = function( ns , query , fields , limit , skip , batchSize , options ){ throw "find not implemented"; }
-if ( ! Mongo.prototype.insert )
- Mongo.prototype.insert = function( ns , obj ){ throw "insert not implemented"; }
-if ( ! Mongo.prototype.remove )
- Mongo.prototype.remove = function( ns , pattern ){ throw "remove not implemented;" }
-if ( ! Mongo.prototype.update )
- Mongo.prototype.update = function( ns , query , obj , upsert ){ throw "update not implemented;" }
-
-if ( typeof mongoInject == "function" ){
- mongoInject( Mongo.prototype );
-}
-
-Mongo.prototype.setSlaveOk = function( value ) {
- if( value == undefined ) value = true
- this.slaveOk = value
-}
-
-Mongo.prototype.getDB = function( name ){
- return new DB( this , name );
-}
-
-Mongo.prototype.getDBs = function(){
- var res = this.getDB( "admin" ).runCommand( { "listDatabases" : 1 } );
- if ( ! res.ok )
- throw "listDatabases failed:" + tojson( res );
- return res;
-}
-
-Mongo.prototype.adminCommand = function( cmd ){
- return this.getDB( "admin" ).runCommand( cmd );
-}
-
-Mongo.prototype.setLogLevel = function( logLevel ){
- return this.adminCommand({ setParameter : 1, logLevel : logLevel })
-}
-
-Mongo.prototype.getDBNames = function(){
- return this.getDBs().databases.map(
- function(z){
- return z.name;
- }
- );
-}
-
-Mongo.prototype.getCollection = function(ns){
- var idx = ns.indexOf( "." );
- if ( idx < 0 )
- throw "need . in ns";
- var db = ns.substring( 0 , idx );
- var c = ns.substring( idx + 1 );
- return this.getDB( db ).getCollection( c );
-}
-
-Mongo.prototype.toString = function(){
- return "connection to " + this.host;
-}
-Mongo.prototype.tojson = Mongo.prototype.toString;
-
-connect = function( url , user , pass ){
- chatty( "connecting to: " + url )
-
- if ( user && ! pass )
- throw "you specified a user and not a password. either you need a password, or you're using the old connect api";
-
- var idx = url.lastIndexOf( "/" );
-
- var db;
-
- if ( idx < 0 )
- db = new Mongo().getDB( url );
- else
- db = new Mongo( url.substring( 0 , idx ) ).getDB( url.substring( idx + 1 ) );
-
- if ( user && pass ){
- if ( ! db.auth( user , pass ) ){
- throw "couldn't login";
- }
- }
-
- return db;
-}
diff --git a/shell/mongo_vstudio.cpp b/shell/mongo_vstudio.cpp
deleted file mode 100644
index d9e4d19a5c2..00000000000
--- a/shell/mongo_vstudio.cpp
+++ /dev/null
@@ -1,4020 +0,0 @@
-#include "bson/stringdata.h"
-namespace mongo {
-struct JSFile{ const char* name; const StringData& source; };
-namespace JSFiles{
-const StringData _jscode_raw_utils =
-"__quiet = false;\n"
-"__magicNoPrint = { __magicNoPrint : 1111 }\n"
-"\n"
-"chatty = function(s){\n"
-"if ( ! __quiet )\n"
-"print( s );\n"
-"}\n"
-"\n"
-"friendlyEqual = function( a , b ){\n"
-"if ( a == b )\n"
-"return true;\n"
-"\n"
-"a = tojson(a,false,true);\n"
-"b = tojson(b,false,true);\n"
-"\n"
-"if ( a == b )\n"
-"return true;\n"
-"\n"
-"var clean = function( s ){\n"
-"s = s.replace( /NumberInt\\((\\-?\\d+)\\)/g , \"$1\" );\n"
-"return s;\n"
-"}\n"
-"\n"
-"a = clean(a);\n"
-"b = clean(b);\n"
-"\n"
-"if ( a == b )\n"
-"return true;\n"
-"\n"
-"return false;\n"
-"}\n"
-"\n"
-"printStackTrace = function(){\n"
-"try{\n"
-"throw new Error(\"Printing Stack Trace\");\n"
-"} catch (e) {\n"
-"print(e.stack);\n"
-"}\n"
-"}\n"
-"\n"
-"doassert = function (msg) {\n"
-"if (msg.indexOf(\"assert\") == 0)\n"
-"print(msg);\n"
-"else\n"
-"print(\"assert: \" + msg);\n"
-"printStackTrace();\n"
-"throw msg;\n"
-"}\n"
-"\n"
-"assert = function( b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"if ( b )\n"
-"return;\n"
-"doassert( msg == undefined ? \"assert failed\" : \"assert failed : \" + msg );\n"
-"}\n"
-"\n"
-"assert.automsg = function( b ) {\n"
-"assert( eval( b ), b );\n"
-"}\n"
-"\n"
-"assert._debug = false;\n"
-"\n"
-"assert.eq = function( a , b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( a == b )\n"
-"return;\n"
-"\n"
-"if ( ( a != null && b != null ) && friendlyEqual( a , b ) )\n"
-"return;\n"
-"\n"
-"doassert( \"[\" + tojson( a ) + \"] != [\" + tojson( b ) + \"] are not equal : \" + msg );\n"
-"}\n"
-"\n"
-"assert.eq.automsg = function( a, b ) {\n"
-"assert.eq( eval( a ), eval( b ), \"[\" + a + \"] != [\" + b + \"]\" );\n"
-"}\n"
-"\n"
-"assert.neq = function( a , b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"if ( a != b )\n"
-"return;\n"
-"\n"
-"doassert( \"[\" + a + \"] != [\" + b + \"] are equal : \" + msg );\n"
-"}\n"
-"\n"
-"assert.contains = function( o, arr, msg ){\n"
-"var wasIn = false\n"
-"\n"
-"if( ! arr.length ){\n"
-"for( i in arr ){\n"
-"wasIn = arr[i] == o || ( ( arr[i] != null && o != null ) && friendlyEqual( arr[i] , o ) )\n"
-"return;\n"
-"if( wasIn ) break\n"
-"}\n"
-"}\n"
-"else {\n"
-"for( var i = 0; i < arr.length; i++ ){\n"
-"wasIn = arr[i] == o || ( ( arr[i] != null && o != null ) && friendlyEqual( arr[i] , o ) )\n"
-"if( wasIn ) break\n"
-"}\n"
-"}\n"
-"\n"
-"if( ! wasIn ) doassert( tojson( o ) + \" was not in \" + tojson( arr ) + \" : \" + msg )\n"
-"}\n"
-"\n"
-"assert.repeat = function( f, msg, timeout, interval ) {\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"var start = new Date();\n"
-"timeout = timeout || 30000;\n"
-"interval = interval || 200;\n"
-"var last;\n"
-"while( 1 ) {\n"
-"\n"
-"if ( typeof( f ) == \"string\" ){\n"
-"if ( eval( f ) )\n"
-"return;\n"
-"}\n"
-"else {\n"
-"if ( f() )\n"
-"return;\n"
-"}\n"
-"\n"
-"if ( ( new Date() ).getTime() - start.getTime() > timeout )\n"
-"break;\n"
-"sleep( interval );\n"
-"}\n"
-"}\n"
-"\n"
-"assert.soon = function( f, msg, timeout /*ms*/, interval ) {\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"var start = new Date();\n"
-"timeout = timeout || 30000;\n"
-"interval = interval || 200;\n"
-"var last;\n"
-"while( 1 ) {\n"
-"\n"
-"if ( typeof( f ) == \"string\" ){\n"
-"if ( eval( f ) )\n"
-"return;\n"
-"}\n"
-"else {\n"
-"if ( f() )\n"
-"return;\n"
-"}\n"
-"\n"
-"if ( ( new Date() ).getTime() - start.getTime() > timeout )\n"
-"doassert( \"assert.soon failed: \" + f + \", msg:\" + msg );\n"
-"sleep( interval );\n"
-"}\n"
-"}\n"
-"\n"
-"assert.throws = function( func , params , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( params && typeof( params ) == \"string\" )\n"
-"throw \"2nd argument to assert.throws has to be an array\"\n"
-"\n"
-"try {\n"
-"func.apply( null , params );\n"
-"}\n"
-"catch ( e ){\n"
-"return e;\n"
-"}\n"
-"\n"
-"doassert( \"did not throw exception: \" + msg );\n"
-"}\n"
-"\n"
-"assert.throws.automsg = function( func, params ) {\n"
-"assert.throws( func, params, func.toString() );\n"
-"}\n"
-"\n"
-"assert.commandWorked = function( res , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( res.ok == 1 )\n"
-"return;\n"
-"\n"
-"doassert( \"command failed: \" + tojson( res ) + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.commandFailed = function( res , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( res.ok == 0 )\n"
-"return;\n"
-"\n"
-"doassert( \"command worked when it should have failed: \" + tojson( res ) + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.isnull = function( what , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( what == null )\n"
-"return;\n"
-"\n"
-"doassert( \"supposed to null (\" + ( msg || \"\" ) + \") was: \" + tojson( what ) );\n"
-"}\n"
-"\n"
-"assert.lt = function( a , b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( a < b )\n"
-"return;\n"
-"doassert( a + \" is not less than \" + b + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.gt = function( a , b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( a > b )\n"
-"return;\n"
-"doassert( a + \" is not greater than \" + b + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.lte = function( a , b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( a <= b )\n"
-"return;\n"
-"doassert( a + \" is not less than or eq \" + b + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.gte = function( a , b , msg ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if ( a >= b )\n"
-"return;\n"
-"doassert( a + \" is not greater than or eq \" + b + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.between = function( a, b, c, msg, inclusive ){\n"
-"if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n"
-"\n"
-"if( ( inclusive == undefined || inclusive == true ) &&\n"
-"a <= b && b <= c ) return;\n"
-"else if( a < b && b < c ) return;\n"
-"\n"
-"doassert( b + \" is not between \" + a + \" and \" + c + \" : \" + msg );\n"
-"}\n"
-"\n"
-"assert.betweenIn = function( a, b, c, msg ){ assert.between( a, b, c, msg, true ) }\n"
-"assert.betweenEx = function( a, b, c, msg ){ assert.between( a, b, c, msg, false ) }\n"
-"\n"
-"assert.close = function( a , b , msg , places ){\n"
-"if (places === undefined) {\n"
-"places = 4;\n"
-"}\n"
-"if (Math.round((a - b) * Math.pow(10, places)) === 0) {\n"
-"return;\n"
-"}\n"
-"doassert( a + \" is not equal to \" + b + \" within \" + places +\n"
-"\" places, diff: \" + (a-b) + \" : \" + msg );\n"
-"};\n"
-"\n"
-"Object.extend = function( dst , src , deep ){\n"
-"for ( var k in src ){\n"
-"var v = src[k];\n"
-"if ( deep && typeof(v) == \"object\" ){\n"
-"if ( \"floatApprox\" in v ) { // convert NumberLong properly\n"
-"eval( \"v = \" + tojson( v ) );\n"
-"} else {\n"
-"v = Object.extend( typeof ( v.length ) == \"number\" ? [] : {} , v , true );\n"
-"}\n"
-"}\n"
-"dst[k] = v;\n"
-"}\n"
-"return dst;\n"
-"}\n"
-"\n"
-"Object.merge = function( dst, src, deep ){\n"
-"var clone = Object.extend( {}, dst, deep )\n"
-"return Object.extend( clone, src, deep )\n"
-"}\n"
-"\n"
-"argumentsToArray = function( a ){\n"
-"var arr = [];\n"
-"for ( var i=0; i<a.length; i++ )\n"
-"arr[i] = a[i];\n"
-"return arr;\n"
-"}\n"
-"\n"
-"isString = function( x ){\n"
-"return typeof( x ) == \"string\";\n"
-"}\n"
-"\n"
-"isNumber = function(x){\n"
-"return typeof( x ) == \"number\";\n"
-"}\n"
-"\n"
-"isObject = function( x ){\n"
-"return typeof( x ) == \"object\";\n"
-"}\n"
-"\n"
-"String.prototype.trim = function() {\n"
-"return this.replace(/^\\s+|\\s+$/g,\"\");\n"
-"}\n"
-"String.prototype.ltrim = function() {\n"
-"return this.replace(/^\\s+/,\"\");\n"
-"}\n"
-"String.prototype.rtrim = function() {\n"
-"return this.replace(/\\s+$/,\"\");\n"
-"}\n"
-"\n"
-"Number.prototype.zeroPad = function(width) {\n"
-"var str = this + '';\n"
-"while (str.length < width)\n"
-"str = '0' + str;\n"
-"return str;\n"
-"}\n"
-"\n"
-"Date.timeFunc = function( theFunc , numTimes ){\n"
-"\n"
-"var start = new Date();\n"
-"\n"
-"numTimes = numTimes || 1;\n"
-"for ( var i=0; i<numTimes; i++ ){\n"
-"theFunc.apply( null , argumentsToArray( arguments ).slice( 2 ) );\n"
-"}\n"
-"\n"
-"return (new Date()).getTime() - start.getTime();\n"
-"}\n"
-"\n"
-"Date.prototype.tojson = function(){\n"
-"\n"
-"var UTC = Date.printAsUTC ? 'UTC' : '';\n"
-"\n"
-"var year = this['get'+UTC+'FullYear']().zeroPad(4);\n"
-"var month = (this['get'+UTC+'Month']() + 1).zeroPad(2);\n"
-"var date = this['get'+UTC+'Date']().zeroPad(2);\n"
-"var hour = this['get'+UTC+'Hours']().zeroPad(2);\n"
-"var minute = this['get'+UTC+'Minutes']().zeroPad(2);\n"
-"var sec = this['get'+UTC+'Seconds']().zeroPad(2)\n"
-"\n"
-"if (this['get'+UTC+'Milliseconds']())\n"
-"sec += '.' + this['get'+UTC+'Milliseconds']().zeroPad(3)\n"
-"\n"
-"var ofs = 'Z';\n"
-"if (!Date.printAsUTC){\n"
-"var ofsmin = this.getTimezoneOffset();\n"
-"if (ofsmin != 0){\n"
-"ofs = ofsmin > 0 ? '-' : '+'; // This is correct\n"
-"ofs += (ofsmin/60).zeroPad(2)\n"
-"ofs += (ofsmin%60).zeroPad(2)\n"
-"}\n"
-"}\n"
-"\n"
-"return 'ISODate(\"'+year+'-'+month+'-'+date+'T'+hour+':'+minute+':'+sec+ofs+'\")';\n"
-"}\n"
-"\n"
-"Date.printAsUTC = true;\n"
-"\n"
-"\n"
-"ISODate = function(isoDateStr){\n"
-"if (!isoDateStr)\n"
-"return new Date();\n"
-"\n"
-"var isoDateRegex = /(\\d{4})-?(\\d{2})-?(\\d{2})([T ](\\d{2})(:?(\\d{2})(:?(\\d{2}(\\.\\d+)?))?)?(Z|([+-])(\\d{2}):?(\\d{2})?)?)?/;\n"
-"var res = isoDateRegex.exec(isoDateStr);\n"
-"\n"
-"if (!res)\n"
-"throw \"invalid ISO date\";\n"
-"\n"
-"var year = parseInt(res[1],10) || 1970; // this should always be present\n"
-"var month = (parseInt(res[2],10) || 1) - 1;\n"
-"var date = parseInt(res[3],10) || 0;\n"
-"var hour = parseInt(res[5],10) || 0;\n"
-"var min = parseInt(res[7],10) || 0;\n"
-"var sec = parseFloat(res[9]) || 0;\n"
-"var ms = Math.round((sec%1) * 1000)\n"
-"sec -= ms/1000\n"
-"\n"
-"var time = Date.UTC(year, month, date, hour, min, sec, ms);\n"
-"\n"
-"if (res[11] && res[11] != 'Z'){\n"
-"var ofs = 0;\n"
-"ofs += (parseInt(res[13],10) || 0) * 60*60*1000; // hours\n"
-"ofs += (parseInt(res[14],10) || 0) * 60*1000; // mins\n"
-"if (res[12] == '+') // if ahead subtract\n"
-"ofs *= -1;\n"
-"\n"
-"time += ofs\n"
-"}\n"
-"\n"
-"return new Date(time);\n"
-"}\n"
-"\n"
-"RegExp.prototype.tojson = RegExp.prototype.toString;\n"
-"\n"
-"Array.contains = function( a , x ){\n"
-"for ( var i=0; i<a.length; i++ ){\n"
-"if ( a[i] == x )\n"
-"return true;\n"
-"}\n"
-"return false;\n"
-"}\n"
-"\n"
-"Array.unique = function( a ){\n"
-"var u = [];\n"
-"for ( var i=0; i<a.length; i++){\n"
-"var o = a[i];\n"
-"if ( ! Array.contains( u , o ) ){\n"
-"u.push( o );\n"
-"}\n"
-"}\n"
-"return u;\n"
-"}\n"
-"\n"
-"Array.shuffle = function( arr ){\n"
-"for ( var i=0; i<arr.length-1; i++ ){\n"
-"var pos = i+Random.randInt(arr.length-i);\n"
-"var save = arr[i];\n"
-"arr[i] = arr[pos];\n"
-"arr[pos] = save;\n"
-"}\n"
-"return arr;\n"
-"}\n"
-"\n"
-"\n"
-"Array.tojson = function( a , indent , nolint ){\n"
-"var lineEnding = nolint ? \" \" : \"\\n\";\n"
-"\n"
-"if (!indent)\n"
-"indent = \"\";\n"
-"\n"
-"if ( nolint )\n"
-"indent = \"\";\n"
-"\n"
-"if (a.length == 0) {\n"
-"return \"[ ]\";\n"
-"}\n"
-"\n"
-"var s = \"[\" + lineEnding;\n"
-"indent += \"\\t\";\n"
-"for ( var i=0; i<a.length; i++){\n"
-"s += indent + tojson( a[i], indent , nolint );\n"
-"if ( i < a.length - 1 ){\n"
-"s += \",\" + lineEnding;\n"
-"}\n"
-"}\n"
-"if ( a.length == 0 ) {\n"
-"s += indent;\n"
-"}\n"
-"\n"
-"indent = indent.substring(1);\n"
-"s += lineEnding+indent+\"]\";\n"
-"return s;\n"
-"}\n"
-"\n"
-"Array.fetchRefs = function( arr , coll ){\n"
-"var n = [];\n"
-"for ( var i=0; i<arr.length; i ++){\n"
-"var z = arr[i];\n"
-"if ( coll && coll != z.getCollection() )\n"
-"continue;\n"
-"n.push( z.fetch() );\n"
-"}\n"
-"\n"
-"return n;\n"
-"}\n"
-"\n"
-"Array.sum = function( arr ){\n"
-"if ( arr.length == 0 )\n"
-"return null;\n"
-"var s = arr[0];\n"
-"for ( var i=1; i<arr.length; i++ )\n"
-"s += arr[i];\n"
-"return s;\n"
-"}\n"
-"\n"
-"Array.avg = function( arr ){\n"
-"if ( arr.length == 0 )\n"
-"return null;\n"
-"return Array.sum( arr ) / arr.length;\n"
-"}\n"
-"\n"
-"Array.stdDev = function( arr ){\n"
-"var avg = Array.avg( arr );\n"
-"var sum = 0;\n"
-"\n"
-"for ( var i=0; i<arr.length; i++ ){\n"
-"sum += Math.pow( arr[i] - avg , 2 );\n"
-"}\n"
-"\n"
-"return Math.sqrt( sum / arr.length );\n"
-"}\n"
-"\n"
-"//these two are helpers for Array.sort(func)\n"
-"compare = function(l, r){ return (l == r ? 0 : (l < r ? -1 : 1)); }\n"
-"\n"
-"// arr.sort(compareOn('name'))\n"
-"compareOn = function(field){\n"
-"return function(l, r) { return compare(l[field], r[field]); }\n"
-"}\n"
-"\n"
-"Object.keySet = function( o ) {\n"
-"var ret = new Array();\n"
-"for( i in o ) {\n"
-"if ( !( i in o.__proto__ && o[ i ] === o.__proto__[ i ] ) ) {\n"
-"ret.push( i );\n"
-"}\n"
-"}\n"
-"return ret;\n"
-"}\n"
-"\n"
-"if ( ! NumberLong.prototype ) {\n"
-"NumberLong.prototype = {}\n"
-"}\n"
-"\n"
-"NumberLong.prototype.tojson = function() {\n"
-"return this.toString();\n"
-"}\n"
-"\n"
-"if ( ! NumberInt.prototype ) {\n"
-"NumberInt.prototype = {}\n"
-"}\n"
-"\n"
-"NumberInt.prototype.tojson = function() {\n"
-"return this.toString();\n"
-"}\n"
-"\n"
-"if ( ! ObjectId.prototype )\n"
-"ObjectId.prototype = {}\n"
-"\n"
-"ObjectId.prototype.toString = function(){\n"
-"return this.str;\n"
-"}\n"
-"\n"
-"ObjectId.prototype.tojson = function(){\n"
-"return \"ObjectId(\\\"\" + this.str + \"\\\")\";\n"
-"}\n"
-"\n"
-"ObjectId.prototype.isObjectId = true;\n"
-"\n"
-"ObjectId.prototype.getTimestamp = function(){\n"
-"return new Date(parseInt(this.toString().slice(0,8), 16)*1000);\n"
-"}\n"
-"\n"
-"ObjectId.prototype.equals = function( other){\n"
-"return this.str == other.str;\n"
-"}\n"
-"\n"
-"if ( typeof( DBPointer ) != \"undefined\" ){\n"
-"DBPointer.prototype.fetch = function(){\n"
-"assert( this.ns , \"need a ns\" );\n"
-"assert( this.id , \"need an id\" );\n"
-"\n"
-"return db[ this.ns ].findOne( { _id : this.id } );\n"
-"}\n"
-"\n"
-"DBPointer.prototype.tojson = function(indent){\n"
-"return tojson({\"ns\" : this.ns, \"id\" : this.id}, indent);\n"
-"}\n"
-"\n"
-"DBPointer.prototype.getCollection = function(){\n"
-"return this.ns;\n"
-"}\n"
-"\n"
-"DBPointer.prototype.toString = function(){\n"
-"return \"DBPointer \" + this.ns + \":\" + this.id;\n"
-"}\n"
-"}\n"
-"else {\n"
-"print( \"warning: no DBPointer\" );\n"
-"}\n"
-"\n"
-"if ( typeof( DBRef ) != \"undefined\" ){\n"
-"DBRef.prototype.fetch = function(){\n"
-"assert( this.$ref , \"need a ns\" );\n"
-"assert( this.$id , \"need an id\" );\n"
-"\n"
-"return db[ this.$ref ].findOne( { _id : this.$id } );\n"
-"}\n"
-"\n"
-"DBRef.prototype.tojson = function(indent){\n"
-"return tojson({\"$ref\" : this.$ref, \"$id\" : this.$id}, indent);\n"
-"}\n"
-"\n"
-"DBRef.prototype.getCollection = function(){\n"
-"return this.$ref;\n"
-"}\n"
-"\n"
-"DBRef.prototype.toString = function(){\n"
-"return this.tojson();\n"
-"}\n"
-"}\n"
-"else {\n"
-"print( \"warning: no DBRef\" );\n"
-"}\n"
-"\n"
-"if ( typeof( BinData ) != \"undefined\" ){\n"
-"BinData.prototype.tojson = function () {\n"
-"//return \"BinData type: \" + this.type + \" len: \" + this.len;\n"
-"return this.toString();\n"
-"}\n"
-"\n"
-"BinData.prototype.subtype = function () {\n"
-"return this.type;\n"
-"}\n"
-"\n"
-"BinData.prototype.length = function () {\n"
-"return this.len;\n"
-"}\n"
-"}\n"
-"else {\n"
-"print( \"warning: no BinData class\" );\n"
-"}\n"
-"\n"
-"/*if ( typeof( UUID ) != \"undefined\" ){\n"
-"UUID.prototype.tojson = function () {\n"
-"return this.toString();\n"
-"}\n"
-"}*/\n"
-"\n"
-"if ( typeof _threadInject != \"undefined\" ){\n"
-"print( \"fork() available!\" );\n"
-"\n"
-"Thread = function(){\n"
-"this.init.apply( this, arguments );\n"
-"}\n"
-"_threadInject( Thread.prototype );\n"
-"\n"
-"ScopedThread = function() {\n"
-"this.init.apply( this, arguments );\n"
-"}\n"
-"ScopedThread.prototype = new Thread( function() {} );\n"
-"_scopedThreadInject( ScopedThread.prototype );\n"
-"\n"
-"fork = function() {\n"
-"var t = new Thread( function() {} );\n"
-"Thread.apply( t, arguments );\n"
-"return t;\n"
-"}\n"
-"\n"
-"// Helper class to generate a list of events which may be executed by a ParallelTester\n"
-"EventGenerator = function( me, collectionName, mean ) {\n"
-"this.mean = mean;\n"
-"this.events = new Array( me, collectionName );\n"
-"}\n"
-"\n"
-"EventGenerator.prototype._add = function( action ) {\n"
-"this.events.push( [ Random.genExp( this.mean ), action ] );\n"
-"}\n"
-"\n"
-"EventGenerator.prototype.addInsert = function( obj ) {\n"
-"this._add( \"t.insert( \" + tojson( obj ) + \" )\" );\n"
-"}\n"
-"\n"
-"EventGenerator.prototype.addRemove = function( obj ) {\n"
-"this._add( \"t.remove( \" + tojson( obj ) + \" )\" );\n"
-"}\n"
-"\n"
-"EventGenerator.prototype.addUpdate = function( objOld, objNew ) {\n"
-"this._add( \"t.update( \" + tojson( objOld ) + \", \" + tojson( objNew ) + \" )\" );\n"
-"}\n"
-"\n"
-"EventGenerator.prototype.addCheckCount = function( count, query, shouldPrint, checkQuery ) {\n"
-"query = query || {};\n"
-"shouldPrint = shouldPrint || false;\n"
-"checkQuery = checkQuery || false;\n"
-"var action = \"assert.eq( \" + count + \", t.count( \" + tojson( query ) + \" ) );\"\n"
-"if ( checkQuery ) {\n"
-"action += \" assert.eq( \" + count + \", t.find( \" + tojson( query ) + \" ).toArray().length );\"\n"
-"}\n"
-"if ( shouldPrint ) {\n"
-"action += \" print( me + ' ' + \" + count + \" );\";\n"
-"}\n"
-"this._add( action );\n"
-"}\n"
-"\n"
-"EventGenerator.prototype.getEvents = function() {\n"
-"return this.events;\n"
-"}\n"
-"\n"
-"EventGenerator.dispatch = function() {\n"
-"var args = argumentsToArray( arguments );\n"
-"var me = args.shift();\n"
-"var collectionName = args.shift();\n"
-"var m = new Mongo( db.getMongo().host );\n"
-"var t = m.getDB( \"test\" )[ collectionName ];\n"
-"for( var i in args ) {\n"
-"sleep( args[ i ][ 0 ] );\n"
-"eval( args[ i ][ 1 ] );\n"
-"}\n"
-"}\n"
-"\n"
-"// Helper class for running tests in parallel. It assembles a set of tests\n"
-"// and then calls assert.parallelests to run them.\n"
-"ParallelTester = function() {\n"
-"this.params = new Array();\n"
-"}\n"
-"\n"
-"ParallelTester.prototype.add = function( fun, args ) {\n"
-"args = args || [];\n"
-"args.unshift( fun );\n"
-"this.params.push( args );\n"
-"}\n"
-"\n"
-"ParallelTester.prototype.run = function( msg, newScopes ) {\n"
-"newScopes = newScopes || false;\n"
-"assert.parallelTests( this.params, msg, newScopes );\n"
-"}\n"
-"\n"
-"// creates lists of tests from jstests dir in a format suitable for use by\n"
-"// ParallelTester.fileTester. The lists will be in random order.\n"
-"// n: number of lists to split these tests into\n"
-"ParallelTester.createJstestsLists = function( n ) {\n"
-"var params = new Array();\n"
-"for( var i = 0; i < n; ++i ) {\n"
-"params.push( [] );\n"
-"}\n"
-"\n"
-"var makeKeys = function( a ) {\n"
-"var ret = {};\n"
-"for( var i in a ) {\n"
-"ret[ a[ i ] ] = 1;\n"
-"}\n"
-"return ret;\n"
-"}\n"
-"\n"
-"// some tests can't run in parallel with most others\n"
-"var skipTests = makeKeys( [ \"jstests/dbadmin.js\",\n"
-"\"jstests/repair.js\",\n"
-"\"jstests/cursor8.js\",\n"
-"\"jstests/recstore.js\",\n"
-"\"jstests/extent.js\",\n"
-"\"jstests/indexb.js\",\n"
-"\"jstests/profile1.js\",\n"
-"\"jstests/mr3.js\",\n"
-"\"jstests/indexh.js\",\n"
-"\"jstests/apitest_db.js\",\n"
-"\"jstests/evalb.js\",\n"
-"\"jstests/evald.js\",\n"
-"\"jstests/evalf.js\",\n"
-"\"jstests/killop.js\",\n"
-"\"jstests/run_program1.js\",\n"
-"\"jstests/notablescan.js\",\n"
-"\"jstests/drop2.js\",\n"
-"\"jstests/dropdb_race.js\",\n"
-"\"jstests/bench_test1.js\",\n"
-"\"jstests/queryoptimizera.js\"] );\n"
-"\n"
-"// some tests can't be run in parallel with each other\n"
-"var serialTestsArr = [ \"jstests/fsync.js\",\n"
-"\"jstests/fsync2.js\" ];\n"
-"var serialTests = makeKeys( serialTestsArr );\n"
-"\n"
-"params[ 0 ] = serialTestsArr;\n"
-"\n"
-"var files = listFiles(\"jstests\");\n"
-"files = Array.shuffle( files );\n"
-"\n"
-"var i = 0;\n"
-"files.forEach(\n"
-"function(x) {\n"
-"\n"
-"if ( ( /[\\/\\\\]_/.test(x.name) ) ||\n"
-"( ! /\\.js$/.test(x.name ) ) ||\n"
-"( x.name in skipTests ) ||\n"
-"( x.name in serialTests ) ||\n"
-"! /\\.js$/.test(x.name ) ){\n"
-"print(\" >>>>>>>>>>>>>>> skipping \" + x.name);\n"
-"return;\n"
-"}\n"
-"\n"
-"params[ i % n ].push( x.name );\n"
-"++i;\n"
-"}\n"
-");\n"
-"\n"
-"// randomize ordering of the serialTests\n"
-"params[ 0 ] = Array.shuffle( params[ 0 ] );\n"
-"\n"
-"for( var i in params ) {\n"
-"params[ i ].unshift( i );\n"
-"}\n"
-"\n"
-"return params;\n"
-"}\n"
-"\n"
-"// runs a set of test files\n"
-"// first argument is an identifier for this tester, remaining arguments are file names\n"
-"ParallelTester.fileTester = function() {\n"
-"var args = argumentsToArray( arguments );\n"
-"var suite = args.shift();\n"
-"args.forEach(\n"
-"function( x ) {\n"
-"print(\" S\" + suite + \" Test : \" + x + \" ...\");\n"
-"var time = Date.timeFunc( function() { load(x); }, 1);\n"
-"print(\" S\" + suite + \" Test : \" + x + \" \" + time + \"ms\" );\n"
-"}\n"
-");\n"
-"}\n"
-"\n"
-"// params: array of arrays, each element of which consists of a function followed\n"
-"// by zero or more arguments to that function. Each function and its arguments will\n"
-"// be called in a separate thread.\n"
-"// msg: failure message\n"
-"// newScopes: if true, each thread starts in a fresh scope\n"
-"assert.parallelTests = function( params, msg, newScopes ) {\n"
-"newScopes = newScopes || false;\n"
-"var wrapper = function( fun, argv ) {\n"
-"eval (\n"
-"\"var z = function() {\" +\n"
-"\"var __parallelTests__fun = \" + fun.toString() + \";\" +\n"
-"\"var __parallelTests__argv = \" + tojson( argv ) + \";\" +\n"
-"\"var __parallelTests__passed = false;\" +\n"
-"\"try {\" +\n"
-"\"__parallelTests__fun.apply( 0, __parallelTests__argv );\" +\n"
-"\"__parallelTests__passed = true;\" +\n"
-"\"} catch ( e ) {\" +\n"
-"\"print( '********** Parallel Test FAILED: ' + tojson(e) );\" +\n"
-"\"}\" +\n"
-"\"return __parallelTests__passed;\" +\n"
-"\"}\"\n"
-");\n"
-"return z;\n"
-"}\n"
-"var runners = new Array();\n"
-"for( var i in params ) {\n"
-"var param = params[ i ];\n"
-"var test = param.shift();\n"
-"var t;\n"
-"if ( newScopes )\n"
-"t = new ScopedThread( wrapper( test, param ) );\n"
-"else\n"
-"t = new Thread( wrapper( test, param ) );\n"
-"runners.push( t );\n"
-"}\n"
-"\n"
-"runners.forEach( function( x ) { x.start(); } );\n"
-"var nFailed = 0;\n"
-"// v8 doesn't like it if we exit before all threads are joined (SERVER-529)\n"
-"runners.forEach( function( x ) { if( !x.returnData() ) { ++nFailed; } } );\n"
-"assert.eq( 0, nFailed, msg );\n"
-"}\n"
-"}\n"
-"\n"
-"tojsononeline = function( x ){\n"
-"return tojson( x , \" \" , true );\n"
-"}\n"
-"\n"
-"tojson = function( x, indent , nolint ){\n"
-"if ( x === null )\n"
-"return \"null\";\n"
-"\n"
-"if ( x === undefined )\n"
-"return \"undefined\";\n"
-"\n"
-"if (!indent)\n"
-"indent = \"\";\n"
-"\n"
-"switch ( typeof x ) {\n"
-"case \"string\": {\n"
-"var s = \"\\\"\";\n"
-"for ( var i=0; i<x.length; i++ ){\n"
-"switch (x[i]){\n"
-"case '\"': s += '\\\\\"'; break;\n"
-"case '\\\\': s += '\\\\\\\\'; break;\n"
-"case '\\b': s += '\\\\b'; break;\n"
-"case '\\f': s += '\\\\f'; break;\n"
-"case '\\n': s += '\\\\n'; break;\n"
-"case '\\r': s += '\\\\r'; break;\n"
-"case '\\t': s += '\\\\t'; break;\n"
-"\n"
-"default: {\n"
-"var code = x.charCodeAt(i);\n"
-"if (code < 0x20){\n"
-"s += (code < 0x10 ? '\\\\u000' : '\\\\u00') + code.toString(16);\n"
-"} else {\n"
-"s += x[i];\n"
-"}\n"
-"}\n"
-"}\n"
-"}\n"
-"return s + \"\\\"\";\n"
-"}\n"
-"case \"number\":\n"
-"case \"boolean\":\n"
-"return \"\" + x;\n"
-"case \"object\":{\n"
-"var s = tojsonObject( x, indent , nolint );\n"
-"if ( ( nolint == null || nolint == true ) && s.length < 80 && ( indent == null || indent.length == 0 ) ){\n"
-"s = s.replace( /[\\s\\r\\n ]+/gm , \" \" );\n"
-"}\n"
-"return s;\n"
-"}\n"
-"case \"function\":\n"
-"return x.toString();\n"
-"default:\n"
-"throw \"tojson can't handle type \" + ( typeof x );\n"
-"}\n"
-"\n"
-"}\n"
-"\n"
-"tojsonObject = function( x, indent , nolint ){\n"
-"var lineEnding = nolint ? \" \" : \"\\n\";\n"
-"var tabSpace = nolint ? \"\" : \"\\t\";\n"
-"\n"
-"assert.eq( ( typeof x ) , \"object\" , \"tojsonObject needs object, not [\" + ( typeof x ) + \"]\" );\n"
-"\n"
-"if (!indent)\n"
-"indent = \"\";\n"
-"\n"
-"if ( typeof( x.tojson ) == \"function\" && x.tojson != tojson ) {\n"
-"return x.tojson(indent,nolint);\n"
-"}\n"
-"\n"
-"if ( x.constructor && typeof( x.constructor.tojson ) == \"function\" && x.constructor.tojson != tojson ) {\n"
-"return x.constructor.tojson( x, indent , nolint );\n"
-"}\n"
-"\n"
-"if ( x.toString() == \"[object MaxKey]\" )\n"
-"return \"{ $maxKey : 1 }\";\n"
-"if ( x.toString() == \"[object MinKey]\" )\n"
-"return \"{ $minKey : 1 }\";\n"
-"\n"
-"var s = \"{\" + lineEnding;\n"
-"\n"
-"// push one level of indent\n"
-"indent += tabSpace;\n"
-"\n"
-"var total = 0;\n"
-"for ( var k in x ) total++;\n"
-"if ( total == 0 ) {\n"
-"s += indent + lineEnding;\n"
-"}\n"
-"\n"
-"var keys = x;\n"
-"if ( typeof( x._simpleKeys ) == \"function\" )\n"
-"keys = x._simpleKeys();\n"
-"var num = 1;\n"
-"for ( var k in keys ){\n"
-"\n"
-"var val = x[k];\n"
-"if ( val == DB.prototype || val == DBCollection.prototype )\n"
-"continue;\n"
-"\n"
-"s += indent + \"\\\"\" + k + \"\\\" : \" + tojson( val, indent , nolint );\n"
-"if (num != total) {\n"
-"s += \",\";\n"
-"num++;\n"
-"}\n"
-"s += lineEnding;\n"
-"}\n"
-"\n"
-"// pop one level of indent\n"
-"indent = indent.substring(1);\n"
-"return s + indent + \"}\";\n"
-"}\n"
-"\n"
-"shellPrint = function( x ){\n"
-"it = x;\n"
-"if ( x != undefined )\n"
-"shellPrintHelper( x );\n"
-"\n"
-"if ( db ){\n"
-"var e = db.getPrevError();\n"
-"if ( e.err ) {\n"
-"if( e.nPrev <= 1 )\n"
-"print( \"error on last call: \" + tojson( e.err ) );\n"
-"else\n"
-"print( \"an error \" + tojson(e.err) + \" occurred \" + e.nPrev + \" operations back in the command invocation\" );\n"
-"}\n"
-"db.resetError();\n"
-"}\n"
-"}\n"
-"\n"
-"printjson = function(x){\n"
-"print( tojson( x ) );\n"
-"}\n"
-"\n"
-"printjsononeline = function(x){\n"
-"print( tojsononeline( x ) );\n"
-"}\n"
-"\n"
-"if ( typeof TestData == \"undefined\" ){\n"
-"TestData = undefined\n"
-"}\n"
-"\n"
-"jsTestName = function(){\n"
-"if( TestData ) return TestData.testName\n"
-"return \"__unknown_name__\"\n"
-"}\n"
-"\n"
-"jsTestFile = function(){\n"
-"if( TestData ) return TestData.testFile\n"
-"return \"__unknown_file__\"\n"
-"}\n"
-"\n"
-"jsTestPath = function(){\n"
-"if( TestData ) return TestData.testPath\n"
-"return \"__unknown_path__\"\n"
-"}\n"
-"\n"
-"jsTestOptions = function(){\n"
-"if( TestData ) return { noJournal : TestData.noJournal,\n"
-"noJournalPrealloc : TestData.noJournalPrealloc }\n"
-"return {}\n"
-"}\n"
-"\n"
-"jsTestLog = function(msg){\n"
-"print( \"\\n\\n----\\n\" + msg + \"\\n----\\n\\n\" )\n"
-"}\n"
-"\n"
-"shellPrintHelper = function (x) {\n"
-"\n"
-"if (typeof (x) == \"undefined\") {\n"
-"\n"
-"if (typeof (db) != \"undefined\" && db.getLastError) {\n"
-"// explicit w:1 so that replset getLastErrorDefaults aren't used here which would be bad.\n"
-"var e = db.getLastError(1);\n"
-"if (e != null)\n"
-"print(e);\n"
-"}\n"
-"\n"
-"return;\n"
-"}\n"
-"\n"
-"if (x == __magicNoPrint)\n"
-"return;\n"
-"\n"
-"if (x == null) {\n"
-"print(\"null\");\n"
-"return;\n"
-"}\n"
-"\n"
-"if (typeof x != \"object\")\n"
-"return print(x);\n"
-"\n"
-"var p = x.shellPrint;\n"
-"if (typeof p == \"function\")\n"
-"return x.shellPrint();\n"
-"\n"
-"var p = x.tojson;\n"
-"if (typeof p == \"function\")\n"
-"print(x.tojson());\n"
-"else\n"
-"print(tojson(x));\n"
-"}\n"
-"\n"
-"shellAutocomplete = function (/*prefix*/){ // outer scope function called on init. Actual function at end\n"
-"\n"
-"var universalMethods = \"constructor prototype toString valueOf toLocaleString hasOwnProperty propertyIsEnumerable\".split(' ');\n"
-"\n"
-"var builtinMethods = {}; // uses constructor objects as keys\n"
-"builtinMethods[Array] = \"length concat join pop push reverse shift slice sort splice unshift indexOf lastIndexOf every filter forEach map some\".split(' ');\n"
-"builtinMethods[Boolean] = \"\".split(' '); // nothing more than universal methods\n"
-"builtinMethods[Date] = \"getDate getDay getFullYear getHours getMilliseconds getMinutes getMonth getSeconds getTime getTimezoneOffset getUTCDate getUTCDay getUTCFullYear getUTCHours getUTCMilliseconds getUTCMinutes getUTCMonth getUTCSeconds getYear parse setDate setFullYear setHours setMilliseconds setMinutes setMonth setSeconds setTime setUTCDate setUTCFullYear setUTCHours setUTCMilliseconds setUTCMinutes setUTCMonth setUTCSeconds setYear toDateString toGMTString toLocaleDateString toLocaleTimeString toTimeString toUTCString UTC\".split(' ');\n"
-"builtinMethods[Math] = \"E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan\".split(' ');\n"
-"builtinMethods[Number] = \"MAX_VALUE MIN_VALUE NEGATIVE_INFINITY POSITIVE_INFINITY toExponential toFixed toPrecision\".split(' ');\n"
-"builtinMethods[RegExp] = \"global ignoreCase lastIndex multiline source compile exec test\".split(' ');\n"
-"builtinMethods[String] = \"length charAt charCodeAt concat fromCharCode indexOf lastIndexOf match replace search slice split substr substring toLowerCase toUpperCase\".split(' ');\n"
-"builtinMethods[Function] = \"call apply\".split(' ');\n"
-"builtinMethods[Object] = \"bsonsize\".split(' ');\n"
-"\n"
-"builtinMethods[Mongo] = \"find update insert remove\".split(' ');\n"
-"builtinMethods[BinData] = \"hex base64 length subtype\".split(' ');\n"
-"\n"
-"var extraGlobals = \"Infinity NaN undefined null true false decodeURI decodeURIComponent encodeURI encodeURIComponent escape eval isFinite isNaN parseFloat parseInt unescape Array Boolean Date Math Number RegExp String print load gc MinKey MaxKey Mongo NumberLong ObjectId DBPointer UUID BinData Map\".split(' ');\n"
-"\n"
-"var isPrivate = function(name){\n"
-"if (shellAutocomplete.showPrivate) return false;\n"
-"if (name == '_id') return false;\n"
-"if (name[0] == '_') return true;\n"
-"if (name[name.length-1] == '_') return true; // some native functions have an extra name_ method\n"
-"return false;\n"
-"}\n"
-"\n"
-"var customComplete = function(obj){\n"
-"try {\n"
-"if(obj.__proto__.constructor.autocomplete){\n"
-"var ret = obj.constructor.autocomplete(obj);\n"
-"if (ret.constructor != Array){\n"
-"print(\"\\nautocompleters must return real Arrays\");\n"
-"return [];\n"
-"}\n"
-"return ret;\n"
-"} else {\n"
-"return [];\n"
-"}\n"
-"} catch (e) {\n"
-"// print(e); // uncomment if debugging custom completers\n"
-"return [];\n"
-"}\n"
-"}\n"
-"\n"
-"var worker = function( prefix ){\n"
-"var global = (function(){return this;}).call(); // trick to get global object\n"
-"\n"
-"var curObj = global;\n"
-"var parts = prefix.split('.');\n"
-"for (var p=0; p < parts.length - 1; p++){ // doesn't include last part\n"
-"curObj = curObj[parts[p]];\n"
-"if (curObj == null)\n"
-"return [];\n"
-"}\n"
-"\n"
-"var lastPrefix = parts[parts.length-1] || '';\n"
-"var begining = parts.slice(0, parts.length-1).join('.');\n"
-"if (begining.length)\n"
-"begining += '.';\n"
-"\n"
-"var possibilities = new Array().concat(\n"
-"universalMethods,\n"
-"Object.keySet(curObj),\n"
-"Object.keySet(curObj.__proto__),\n"
-"builtinMethods[curObj] || [], // curObj is a builtin constructor\n"
-"builtinMethods[curObj.__proto__.constructor] || [], // curObj is made from a builtin constructor\n"
-"curObj == global ? extraGlobals : [],\n"
-"customComplete(curObj)\n"
-");\n"
-"\n"
-"var ret = [];\n"
-"for (var i=0; i < possibilities.length; i++){\n"
-"var p = possibilities[i];\n"
-"if (typeof(curObj[p]) == \"undefined\" && curObj != global) continue; // extraGlobals aren't in the global object\n"
-"if (p.length == 0 || p.length < lastPrefix.length) continue;\n"
-"if (lastPrefix[0] != '_' && isPrivate(p)) continue;\n"
-"if (p.match(/^[0-9]+$/)) continue; // don't array number indexes\n"
-"if (p.substr(0, lastPrefix.length) != lastPrefix) continue;\n"
-"\n"
-"var completion = begining + p;\n"
-"if(curObj[p] && curObj[p].constructor == Function && p != 'constructor')\n"
-"completion += '(';\n"
-"\n"
-"ret.push(completion);\n"
-"}\n"
-"\n"
-"return ret;\n"
-"}\n"
-"\n"
-"// this is the actual function that gets assigned to shellAutocomplete\n"
-"return function( prefix ){\n"
-"try {\n"
-"__autocomplete__ = worker(prefix).sort();\n"
-"}catch (e){\n"
-"print(\"exception durring autocomplete: \" + tojson(e.message));\n"
-"__autocomplete__ = [];\n"
-"}\n"
-"}\n"
-"}();\n"
-"\n"
-"shellAutocomplete.showPrivate = false; // toggle to show (useful when working on internals)\n"
-"\n"
-"shellHelper = function( command , rest , shouldPrint ){\n"
-"command = command.trim();\n"
-"var args = rest.trim().replace(/\\s*;$/,\"\").split( \"\\s+\" );\n"
-"\n"
-"if ( ! shellHelper[command] )\n"
-"throw \"no command [\" + command + \"]\";\n"
-"\n"
-"var res = shellHelper[command].apply( null , args );\n"
-"if ( shouldPrint ){\n"
-"shellPrintHelper( res );\n"
-"}\n"
-"return res;\n"
-"}\n"
-"\n"
-"shellHelper.use = function (dbname) {\n"
-"var s = \"\" + dbname;\n"
-"if (s == \"\") {\n"
-"print(\"bad use parameter\");\n"
-"return;\n"
-"}\n"
-"db = db.getMongo().getDB(dbname);\n"
-"print(\"switched to db \" + db.getName());\n"
-"}\n"
-"\n"
-"shellHelper.it = function(){\n"
-"if ( typeof( ___it___ ) == \"undefined\" || ___it___ == null ){\n"
-"print( \"no cursor\" );\n"
-"return;\n"
-"}\n"
-"shellPrintHelper( ___it___ );\n"
-"}\n"
-"\n"
-"shellHelper.show = function (what) {\n"
-"assert(typeof what == \"string\");\n"
-"\n"
-"var args = what.split( /\\s+/ );\n"
-"what = args[0]\n"
-"args = args.splice(1)\n"
-"\n"
-"if (what == \"profile\") {\n"
-"if (db.system.profile.count() == 0) {\n"
-"print(\"db.system.profile is empty\");\n"
-"print(\"Use db.setProfilingLevel(2) will enable profiling\");\n"
-"print(\"Use db.system.profile.find() to show raw profile entries\");\n"
-"}\n"
-"else {\n"
-"print();\n"
-"db.system.profile.find({ millis: { $gt: 0} }).sort({ $natural: -1 }).limit(5).forEach(\n"
-"function (x) {\n"
-"print(\"\" + x.op + \"\\t\" + x.ns + \" \" + x.millis + \"ms \" + String(x.ts).substring(0, 24));\n"
-"var l = \"\";\n"
-"for ( var z in x ){\n"
-"if ( z == \"op\" || z == \"ns\" || z == \"millis\" || z == \"ts\" )\n"
-"continue;\n"
-"\n"
-"var val = x[z];\n"
-"var mytype = typeof(val);\n"
-"\n"
-"if ( mytype == \"string\" ||\n"
-"mytype == \"number\" )\n"
-"l += z + \":\" + val + \" \";\n"
-"else if ( mytype == \"object\" )\n"
-"l += z + \":\" + tojson(val ) + \" \";\n"
-"else if ( mytype == \"boolean\" )\n"
-"l += z + \" \";\n"
-"else\n"
-"l += z + \":\" + val + \" \";\n"
-"\n"
-"}\n"
-"print( l );\n"
-"print(\"\\n\");\n"
-"}\n"
-")\n"
-"}\n"
-"return \"\";\n"
-"}\n"
-"\n"
-"if (what == \"users\") {\n"
-"db.system.users.find().forEach(printjson);\n"
-"return \"\";\n"
-"}\n"
-"\n"
-"if (what == \"collections\" || what == \"tables\") {\n"
-"db.getCollectionNames().forEach(function (x) { print(x) });\n"
-"return \"\";\n"
-"}\n"
-"\n"
-"if (what == \"dbs\") {\n"
-"var dbs = db.getMongo().getDBs();\n"
-"var size = {};\n"
-"dbs.databases.forEach(function (x) { size[x.name] = x.sizeOnDisk; });\n"
-"var names = dbs.databases.map(function (z) { return z.name; }).sort();\n"
-"names.forEach(function (n) {\n"
-"if (size[n] > 1) {\n"
-"print(n + \"\\t\" + size[n] / 1024 / 1024 / 1024 + \"GB\");\n"
-"} else {\n"
-"print(n + \"\\t(empty)\");\n"
-"}\n"
-"});\n"
-"//db.getMongo().getDBNames().sort().forEach(function (x) { print(x) });\n"
-"return \"\";\n"
-"}\n"
-"\n"
-"if (what == \"log\" ) {\n"
-"var n = \"global\";\n"
-"if ( args.length > 0 )\n"
-"n = args[0]\n"
-"\n"
-"var res = db.adminCommand( { getLog : n } )\n"
-"for ( var i=0; i<res.log.length; i++){\n"
-"print( res.log[i] )\n"
-"}\n"
-"return \"\"\n"
-"}\n"
-"\n"
-"if (what == \"logs\" ) {\n"
-"var res = db.adminCommand( { getLog : \"*\" } )\n"
-"for ( var i=0; i<res.names.length; i++){\n"
-"print( res.names[i] )\n"
-"}\n"
-"return \"\"\n"
-"}\n"
-"\n"
-"\n"
-"throw \"don't know how to show [\" + what + \"]\";\n"
-"\n"
-"}\n"
-"\n"
-"if ( typeof( Map ) == \"undefined\" ){\n"
-"Map = function(){\n"
-"this._data = {};\n"
-"}\n"
-"}\n"
-"\n"
-"Map.hash = function( val ){\n"
-"if ( ! val )\n"
-"return val;\n"
-"\n"
-"switch ( typeof( val ) ){\n"
-"case 'string':\n"
-"case 'number':\n"
-"case 'date':\n"
-"return val.toString();\n"
-"case 'object':\n"
-"case 'array':\n"
-"var s = \"\";\n"
-"for ( var k in val ){\n"
-"s += k + val[k];\n"
-"}\n"
-"return s;\n"
-"}\n"
-"\n"
-"throw \"can't hash : \" + typeof( val );\n"
-"}\n"
-"\n"
-"Map.prototype.put = function( key , value ){\n"
-"var o = this._get( key );\n"
-"var old = o.value;\n"
-"o.value = value;\n"
-"return old;\n"
-"}\n"
-"\n"
-"Map.prototype.get = function( key ){\n"
-"return this._get( key ).value;\n"
-"}\n"
-"\n"
-"Map.prototype._get = function( key ){\n"
-"var h = Map.hash( key );\n"
-"var a = this._data[h];\n"
-"if ( ! a ){\n"
-"a = [];\n"
-"this._data[h] = a;\n"
-"}\n"
-"\n"
-"for ( var i=0; i<a.length; i++ ){\n"
-"if ( friendlyEqual( key , a[i].key ) ){\n"
-"return a[i];\n"
-"}\n"
-"}\n"
-"var o = { key : key , value : null };\n"
-"a.push( o );\n"
-"return o;\n"
-"}\n"
-"\n"
-"Map.prototype.values = function(){\n"
-"var all = [];\n"
-"for ( var k in this._data ){\n"
-"this._data[k].forEach( function(z){ all.push( z.value ); } );\n"
-"}\n"
-"return all;\n"
-"}\n"
-"\n"
-"if ( typeof( gc ) == \"undefined\" ){\n"
-"gc = function(){\n"
-"print( \"warning: using noop gc()\" );\n"
-"}\n"
-"}\n"
-"\n"
-"\n"
-"Math.sigFig = function( x , N ){\n"
-"if ( ! N ){\n"
-"N = 3;\n"
-"}\n"
-"var p = Math.pow( 10, N - Math.ceil( Math.log( Math.abs(x) ) / Math.log( 10 )) );\n"
-"return Math.round(x*p)/p;\n"
-"}\n"
-"\n"
-"Random = function() {}\n"
-"\n"
-"// set random seed\n"
-"Random.srand = function( s ) { _srand( s ); }\n"
-"\n"
-"// random number 0 <= r < 1\n"
-"Random.rand = function() { return _rand(); }\n"
-"\n"
-"// random integer 0 <= r < n\n"
-"Random.randInt = function( n ) { return Math.floor( Random.rand() * n ); }\n"
-"\n"
-"Random.setRandomSeed = function( s ) {\n"
-"s = s || new Date().getTime();\n"
-"print( \"setting random seed: \" + s );\n"
-"Random.srand( s );\n"
-"}\n"
-"\n"
-"// generate a random value from the exponential distribution with the specified mean\n"
-"Random.genExp = function( mean ) {\n"
-"return -Math.log( Random.rand() ) * mean;\n"
-"}\n"
-"\n"
-"Geo = {};\n"
-"Geo.distance = function( a , b ){\n"
-"var ax = null;\n"
-"var ay = null;\n"
-"var bx = null;\n"
-"var by = null;\n"
-"\n"
-"for ( var key in a ){\n"
-"if ( ax == null )\n"
-"ax = a[key];\n"
-"else if ( ay == null )\n"
-"ay = a[key];\n"
-"}\n"
-"\n"
-"for ( var key in b ){\n"
-"if ( bx == null )\n"
-"bx = b[key];\n"
-"else if ( by == null )\n"
-"by = b[key];\n"
-"}\n"
-"\n"
-"return Math.sqrt( Math.pow( by - ay , 2 ) +\n"
-"Math.pow( bx - ax , 2 ) );\n"
-"}\n"
-"\n"
-"Geo.sphereDistance = function( a , b ){\n"
-"var ax = null;\n"
-"var ay = null;\n"
-"var bx = null;\n"
-"var by = null;\n"
-"\n"
-"// TODO swap order of x and y when done on server\n"
-"for ( var key in a ){\n"
-"if ( ax == null )\n"
-"ax = a[key] * (Math.PI/180);\n"
-"else if ( ay == null )\n"
-"ay = a[key] * (Math.PI/180);\n"
-"}\n"
-"\n"
-"for ( var key in b ){\n"
-"if ( bx == null )\n"
-"bx = b[key] * (Math.PI/180);\n"
-"else if ( by == null )\n"
-"by = b[key] * (Math.PI/180);\n"
-"}\n"
-"\n"
-"var sin_x1=Math.sin(ax), cos_x1=Math.cos(ax);\n"
-"var sin_y1=Math.sin(ay), cos_y1=Math.cos(ay);\n"
-"var sin_x2=Math.sin(bx), cos_x2=Math.cos(bx);\n"
-"var sin_y2=Math.sin(by), cos_y2=Math.cos(by);\n"
-"\n"
-"var cross_prod =\n"
-"(cos_y1*cos_x1 * cos_y2*cos_x2) +\n"
-"(cos_y1*sin_x1 * cos_y2*sin_x2) +\n"
-"(sin_y1 * sin_y2);\n"
-"\n"
-"if (cross_prod >= 1 || cross_prod <= -1){\n"
-"// fun with floats\n"
-"assert( Math.abs(cross_prod)-1 < 1e-6 );\n"
-"return cross_prod > 0 ? 0 : Math.PI;\n"
-"}\n"
-"\n"
-"return Math.acos(cross_prod);\n"
-"}\n"
-"\n"
-"rs = function () { return \"try rs.help()\"; }\n"
-"\n"
-"rs.help = function () {\n"
-"print(\"\\trs.status() { replSetGetStatus : 1 } checks repl set status\");\n"
-"print(\"\\trs.initiate() { replSetInitiate : null } initiates set with default settings\");\n"
-"print(\"\\trs.initiate(cfg) { replSetInitiate : cfg } initiates set with configuration cfg\");\n"
-"print(\"\\trs.conf() get the current configuration object from local.system.replset\");\n"
-"print(\"\\trs.reconfig(cfg) updates the configuration of a running replica set with cfg (disconnects)\");\n"
-"print(\"\\trs.add(hostportstr) add a new member to the set with default attributes (disconnects)\");\n"
-"print(\"\\trs.add(membercfgobj) add a new member to the set with extra attributes (disconnects)\");\n"
-"print(\"\\trs.addArb(hostportstr) add a new member which is arbiterOnly:true (disconnects)\");\n"
-"print(\"\\trs.stepDown([secs]) step down as primary (momentarily) (disconnects)\");\n"
-"print(\"\\trs.freeze(secs) make a node ineligible to become primary for the time specified\");\n"
-"print(\"\\trs.remove(hostportstr) remove a host from the replica set (disconnects)\");\n"
-"print(\"\\trs.slaveOk() shorthand for db.getMongo().setSlaveOk()\");\n"
-"print();\n"
-"print(\"\\tdb.isMaster() check who is primary\");\n"
-"print();\n"
-"print(\"\\treconfiguration helpers disconnect from the database so the shell will display\");\n"
-"print(\"\\tan error, even if the command succeeds.\");\n"
-"print(\"\\tsee also http://<mongod_host>:28017/_replSet for additional diagnostic info\");\n"
-"}\n"
-"rs.slaveOk = function () { return db.getMongo().setSlaveOk(); }\n"
-"rs.status = function () { return db._adminCommand(\"replSetGetStatus\"); }\n"
-"rs.isMaster = function () { return db.isMaster(); }\n"
-"rs.initiate = function (c) { return db._adminCommand({ replSetInitiate: c }); }\n"
-"rs._runCmd = function (c) {\n"
-"// after the command, catch the disconnect and reconnect if necessary\n"
-"var res = null;\n"
-"try {\n"
-"res = db.adminCommand(c);\n"
-"}\n"
-"catch (e) {\n"
-"if ((\"\" + e).indexOf(\"error doing query\") >= 0) {\n"
-"// closed connection. reconnect.\n"
-"db.getLastErrorObj();\n"
-"var o = db.getLastErrorObj();\n"
-"if (o.ok) {\n"
-"print(\"reconnected to server after rs command (which is normal)\");\n"
-"}\n"
-"else {\n"
-"printjson(o);\n"
-"}\n"
-"}\n"
-"else {\n"
-"print(\"shell got exception during repl set operation: \" + e);\n"
-"print(\"in some circumstances, the primary steps down and closes connections on a reconfig\");\n"
-"}\n"
-"return \"\";\n"
-"}\n"
-"return res;\n"
-"}\n"
-"rs.reconfig = function (cfg, options) {\n"
-"cfg.version = rs.conf().version + 1;\n"
-"cmd = { replSetReconfig: cfg };\n"
-"for (var i in options) {\n"
-"cmd[i] = options[i];\n"
-"}\n"
-"return this._runCmd(cmd);\n"
-"}\n"
-"rs.add = function (hostport, arb) {\n"
-"var cfg = hostport;\n"
-"\n"
-"var local = db.getSisterDB(\"local\");\n"
-"assert(local.system.replset.count() <= 1, \"error: local.system.replset has unexpected contents\");\n"
-"var c = local.system.replset.findOne();\n"
-"assert(c, \"no config object retrievable from local.system.replset\");\n"
-"\n"
-"c.version++;\n"
-"\n"
-"var max = 0;\n"
-"for (var i in c.members)\n"
-"if (c.members[i]._id > max) max = c.members[i]._id;\n"
-"if (isString(hostport)) {\n"
-"cfg = { _id: max + 1, host: hostport };\n"
-"if (arb)\n"
-"cfg.arbiterOnly = true;\n"
-"}\n"
-"c.members.push(cfg);\n"
-"return this._runCmd({ replSetReconfig: c });\n"
-"}\n"
-"rs.stepDown = function (secs) { return db._adminCommand({ replSetStepDown:(secs === undefined) ? 60:secs}); }\n"
-"rs.freeze = function (secs) { return db._adminCommand({replSetFreeze:secs}); }\n"
-"rs.addArb = function (hn) { return this.add(hn, true); }\n"
-"rs.conf = function () { return db.getSisterDB(\"local\").system.replset.findOne(); }\n"
-"rs.config = function () { return rs.conf(); }\n"
-"\n"
-"rs.remove = function (hn) {\n"
-"var local = db.getSisterDB(\"local\");\n"
-"assert(local.system.replset.count() <= 1, \"error: local.system.replset has unexpected contents\");\n"
-"var c = local.system.replset.findOne();\n"
-"assert(c, \"no config object retrievable from local.system.replset\");\n"
-"c.version++;\n"
-"\n"
-"for (var i in c.members) {\n"
-"if (c.members[i].host == hn) {\n"
-"c.members.splice(i, 1);\n"
-"return db._adminCommand({ replSetReconfig : c});\n"
-"}\n"
-"}\n"
-"\n"
-"return \"error: couldn't find \"+hn+\" in \"+tojson(c.members);\n"
-"};\n"
-"\n"
-"rs.debug = {};\n"
-"\n"
-"rs.debug.nullLastOpWritten = function(primary, secondary) {\n"
-"var p = connect(primary+\"/local\");\n"
-"var s = connect(secondary+\"/local\");\n"
-"s.getMongo().setSlaveOk();\n"
-"\n"
-"var secondToLast = s.oplog.rs.find().sort({$natural : -1}).limit(1).next();\n"
-"var last = p.runCommand({findAndModify : \"oplog.rs\",\n"
-"query : {ts : {$gt : secondToLast.ts}},\n"
-"sort : {$natural : 1},\n"
-"update : {$set : {op : \"n\"}}});\n"
-"\n"
-"if (!last.value.o || !last.value.o._id) {\n"
-"print(\"couldn't find an _id?\");\n"
-"}\n"
-"else {\n"
-"last.value.o = {_id : last.value.o._id};\n"
-"}\n"
-"\n"
-"print(\"nulling out this op:\");\n"
-"printjson(last);\n"
-"};\n"
-"\n"
-"rs.debug.getLastOpWritten = function(server) {\n"
-"var s = db.getSisterDB(\"local\");\n"
-"if (server) {\n"
-"s = connect(server+\"/local\");\n"
-"}\n"
-"s.getMongo().setSlaveOk();\n"
-"\n"
-"return s.oplog.rs.find().sort({$natural : -1}).limit(1).next();\n"
-"};\n"
-"\n"
-"\n"
-"help = shellHelper.help = function (x) {\n"
-"if (x == \"mr\") {\n"
-"print(\"\\nSee also http://www.mongodb.org/display/DOCS/MapReduce\");\n"
-"print(\"\\nfunction mapf() {\");\n"
-"print(\" // 'this' holds current document to inspect\");\n"
-"print(\" emit(key, value);\");\n"
-"print(\"}\");\n"
-"print(\"\\nfunction reducef(key,value_array) {\");\n"
-"print(\" return reduced_value;\");\n"
-"print(\"}\");\n"
-"print(\"\\ndb.mycollection.mapReduce(mapf, reducef[, options])\");\n"
-"print(\"\\noptions\");\n"
-"print(\"{[query : <query filter object>]\");\n"
-"print(\" [, sort : <sort the query. useful for optimization>]\");\n"
-"print(\" [, limit : <number of objects to return from collection>]\");\n"
-"print(\" [, out : <output-collection name>]\");\n"
-"print(\" [, keeptemp: <true|false>]\");\n"
-"print(\" [, finalize : <finalizefunction>]\");\n"
-"print(\" [, scope : <object where fields go into javascript global scope >]\");\n"
-"print(\" [, verbose : true]}\\n\");\n"
-"return;\n"
-"} else if (x == \"connect\") {\n"
-"print(\"\\nNormally one specifies the server on the mongo shell command line. Run mongo --help to see those options.\");\n"
-"print(\"Additional connections may be opened:\\n\");\n"
-"print(\" var x = new Mongo('host[:port]');\");\n"
-"print(\" var mydb = x.getDB('mydb');\");\n"
-"print(\" or\");\n"
-"print(\" var mydb = connect('host[:port]/mydb');\");\n"
-"print(\"\\nNote: the REPL prompt only auto-reports getLastError() for the shell command line connection.\\n\");\n"
-"return;\n"
-"}\n"
-"else if (x == \"keys\") {\n"
-"print(\"Tab completion and command history is available at the command prompt.\\n\");\n"
-"print(\"Some emacs keystrokes are available too:\");\n"
-"print(\" Ctrl-A start of line\");\n"
-"print(\" Ctrl-E end of line\");\n"
-"print(\" Ctrl-K del to end of line\");\n"
-"print(\"\\nMulti-line commands\");\n"
-"print(\"You can enter a multi line javascript expression. If parens, braces, etc. are not closed, you will see a new line \");\n"
-"print(\"beginning with '...' characters. Type the rest of your expression. Press Ctrl-C to abort the data entry if you\");\n"
-"print(\"get stuck.\\n\");\n"
-"}\n"
-"else if (x == \"misc\") {\n"
-"print(\"\\tb = new BinData(subtype,base64str) create a BSON BinData value\");\n"
-"print(\"\\tb.subtype() the BinData subtype (0..255)\");\n"
-"print(\"\\tb.length() length of the BinData data in bytes\");\n"
-"print(\"\\tb.hex() the data as a hex encoded string\");\n"
-"print(\"\\tb.base64() the data as a base 64 encoded string\");\n"
-"print(\"\\tb.toString()\");\n"
-"print();\n"
-"print(\"\\tb = HexData(subtype,hexstr) create a BSON BinData value from a hex string\");\n"
-"print(\"\\tb = UUID(hexstr) create a BSON BinData value of UUID subtype\");\n"
-"print(\"\\tb = MD5(hexstr) create a BSON BinData value of MD5 subtype\");\n"
-"print();\n"
-"print(\"\\to = new ObjectId() create a new ObjectId\");\n"
-"print(\"\\to.getTimestamp() return timestamp derived from first 32 bits of the OID\");\n"
-"print(\"\\to.isObjectId()\");\n"
-"print(\"\\to.toString()\");\n"
-"print(\"\\to.equals(otherid)\");\n"
-"return;\n"
-"}\n"
-"else if (x == \"admin\") {\n"
-"print(\"\\tls([path]) list files\");\n"
-"print(\"\\tpwd() returns current directory\");\n"
-"print(\"\\tlistFiles([path]) returns file list\");\n"
-"print(\"\\thostname() returns name of this host\");\n"
-"print(\"\\tcat(fname) returns contents of text file as a string\");\n"
-"print(\"\\tremoveFile(f) delete a file or directory\");\n"
-"print(\"\\tload(jsfilename) load and execute a .js file\");\n"
-"print(\"\\trun(program[, args...]) spawn a program and wait for its completion\");\n"
-"print(\"\\trunProgram(program[, args...]) same as run(), above\");\n"
-"print(\"\\tsleep(m) sleep m milliseconds\");\n"
-"print(\"\\tgetMemInfo() diagnostic\");\n"
-"return;\n"
-"}\n"
-"else if (x == \"test\") {\n"
-"print(\"\\tstartMongodEmpty(args) DELETES DATA DIR and then starts mongod\");\n"
-"print(\"\\t returns a connection to the new server\");\n"
-"print(\"\\tstartMongodTest(port,dir,options)\");\n"
-"print(\"\\t DELETES DATA DIR\");\n"
-"print(\"\\t automatically picks port #s starting at 27000 and increasing\");\n"
-"print(\"\\t or you can specify the port as the first arg\");\n"
-"print(\"\\t dir is /data/db/<port>/ if not specified as the 2nd arg\");\n"
-"print(\"\\t returns a connection to the new server\");\n"
-"print(\"\\tresetDbpath(dirpathstr) deletes everything under the dir specified including subdirs\");\n"
-"print(\"\\tstopMongoProgram(port[, signal])\");\n"
-"return;\n"
-"}\n"
-"else if (x == \"\") {\n"
-"print(\"\\t\" + \"db.help() help on db methods\");\n"
-"print(\"\\t\" + \"db.mycoll.help() help on collection methods\");\n"
-"print(\"\\t\" + \"rs.help() help on replica set methods\");\n"
-"print(\"\\t\" + \"help admin administrative help\");\n"
-"print(\"\\t\" + \"help connect connecting to a db help\");\n"
-"print(\"\\t\" + \"help keys key shortcuts\");\n"
-"print(\"\\t\" + \"help misc misc things to know\");\n"
-"print(\"\\t\" + \"help mr mapreduce\");\n"
-"print();\n"
-"print(\"\\t\" + \"show dbs show database names\");\n"
-"print(\"\\t\" + \"show collections show collections in current database\");\n"
-"print(\"\\t\" + \"show users show users in current database\");\n"
-"print(\"\\t\" + \"show profile show most recent system.profile entries with time >= 1ms\");\n"
-"print(\"\\t\" + \"show logs show the accessible logger names\");\n"
-"print(\"\\t\" + \"show log [name] prints out the last segment of log in memory, 'global' is default\");\n"
-"print(\"\\t\" + \"use <db_name> set current database\");\n"
-"print(\"\\t\" + \"db.foo.find() list objects in collection foo\");\n"
-"print(\"\\t\" + \"db.foo.find( { a : 1 } ) list objects in foo where a == 1\");\n"
-"print(\"\\t\" + \"it result of the last line evaluated; use to further iterate\");\n"
-"print(\"\\t\" + \"DBQuery.shellBatchSize = x set default number of items to display on shell\");\n"
-"print(\"\\t\" + \"exit quit the mongo shell\");\n"
-"}\n"
-"else\n"
-"print(\"unknown help option\");\n"
-"}\n"
-;
-extern const JSFile utils;
-const JSFile utils = { "shell/utils.js" , _jscode_raw_utils };
-const StringData _jscode_raw_utils_sh =
-"sh = function() { return \"try sh.help();\" }\n"
-"\n"
-"\n"
-"sh._checkMongos = function() {\n"
-"var x = db.runCommand( \"ismaster\" );\n"
-"if ( x.msg != \"isdbgrid\" )\n"
-"throw \"not connected to a mongos\"\n"
-"}\n"
-"\n"
-"sh._checkFullName = function( fullName ) {\n"
-"assert( fullName , \"neeed a full name\" )\n"
-"assert( fullName.indexOf( \".\" ) > 0 , \"name needs to be fully qualified <db>.<collection>'\" )\n"
-"}\n"
-"\n"
-"sh._adminCommand = function( cmd , skipCheck ) {\n"
-"if ( ! skipCheck ) sh._checkMongos();\n"
-"var res = db.getSisterDB( \"admin\" ).runCommand( cmd );\n"
-"\n"
-"if ( res == null || ! res.ok ) {\n"
-"print( \"command failed: \" + tojson( res ) )\n"
-"}\n"
-"\n"
-"return res;\n"
-"}\n"
-"\n"
-"\n"
-"sh._dataFormat = function( bytes ){\n"
-"if( bytes < 1024 ) return Math.floor( bytes ) + \"b\"\n"
-"if( bytes < 1024 * 1024 ) return Math.floor( bytes / 1024 ) + \"kb\"\n"
-"if( bytes < 1024 * 1024 * 1024 ) return Math.floor( ( Math.floor( bytes / 1024 ) / 1024 ) * 100 ) / 100 + \"Mb\"\n"
-"return Math.floor( ( Math.floor( bytes / ( 1024 * 1024 ) ) / 1024 ) * 100 ) / 100 + \"Gb\"\n"
-"}\n"
-"\n"
-"sh._collRE = function( coll ){\n"
-"return RegExp( \"^\" + (coll + \"\").replace(/\\./g, \"\\\\.\") + \"-.*\" )\n"
-"}\n"
-"\n"
-"sh._pchunk = function( chunk ){\n"
-"return \"[\" + tojson( chunk.min ) + \" -> \" + tojson( chunk.max ) + \"]\"\n"
-"}\n"
-"\n"
-"sh.help = function() {\n"
-"print( \"\\tsh.addShard( host ) server:port OR setname/server:port\" )\n"
-"print( \"\\tsh.enableSharding(dbname) enables sharding on the database dbname\" )\n"
-"print( \"\\tsh.shardCollection(fullName,key,unique) shards the collection\" );\n"
-"\n"
-"print( \"\\tsh.splitFind(fullName,find) splits the chunk that find is in at the median\" );\n"
-"print( \"\\tsh.splitAt(fullName,middle) splits the chunk that middle is in at middle\" );\n"
-"print( \"\\tsh.moveChunk(fullName,find,to) move the chunk where 'find' is to 'to' (name of shard)\");\n"
-"\n"
-"print( \"\\tsh.setBalancerState( <bool on or not> ) turns the balancer on or off true=on, false=off\" );\n"
-"print( \"\\tsh.getBalancerState() return true if on, off if not\" );\n"
-"print( \"\\tsh.isBalancerRunning() return true if the balancer is running on any mongos\" );\n"
-"\n"
-"print( \"\\tsh.status() prints a general overview of the cluster\" )\n"
-"}\n"
-"\n"
-"sh.status = function( verbose , configDB ) {\n"
-"// TODO: move the actual commadn here\n"
-"printShardingStatus( configDB , verbose );\n"
-"}\n"
-"\n"
-"sh.addShard = function( url ){\n"
-"sh._adminCommand( { addShard : url } , true )\n"
-"}\n"
-"\n"
-"sh.enableSharding = function( dbname ) {\n"
-"assert( dbname , \"need a valid dbname\" )\n"
-"sh._adminCommand( { enableSharding : dbname } )\n"
-"}\n"
-"\n"
-"sh.shardCollection = function( fullName , key , unique ) {\n"
-"sh._checkFullName( fullName )\n"
-"assert( key , \"need a key\" )\n"
-"assert( typeof( key ) == \"object\" , \"key needs to be an object\" )\n"
-"\n"
-"var cmd = { shardCollection : fullName , key : key }\n"
-"if ( unique )\n"
-"cmd.unique = true;\n"
-"\n"
-"sh._adminCommand( cmd )\n"
-"}\n"
-"\n"
-"\n"
-"sh.splitFind = function( fullName , find ) {\n"
-"sh._checkFullName( fullName )\n"
-"sh._adminCommand( { split : fullName , find : find } )\n"
-"}\n"
-"\n"
-"sh.splitAt = function( fullName , middle ) {\n"
-"sh._checkFullName( fullName )\n"
-"sh._adminCommand( { split : fullName , middle : middle } )\n"
-"}\n"
-"\n"
-"sh.moveChunk = function( fullName , find , to ) {\n"
-"sh._checkFullName( fullName );\n"
-"sh._adminCommand( { moveChunk : fullName , find : find , to : to } )\n"
-"}\n"
-"\n"
-"sh.setBalancerState = function( onOrNot ) {\n"
-"db.getSisterDB( \"config\" ).settings.update({ _id: \"balancer\" }, { $set : { stopped: onOrNot ? false : true } }, true );\n"
-"}\n"
-"\n"
-"sh.getBalancerState = function() {\n"
-"var x = db.getSisterDB( \"config\" ).settings.findOne({ _id: \"balancer\" } )\n"
-"if ( x == null )\n"
-"return true;\n"
-"return ! x.stopped;\n"
-"}\n"
-"\n"
-"sh.isBalancerRunning = function() {\n"
-"var x = db.getSisterDB( \"config\" ).locks.findOne( { _id : \"balancer\" } );\n"
-"return x.state > 0;\n"
-"}\n"
-;
-extern const JSFile utils_sh;
-const JSFile utils_sh = { "shell/utils_sh.js" , _jscode_raw_utils_sh };
-const StringData _jscode_raw_db =
-"// db.js\n"
-"\n"
-"if ( typeof DB == \"undefined\" ){\n"
-"DB = function( mongo , name ){\n"
-"this._mongo = mongo;\n"
-"this._name = name;\n"
-"}\n"
-"}\n"
-"\n"
-"DB.prototype.getMongo = function(){\n"
-"assert( this._mongo , \"why no mongo!\" );\n"
-"return this._mongo;\n"
-"}\n"
-"\n"
-"DB.prototype.getSiblingDB = function( name ){\n"
-"return this.getMongo().getDB( name );\n"
-"}\n"
-"\n"
-"DB.prototype.getSisterDB = DB.prototype.getSiblingDB;\n"
-"\n"
-"DB.prototype.getName = function(){\n"
-"return this._name;\n"
-"}\n"
-"\n"
-"DB.prototype.stats = function(scale){\n"
-"return this.runCommand( { dbstats : 1 , scale : scale } );\n"
-"}\n"
-"\n"
-"DB.prototype.getCollection = function( name ){\n"
-"return new DBCollection( this._mongo , this , name , this._name + \".\" + name );\n"
-"}\n"
-"\n"
-"DB.prototype.commandHelp = function( name ){\n"
-"var c = {};\n"
-"c[name] = 1;\n"
-"c.help = true;\n"
-"var res = this.runCommand( c );\n"
-"if ( ! res.ok )\n"
-"throw res.errmsg;\n"
-"return res.help;\n"
-"}\n"
-"\n"
-"DB.prototype.runCommand = function( obj ){\n"
-"if ( typeof( obj ) == \"string\" ){\n"
-"var n = {};\n"
-"n[obj] = 1;\n"
-"obj = n;\n"
-"}\n"
-"return this.getCollection( \"$cmd\" ).findOne( obj );\n"
-"}\n"
-"\n"
-"DB.prototype._dbCommand = DB.prototype.runCommand;\n"
-"\n"
-"DB.prototype.adminCommand = function( obj ){\n"
-"if ( this._name == \"admin\" )\n"
-"return this.runCommand( obj );\n"
-"return this.getSiblingDB( \"admin\" ).runCommand( obj );\n"
-"}\n"
-"\n"
-"DB.prototype._adminCommand = DB.prototype.adminCommand; // alias old name\n"
-"\n"
-"DB.prototype.addUser = function( username , pass, readOnly ){\n"
-"if ( pass == null || pass.length == 0 )\n"
-"throw \"password can't be empty\";\n"
-"\n"
-"readOnly = readOnly || false;\n"
-"var c = this.getCollection( \"system.users\" );\n"
-"\n"
-"var u = c.findOne( { user : username } ) || { user : username };\n"
-"u.readOnly = readOnly;\n"
-"u.pwd = hex_md5( username + \":mongo:\" + pass );\n"
-"\n"
-"c.save( u );\n"
-"var le = this.getLastErrorObj();\n"
-"printjson( le )\n"
-"if ( le.err )\n"
-"throw \"couldn't add user: \" + le.err\n"
-"print( tojson( u ) );\n"
-"}\n"
-"\n"
-"DB.prototype.logout = function(){\n"
-"return this.runCommand({logout : 1});\n"
-"}\n"
-"\n"
-"DB.prototype.removeUser = function( username ){\n"
-"this.getCollection( \"system.users\" ).remove( { user : username } );\n"
-"}\n"
-"\n"
-"DB.prototype.__pwHash = function( nonce, username, pass ) {\n"
-"return hex_md5( nonce + username + hex_md5( username + \":mongo:\" + pass ) );\n"
-"}\n"
-"\n"
-"DB.prototype.auth = function( username , pass ){\n"
-"var n = this.runCommand( { getnonce : 1 } );\n"
-"\n"
-"var a = this.runCommand(\n"
-"{\n"
-"authenticate : 1 ,\n"
-"user : username ,\n"
-"nonce : n.nonce ,\n"
-"key : this.__pwHash( n.nonce, username, pass )\n"
-"}\n"
-");\n"
-"\n"
-"return a.ok;\n"
-"}\n"
-"\n"
-"/**\n"
-"Create a new collection in the database. Normally, collection creation is automatic. You would\n"
-"use this function if you wish to specify special options on creation.\n"
-"\n"
-"If the collection already exists, no action occurs.\n"
-"\n"
-"<p>Options:</p>\n"
-"<ul>\n"
-"<li>\n"
-"size: desired initial extent size for the collection. Must be <= 1000000000.\n"
-"for fixed size (capped) collections, this size is the total/max size of the\n"
-"collection.\n"
-"</li>\n"
-"<li>\n"
-"capped: if true, this is a capped collection (where old data rolls out).\n"
-"</li>\n"
-"<li> max: maximum number of objects if capped (optional).</li>\n"
-"</ul>\n"
-"\n"
-"<p>Example: </p>\n"
-"\n"
-"<code>db.createCollection(\"movies\", { size: 10 * 1024 * 1024, capped:true } );</code>\n"
-"\n"
-"* @param {String} name Name of new collection to create\n"
-"* @param {Object} options Object with options for call. Options are listed above.\n"
-"* @return SOMETHING_FIXME\n"
-"*/\n"
-"DB.prototype.createCollection = function(name, opt) {\n"
-"var options = opt || {};\n"
-"var cmd = { create: name, capped: options.capped, size: options.size, max: options.max };\n"
-"if (options.autoIndexId != undefined)\n"
-"cmd.autoIndexId = options.autoIndexId;\n"
-"var res = this._dbCommand(cmd);\n"
-"return res;\n"
-"}\n"
-"\n"
-"/**\n"
-"* @deprecated use getProfilingStatus\n"
-"* Returns the current profiling level of this database\n"
-"* @return SOMETHING_FIXME or null on error\n"
-"*/\n"
-"DB.prototype.getProfilingLevel = function() {\n"
-"var res = this._dbCommand( { profile: -1 } );\n"
-"return res ? res.was : null;\n"
-"}\n"
-"\n"
-"/**\n"
-"* @return the current profiling status\n"
-"* example { was : 0, slowms : 100 }\n"
-"* @return SOMETHING_FIXME or null on error\n"
-"*/\n"
-"DB.prototype.getProfilingStatus = function() {\n"
-"var res = this._dbCommand( { profile: -1 } );\n"
-"if ( ! res.ok )\n"
-"throw \"profile command failed: \" + tojson( res );\n"
-"delete res.ok\n"
-"return res;\n"
-"}\n"
-"\n"
-"\n"
-"/**\n"
-"Erase the entire database. (!)\n"
-"\n"
-"* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n"
-"*/\n"
-"DB.prototype.dropDatabase = function() {\n"
-"if ( arguments.length )\n"
-"throw \"dropDatabase doesn't take arguments\";\n"
-"return this._dbCommand( { dropDatabase: 1 } );\n"
-"}\n"
-"\n"
-"/**\n"
-"* Shuts down the database. Must be run while using the admin database.\n"
-"* @param opts Options for shutdown. Possible options are:\n"
-"* - force: (boolean) if the server should shut down, even if there is no\n"
-"* up-to-date slave\n"
-"* - timeoutSecs: (number) the server will continue checking over timeoutSecs\n"
-"* if any other servers have caught up enough for it to shut down.\n"
-"*/\n"
-"DB.prototype.shutdownServer = function(opts) {\n"
-"if( \"admin\" != this._name ){\n"
-"return \"shutdown command only works with the admin database; try 'use admin'\";\n"
-"}\n"
-"\n"
-"cmd = {\"shutdown\" : 1};\n"
-"opts = opts || {};\n"
-"for (var o in opts) {\n"
-"cmd[o] = opts[o];\n"
-"}\n"
-"\n"
-"try {\n"
-"var res = this.runCommand(cmd);\n"
-"if( res )\n"
-"throw \"shutdownServer failed: \" + res.errmsg;\n"
-"throw \"shutdownServer failed\";\n"
-"}\n"
-"catch ( e ){\n"
-"assert( tojson( e ).indexOf( \"error doing query: failed\" ) >= 0 , \"unexpected error: \" + tojson( e ) );\n"
-"print( \"server should be down...\" );\n"
-"}\n"
-"}\n"
-"\n"
-"/**\n"
-"Clone database on another server to here.\n"
-"<p>\n"
-"Generally, you should dropDatabase() first as otherwise the cloned information will MERGE\n"
-"into whatever data is already present in this database. (That is however a valid way to use\n"
-"clone if you are trying to do something intentionally, such as union three non-overlapping\n"
-"databases into one.)\n"
-"<p>\n"
-"This is a low level administrative function will is not typically used.\n"
-"\n"
-"* @param {String} from Where to clone from (dbhostname[:port]). May not be this database\n"
-"(self) as you cannot clone to yourself.\n"
-"* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n"
-"* See also: db.copyDatabase()\n"
-"*/\n"
-"DB.prototype.cloneDatabase = function(from) {\n"
-"assert( isString(from) && from.length );\n"
-"//this.resetIndexCache();\n"
-"return this._dbCommand( { clone: from } );\n"
-"}\n"
-"\n"
-"\n"
-"/**\n"
-"Clone collection on another server to here.\n"
-"<p>\n"
-"Generally, you should drop() first as otherwise the cloned information will MERGE\n"
-"into whatever data is already present in this collection. (That is however a valid way to use\n"
-"clone if you are trying to do something intentionally, such as union three non-overlapping\n"
-"collections into one.)\n"
-"<p>\n"
-"This is a low level administrative function is not typically used.\n"
-"\n"
-"* @param {String} from mongod instance from which to clnoe (dbhostname:port). May\n"
-"not be this mongod instance, as clone from self is not allowed.\n"
-"* @param {String} collection name of collection to clone.\n"
-"* @param {Object} query query specifying which elements of collection are to be cloned.\n"
-"* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n"
-"* See also: db.cloneDatabase()\n"
-"*/\n"
-"DB.prototype.cloneCollection = function(from, collection, query) {\n"
-"assert( isString(from) && from.length );\n"
-"assert( isString(collection) && collection.length );\n"
-"collection = this._name + \".\" + collection;\n"
-"query = query || {};\n"
-"//this.resetIndexCache();\n"
-"return this._dbCommand( { cloneCollection:collection, from:from, query:query } );\n"
-"}\n"
-"\n"
-"\n"
-"/**\n"
-"Copy database from one server or name to another server or name.\n"
-"\n"
-"Generally, you should dropDatabase() first as otherwise the copied information will MERGE\n"
-"into whatever data is already present in this database (and you will get duplicate objects\n"
-"in collections potentially.)\n"
-"\n"
-"For security reasons this function only works when executed on the \"admin\" db. However,\n"
-"if you have access to said db, you can copy any database from one place to another.\n"
-"\n"
-"This method provides a way to \"rename\" a database by copying it to a new db name and\n"
-"location. Additionally, it effectively provides a repair facility.\n"
-"\n"
-"* @param {String} fromdb database name from which to copy.\n"
-"* @param {String} todb database name to copy to.\n"
-"* @param {String} fromhost hostname of the database (and optionally, \":port\") from which to\n"
-"copy the data. default if unspecified is to copy from self.\n"
-"* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n"
-"* See also: db.clone()\n"
-"*/\n"
-"DB.prototype.copyDatabase = function(fromdb, todb, fromhost, username, password) {\n"
-"assert( isString(fromdb) && fromdb.length );\n"
-"assert( isString(todb) && todb.length );\n"
-"fromhost = fromhost || \"\";\n"
-"if ( username && password ) {\n"
-"var n = this._adminCommand( { copydbgetnonce : 1, fromhost:fromhost } );\n"
-"return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb, username:username, nonce:n.nonce, key:this.__pwHash( n.nonce, username, password ) } );\n"
-"} else {\n"
-"return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb } );\n"
-"}\n"
-"}\n"
-"\n"
-"/**\n"
-"Repair database.\n"
-"\n"
-"* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n"
-"*/\n"
-"DB.prototype.repairDatabase = function() {\n"
-"return this._dbCommand( { repairDatabase: 1 } );\n"
-"}\n"
-"\n"
-"\n"
-"DB.prototype.help = function() {\n"
-"print(\"DB methods:\");\n"
-"print(\"\\tdb.addUser(username, password[, readOnly=false])\");\n"
-"print(\"\\tdb.auth(username, password)\");\n"
-"print(\"\\tdb.cloneDatabase(fromhost)\");\n"
-"print(\"\\tdb.commandHelp(name) returns the help for the command\");\n"
-"print(\"\\tdb.copyDatabase(fromdb, todb, fromhost)\");\n"
-"print(\"\\tdb.createCollection(name, { size : ..., capped : ..., max : ... } )\");\n"
-"print(\"\\tdb.currentOp() displays the current operation in the db\");\n"
-"print(\"\\tdb.dropDatabase()\");\n"
-"print(\"\\tdb.eval(func, args) run code server-side\");\n"
-"print(\"\\tdb.getCollection(cname) same as db['cname'] or db.cname\");\n"
-"print(\"\\tdb.getCollectionNames()\");\n"
-"print(\"\\tdb.getLastError() - just returns the err msg string\");\n"
-"print(\"\\tdb.getLastErrorObj() - return full status object\");\n"
-"print(\"\\tdb.getMongo() get the server connection object\");\n"
-"print(\"\\tdb.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair\");\n"
-"print(\"\\tdb.getName()\");\n"
-"print(\"\\tdb.getPrevError()\");\n"
-"print(\"\\tdb.getProfilingLevel() - deprecated\");\n"
-"print(\"\\tdb.getProfilingStatus() - returns if profiling is on and slow threshold \");\n"
-"print(\"\\tdb.getReplicationInfo()\");\n"
-"print(\"\\tdb.getSiblingDB(name) get the db at the same server as this one\");\n"
-"print(\"\\tdb.isMaster() check replica primary status\");\n"
-"print(\"\\tdb.killOp(opid) kills the current operation in the db\");\n"
-"print(\"\\tdb.listCommands() lists all the db commands\");\n"
-"print(\"\\tdb.logout()\");\n"
-"print(\"\\tdb.printCollectionStats()\");\n"
-"print(\"\\tdb.printReplicationInfo()\");\n"
-"print(\"\\tdb.printSlaveReplicationInfo()\");\n"
-"print(\"\\tdb.printShardingStatus()\");\n"
-"print(\"\\tdb.removeUser(username)\");\n"
-"print(\"\\tdb.repairDatabase()\");\n"
-"print(\"\\tdb.resetError()\");\n"
-"print(\"\\tdb.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }\");\n"
-"print(\"\\tdb.serverStatus()\");\n"
-"print(\"\\tdb.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all\");\n"
-"print(\"\\tdb.shutdownServer()\");\n"
-"print(\"\\tdb.stats()\");\n"
-"print(\"\\tdb.version() current version of the server\");\n"
-"print(\"\\tdb.getMongo().setSlaveOk() allow queries on a replication slave server\");\n"
-"print(\"\\tdb.fsyncLock() flush data to disk and lock server for backups\");\n"
-"print(\"\\tdb.fsyncUnock() unlocks server following a db.fsyncLock()\");\n"
-"\n"
-"return __magicNoPrint;\n"
-"}\n"
-"\n"
-"DB.prototype.printCollectionStats = function(){\n"
-"var mydb = this;\n"
-"this.getCollectionNames().forEach(\n"
-"function(z){\n"
-"print( z );\n"
-"printjson( mydb.getCollection(z).stats() );\n"
-"print( \"---\" );\n"
-"}\n"
-");\n"
-"}\n"
-"\n"
-"/**\n"
-"* <p> Set profiling level for your db. Profiling gathers stats on query performance. </p>\n"
-"*\n"
-"* <p>Default is off, and resets to off on a database restart -- so if you want it on,\n"
-"* turn it on periodically. </p>\n"
-"*\n"
-"* <p>Levels :</p>\n"
-"* <ul>\n"
-"* <li>0=off</li>\n"
-"* <li>1=log very slow operations; optional argument slowms specifies slowness threshold</li>\n"
-"* <li>2=log all</li>\n"
-"* @param {String} level Desired level of profiling\n"
-"* @param {String} slowms For slow logging, query duration that counts as slow (default 100ms)\n"
-"* @return SOMETHING_FIXME or null on error\n"
-"*/\n"
-"DB.prototype.setProfilingLevel = function(level,slowms) {\n"
-"\n"
-"if (level < 0 || level > 2) {\n"
-"throw { dbSetProfilingException : \"input level \" + level + \" is out of range [0..2]\" };\n"
-"}\n"
-"\n"
-"var cmd = { profile: level };\n"
-"if ( slowms )\n"
-"cmd[\"slowms\"] = slowms;\n"
-"return this._dbCommand( cmd );\n"
-"}\n"
-"\n"
-"\n"
-"/**\n"
-"* <p> Evaluate a js expression at the database server.</p>\n"
-"*\n"
-"* <p>Useful if you need to touch a lot of data lightly; in such a scenario\n"
-"* the network transfer of the data could be a bottleneck. A good example\n"
-"* is \"select count(*)\" -- can be done server side via this mechanism.\n"
-"* </p>\n"
-"*\n"
-"* <p>\n"
-"* If the eval fails, an exception is thrown of the form:\n"
-"* </p>\n"
-"* <code>{ dbEvalException: { retval: functionReturnValue, ok: num [, errno: num] [, errmsg: str] } }</code>\n"
-"*\n"
-"* <p>Example: </p>\n"
-"* <code>print( \"mycount: \" + db.eval( function(){db.mycoll.find({},{_id:ObjId()}).length();} );</code>\n"
-"*\n"
-"* @param {Function} jsfunction Javascript function to run on server. Note this it not a closure, but rather just \"code\".\n"
-"* @return result of your function, or null if error\n"
-"*\n"
-"*/\n"
-"DB.prototype.eval = function(jsfunction) {\n"
-"var cmd = { $eval : jsfunction };\n"
-"if ( arguments.length > 1 ) {\n"
-"cmd.args = argumentsToArray( arguments ).slice(1);\n"
-"}\n"
-"\n"
-"var res = this._dbCommand( cmd );\n"
-"\n"
-"if (!res.ok)\n"
-"throw tojson( res );\n"
-"\n"
-"return res.retval;\n"
-"}\n"
-"\n"
-"DB.prototype.dbEval = DB.prototype.eval;\n"
-"\n"
-"\n"
-"/**\n"
-"*\n"
-"* <p>\n"
-"* Similar to SQL group by. For example: </p>\n"
-"*\n"
-"* <code>select a,b,sum(c) csum from coll where active=1 group by a,b</code>\n"
-"*\n"
-"* <p>\n"
-"* corresponds to the following in 10gen:\n"
-"* </p>\n"
-"*\n"
-"* <code>\n"
-"db.group(\n"
-"{\n"
-"ns: \"coll\",\n"
-"key: { a:true, b:true },\n"
-"// keyf: ...,\n"
-"cond: { active:1 },\n"
-"reduce: function(obj,prev) { prev.csum += obj.c; } ,\n"
-"initial: { csum: 0 }\n"
-"});\n"
-"</code>\n"
-"*\n"
-"*\n"
-"* <p>\n"
-"* An array of grouped items is returned. The array must fit in RAM, thus this function is not\n"
-"* suitable when the return set is extremely large.\n"
-"* </p>\n"
-"* <p>\n"
-"* To order the grouped data, simply sort it client side upon return.\n"
-"* <p>\n"
-"Defaults\n"
-"cond may be null if you want to run against all rows in the collection\n"
-"keyf is a function which takes an object and returns the desired key. set either key or keyf (not both).\n"
-"* </p>\n"
-"*/\n"
-"DB.prototype.groupeval = function(parmsObj) {\n"
-"\n"
-"var groupFunction = function() {\n"
-"var parms = args[0];\n"
-"var c = db[parms.ns].find(parms.cond||{});\n"
-"var map = new Map();\n"
-"var pks = parms.key ? Object.keySet( parms.key ) : null;\n"
-"var pkl = pks ? pks.length : 0;\n"
-"var key = {};\n"
-"\n"
-"while( c.hasNext() ) {\n"
-"var obj = c.next();\n"
-"if ( pks ) {\n"
-"for( var i=0; i<pkl; i++ ){\n"
-"var k = pks[i];\n"
-"key[k] = obj[k];\n"
-"}\n"
-"}\n"
-"else {\n"
-"key = parms.$keyf(obj);\n"
-"}\n"
-"\n"
-"var aggObj = map.get(key);\n"
-"if( aggObj == null ) {\n"
-"var newObj = Object.extend({}, key); // clone\n"
-"aggObj = Object.extend(newObj, parms.initial)\n"
-"map.put( key , aggObj );\n"
-"}\n"
-"parms.$reduce(obj, aggObj);\n"
-"}\n"
-"\n"
-"return map.values();\n"
-"}\n"
-"\n"
-"return this.eval(groupFunction, this._groupFixParms( parmsObj ));\n"
-"}\n"
-"\n"
-"DB.prototype.groupcmd = function( parmsObj ){\n"
-"var ret = this.runCommand( { \"group\" : this._groupFixParms( parmsObj ) } );\n"
-"if ( ! ret.ok ){\n"
-"throw \"group command failed: \" + tojson( ret );\n"
-"}\n"
-"return ret.retval;\n"
-"}\n"
-"\n"
-"DB.prototype.group = DB.prototype.groupcmd;\n"
-"\n"
-"DB.prototype._groupFixParms = function( parmsObj ){\n"
-"var parms = Object.extend({}, parmsObj);\n"
-"\n"
-"if( parms.reduce ) {\n"
-"parms.$reduce = parms.reduce; // must have $ to pass to db\n"
-"delete parms.reduce;\n"
-"}\n"
-"\n"
-"if( parms.keyf ) {\n"
-"parms.$keyf = parms.keyf;\n"
-"delete parms.keyf;\n"
-"}\n"
-"\n"
-"return parms;\n"
-"}\n"
-"\n"
-"DB.prototype.resetError = function(){\n"
-"return this.runCommand( { reseterror : 1 } );\n"
-"}\n"
-"\n"
-"DB.prototype.forceError = function(){\n"
-"return this.runCommand( { forceerror : 1 } );\n"
-"}\n"
-"\n"
-"DB.prototype.getLastError = function( w , wtimeout ){\n"
-"var res = this.getLastErrorObj( w , wtimeout );\n"
-"if ( ! res.ok )\n"
-"throw \"getlasterror failed: \" + tojson( res );\n"
-"return res.err;\n"
-"}\n"
-"DB.prototype.getLastErrorObj = function( w , wtimeout ){\n"
-"var cmd = { getlasterror : 1 };\n"
-"if ( w ){\n"
-"cmd.w = w;\n"
-"if ( wtimeout )\n"
-"cmd.wtimeout = wtimeout;\n"
-"}\n"
-"var res = this.runCommand( cmd );\n"
-"\n"
-"if ( ! res.ok )\n"
-"throw \"getlasterror failed: \" + tojson( res );\n"
-"return res;\n"
-"}\n"
-"DB.prototype.getLastErrorCmd = DB.prototype.getLastErrorObj;\n"
-"\n"
-"\n"
-"/* Return the last error which has occurred, even if not the very last error.\n"
-"\n"
-"Returns:\n"
-"{ err : <error message>, nPrev : <how_many_ops_back_occurred>, ok : 1 }\n"
-"\n"
-"result.err will be null if no error has occurred.\n"
-"*/\n"
-"DB.prototype.getPrevError = function(){\n"
-"return this.runCommand( { getpreverror : 1 } );\n"
-"}\n"
-"\n"
-"DB.prototype.getCollectionNames = function(){\n"
-"var all = [];\n"
-"\n"
-"var nsLength = this._name.length + 1;\n"
-"\n"
-"var c = this.getCollection( \"system.namespaces\" ).find();\n"
-"while ( c.hasNext() ){\n"
-"var name = c.next().name;\n"
-"\n"
-"if ( name.indexOf( \"$\" ) >= 0 && name.indexOf( \".oplog.$\" ) < 0 )\n"
-"continue;\n"
-"\n"
-"all.push( name.substring( nsLength ) );\n"
-"}\n"
-"\n"
-"return all.sort();\n"
-"}\n"
-"\n"
-"DB.prototype.tojson = function(){\n"
-"return this._name;\n"
-"}\n"
-"\n"
-"DB.prototype.toString = function(){\n"
-"return this._name;\n"
-"}\n"
-"\n"
-"DB.prototype.isMaster = function () { return this.runCommand(\"isMaster\"); }\n"
-"\n"
-"DB.prototype.currentOp = function( arg ){\n"
-"var q = {}\n"
-"if ( arg ) {\n"
-"if ( typeof( arg ) == \"object\" )\n"
-"Object.extend( q , arg );\n"
-"else if ( arg )\n"
-"q[\"$all\"] = true;\n"
-"}\n"
-"return db.$cmd.sys.inprog.findOne( q );\n"
-"}\n"
-"DB.prototype.currentOP = DB.prototype.currentOp;\n"
-"\n"
-"DB.prototype.killOp = function(op) {\n"
-"if( !op )\n"
-"throw \"no opNum to kill specified\";\n"
-"return db.$cmd.sys.killop.findOne({'op':op});\n"
-"}\n"
-"DB.prototype.killOP = DB.prototype.killOp;\n"
-"\n"
-"DB.tsToSeconds = function(x){\n"
-"if ( x.t && x.i )\n"
-"return x.t / 1000;\n"
-"return x / 4294967296; // low 32 bits are ordinal #s within a second\n"
-"}\n"
-"\n"
-"/**\n"
-"Get a replication log information summary.\n"
-"<p>\n"
-"This command is for the database/cloud administer and not applicable to most databases.\n"
-"It is only used with the local database. One might invoke from the JS shell:\n"
-"<pre>\n"
-"use local\n"
-"db.getReplicationInfo();\n"
-"</pre>\n"
-"It is assumed that this database is a replication master -- the information returned is\n"
-"about the operation log stored at local.oplog.$main on the replication master. (It also\n"
-"works on a machine in a replica pair: for replica pairs, both machines are \"masters\" from\n"
-"an internal database perspective.\n"
-"<p>\n"
-"* @return Object timeSpan: time span of the oplog from start to end if slave is more out\n"
-"* of date than that, it can't recover without a complete resync\n"
-"*/\n"
-"DB.prototype.getReplicationInfo = function() {\n"
-"var db = this.getSiblingDB(\"local\");\n"
-"\n"
-"var result = { };\n"
-"var oplog;\n"
-"if (db.system.namespaces.findOne({name:\"local.oplog.rs\"}) != null) {\n"
-"oplog = 'oplog.rs';\n"
-"}\n"
-"else if (db.system.namespaces.findOne({name:\"local.oplog.$main\"}) != null) {\n"
-"oplog = 'oplog.$main';\n"
-"}\n"
-"else {\n"
-"result.errmsg = \"neither master/slave nor replica set replication detected\";\n"
-"return result;\n"
-"}\n"
-"\n"
-"var ol_entry = db.system.namespaces.findOne({name:\"local.\"+oplog});\n"
-"if( ol_entry && ol_entry.options ) {\n"
-"result.logSizeMB = ol_entry.options.size / ( 1024 * 1024 );\n"
-"} else {\n"
-"result.errmsg = \"local.\"+oplog+\", or its options, not found in system.namespaces collection\";\n"
-"return result;\n"
-"}\n"
-"ol = db.getCollection(oplog);\n"
-"\n"
-"result.usedMB = ol.stats().size / ( 1024 * 1024 );\n"
-"result.usedMB = Math.ceil( result.usedMB * 100 ) / 100;\n"
-"\n"
-"var firstc = ol.find().sort({$natural:1}).limit(1);\n"
-"var lastc = ol.find().sort({$natural:-1}).limit(1);\n"
-"if( !firstc.hasNext() || !lastc.hasNext() ) {\n"
-"result.errmsg = \"objects not found in local.oplog.$main -- is this a new and empty db instance?\";\n"
-"result.oplogMainRowCount = ol.count();\n"
-"return result;\n"
-"}\n"
-"\n"
-"var first = firstc.next();\n"
-"var last = lastc.next();\n"
-"{\n"
-"var tfirst = first.ts;\n"
-"var tlast = last.ts;\n"
-"\n"
-"if( tfirst && tlast ) {\n"
-"tfirst = DB.tsToSeconds( tfirst );\n"
-"tlast = DB.tsToSeconds( tlast );\n"
-"result.timeDiff = tlast - tfirst;\n"
-"result.timeDiffHours = Math.round(result.timeDiff / 36)/100;\n"
-"result.tFirst = (new Date(tfirst*1000)).toString();\n"
-"result.tLast = (new Date(tlast*1000)).toString();\n"
-"result.now = Date();\n"
-"}\n"
-"else {\n"
-"result.errmsg = \"ts element not found in oplog objects\";\n"
-"}\n"
-"}\n"
-"\n"
-"return result;\n"
-"};\n"
-"\n"
-"DB.prototype.printReplicationInfo = function() {\n"
-"var result = this.getReplicationInfo();\n"
-"if( result.errmsg ) {\n"
-"if (!this.isMaster().ismaster) {\n"
-"print(\"this is a slave, printing slave replication info.\");\n"
-"this.printSlaveReplicationInfo();\n"
-"return;\n"
-"}\n"
-"print(tojson(result));\n"
-"return;\n"
-"}\n"
-"print(\"configured oplog size: \" + result.logSizeMB + \"MB\");\n"
-"print(\"log length start to end: \" + result.timeDiff + \"secs (\" + result.timeDiffHours + \"hrs)\");\n"
-"print(\"oplog first event time: \" + result.tFirst);\n"
-"print(\"oplog last event time: \" + result.tLast);\n"
-"print(\"now: \" + result.now);\n"
-"}\n"
-"\n"
-"DB.prototype.printSlaveReplicationInfo = function() {\n"
-"function getReplLag(st) {\n"
-"var now = new Date();\n"
-"print(\"\\t syncedTo: \" + st.toString() );\n"
-"var ago = (now-st)/1000;\n"
-"var hrs = Math.round(ago/36)/100;\n"
-"print(\"\\t\\t = \" + Math.round(ago) + \" secs ago (\" + hrs + \"hrs)\");\n"
-"};\n"
-"\n"
-"function g(x) {\n"
-"assert( x , \"how could this be null (printSlaveReplicationInfo gx)\" )\n"
-"print(\"source: \" + x.host);\n"
-"if ( x.syncedTo ){\n"
-"var st = new Date( DB.tsToSeconds( x.syncedTo ) * 1000 );\n"
-"getReplLag(st);\n"
-"}\n"
-"else {\n"
-"print( \"\\t doing initial sync\" );\n"
-"}\n"
-"};\n"
-"\n"
-"function r(x) {\n"
-"assert( x , \"how could this be null (printSlaveReplicationInfo rx)\" );\n"
-"if ( x.state == 1 ) {\n"
-"return;\n"
-"}\n"
-"\n"
-"print(\"source: \" + x.name);\n"
-"if ( x.optime ) {\n"
-"getReplLag(x.optimeDate);\n"
-"}\n"
-"else {\n"
-"print( \"\\t no replication info, yet. State: \" + x.stateStr );\n"
-"}\n"
-"};\n"
-"\n"
-"var L = this.getSiblingDB(\"local\");\n"
-"\n"
-"if (L.system.replset.count() != 0) {\n"
-"var status = this.adminCommand({'replSetGetStatus' : 1});\n"
-"status.members.forEach(r);\n"
-"}\n"
-"else if( L.sources.count() != 0 ) {\n"
-"L.sources.find().forEach(g);\n"
-"}\n"
-"else {\n"
-"print(\"local.sources is empty; is this db a --slave?\");\n"
-"return;\n"
-"}\n"
-"}\n"
-"\n"
-"DB.prototype.serverBuildInfo = function(){\n"
-"return this._adminCommand( \"buildinfo\" );\n"
-"}\n"
-"\n"
-"DB.prototype.serverStatus = function(){\n"
-"return this._adminCommand( \"serverStatus\" );\n"
-"}\n"
-"\n"
-"DB.prototype.serverCmdLineOpts = function(){\n"
-"return this._adminCommand( \"getCmdLineOpts\" );\n"
-"}\n"
-"\n"
-"DB.prototype.version = function(){\n"
-"return this.serverBuildInfo().version;\n"
-"}\n"
-"\n"
-"DB.prototype.serverBits = function(){\n"
-"return this.serverBuildInfo().bits;\n"
-"}\n"
-"\n"
-"DB.prototype.listCommands = function(){\n"
-"var x = this.runCommand( \"listCommands\" );\n"
-"for ( var name in x.commands ){\n"
-"var c = x.commands[name];\n"
-"\n"
-"var s = name + \": \";\n"
-"\n"
-"switch ( c.lockType ){\n"
-"case -1: s += \"read-lock\"; break;\n"
-"case 0: s += \"no-lock\"; break;\n"
-"case 1: s += \"write-lock\"; break;\n"
-"default: s += c.lockType;\n"
-"}\n"
-"\n"
-"if (c.adminOnly) s += \" adminOnly \";\n"
-"if (c.adminOnly) s += \" slaveOk \";\n"
-"\n"
-"s += \"\\n \";\n"
-"s += c.help.replace(/\\n/g, '\\n ');\n"
-"s += \"\\n\";\n"
-"\n"
-"print( s );\n"
-"}\n"
-"}\n"
-"\n"
-"DB.prototype.printShardingStatus = function( verbose ){\n"
-"printShardingStatus( this.getSiblingDB( \"config\" ) , verbose );\n"
-"}\n"
-"\n"
-"DB.prototype.fsyncLock = function() {\n"
-"return db.adminCommand({fsync:1, lock:true});\n"
-"}\n"
-"\n"
-"DB.prototype.fsyncUnlock = function() {\n"
-"return db.getSiblingDB(\"admin\").$cmd.sys.unlock.findOne()\n"
-"}\n"
-"\n"
-"DB.autocomplete = function(obj){\n"
-"var colls = obj.getCollectionNames();\n"
-"var ret=[];\n"
-"for (var i=0; i<colls.length; i++){\n"
-"if (colls[i].match(/^[a-zA-Z0-9_.\\$]+$/))\n"
-"ret.push(colls[i]);\n"
-"}\n"
-"return ret;\n"
-"}\n"
-;
-extern const JSFile db;
-const JSFile db = { "shell/db.js" , _jscode_raw_db };
-const StringData _jscode_raw_mongo =
-"// mongo.js\n"
-"\n"
-"// NOTE 'Mongo' may be defined here or in MongoJS.cpp. Add code to init, not to this constructor.\n"
-"if ( typeof Mongo == \"undefined\" ){\n"
-"Mongo = function( host ){\n"
-"this.init( host );\n"
-"}\n"
-"}\n"
-"\n"
-"if ( ! Mongo.prototype ){\n"
-"throw \"Mongo.prototype not defined\";\n"
-"}\n"
-"\n"
-"if ( ! Mongo.prototype.find )\n"
-"Mongo.prototype.find = function( ns , query , fields , limit , skip , batchSize , options ){ throw \"find not implemented\"; }\n"
-"if ( ! Mongo.prototype.insert )\n"
-"Mongo.prototype.insert = function( ns , obj ){ throw \"insert not implemented\"; }\n"
-"if ( ! Mongo.prototype.remove )\n"
-"Mongo.prototype.remove = function( ns , pattern ){ throw \"remove not implemented;\" }\n"
-"if ( ! Mongo.prototype.update )\n"
-"Mongo.prototype.update = function( ns , query , obj , upsert ){ throw \"update not implemented;\" }\n"
-"\n"
-"if ( typeof mongoInject == \"function\" ){\n"
-"mongoInject( Mongo.prototype );\n"
-"}\n"
-"\n"
-"Mongo.prototype.setSlaveOk = function( value ) {\n"
-"if( value == undefined ) value = true\n"
-"this.slaveOk = value\n"
-"}\n"
-"\n"
-"Mongo.prototype.getDB = function( name ){\n"
-"return new DB( this , name );\n"
-"}\n"
-"\n"
-"Mongo.prototype.getDBs = function(){\n"
-"var res = this.getDB( \"admin\" ).runCommand( { \"listDatabases\" : 1 } );\n"
-"if ( ! res.ok )\n"
-"throw \"listDatabases failed:\" + tojson( res );\n"
-"return res;\n"
-"}\n"
-"\n"
-"Mongo.prototype.adminCommand = function( cmd ){\n"
-"return this.getDB( \"admin\" ).runCommand( cmd );\n"
-"}\n"
-"\n"
-"Mongo.prototype.setLogLevel = function( logLevel ){\n"
-"return this.adminCommand({ setParameter : 1, logLevel : logLevel })\n"
-"}\n"
-"\n"
-"Mongo.prototype.getDBNames = function(){\n"
-"return this.getDBs().databases.map(\n"
-"function(z){\n"
-"return z.name;\n"
-"}\n"
-");\n"
-"}\n"
-"\n"
-"Mongo.prototype.getCollection = function(ns){\n"
-"var idx = ns.indexOf( \".\" );\n"
-"if ( idx < 0 )\n"
-"throw \"need . in ns\";\n"
-"var db = ns.substring( 0 , idx );\n"
-"var c = ns.substring( idx + 1 );\n"
-"return this.getDB( db ).getCollection( c );\n"
-"}\n"
-"\n"
-"Mongo.prototype.toString = function(){\n"
-"return \"connection to \" + this.host;\n"
-"}\n"
-"Mongo.prototype.tojson = Mongo.prototype.toString;\n"
-"\n"
-"connect = function( url , user , pass ){\n"
-"chatty( \"connecting to: \" + url )\n"
-"\n"
-"if ( user && ! pass )\n"
-"throw \"you specified a user and not a password. either you need a password, or you're using the old connect api\";\n"
-"\n"
-"var idx = url.lastIndexOf( \"/\" );\n"
-"\n"
-"var db;\n"
-"\n"
-"if ( idx < 0 )\n"
-"db = new Mongo().getDB( url );\n"
-"else\n"
-"db = new Mongo( url.substring( 0 , idx ) ).getDB( url.substring( idx + 1 ) );\n"
-"\n"
-"if ( user && pass ){\n"
-"if ( ! db.auth( user , pass ) ){\n"
-"throw \"couldn't login\";\n"
-"}\n"
-"}\n"
-"\n"
-"return db;\n"
-"}\n"
-;
-extern const JSFile mongo;
-const JSFile mongo = { "shell/mongo.js" , _jscode_raw_mongo };
-const StringData _jscode_raw_mr =
-"// mr.js\n"
-"\n"
-"MR = {};\n"
-"\n"
-"MR.init = function(){\n"
-"$max = 0;\n"
-"$arr = [];\n"
-"emit = MR.emit;\n"
-"$numEmits = 0;\n"
-"$numReduces = 0;\n"
-"$numReducesToDB = 0;\n"
-"gc(); // this is just so that keep memory size sane\n"
-"}\n"
-"\n"
-"MR.cleanup = function(){\n"
-"MR.init();\n"
-"gc();\n"
-"}\n"
-"\n"
-"MR.emit = function(k,v){\n"
-"$numEmits++;\n"
-"var num = nativeHelper.apply( get_num_ , [ k ] );\n"
-"var data = $arr[num];\n"
-"if ( ! data ){\n"
-"data = { key : k , values : new Array(1000) , count : 0 };\n"
-"$arr[num] = data;\n"
-"}\n"
-"data.values[data.count++] = v;\n"
-"$max = Math.max( $max , data.count );\n"
-"}\n"
-"\n"
-"MR.doReduce = function( useDB ){\n"
-"$numReduces++;\n"
-"if ( useDB )\n"
-"$numReducesToDB++;\n"
-"$max = 0;\n"
-"for ( var i=0; i<$arr.length; i++){\n"
-"var data = $arr[i];\n"
-"if ( ! data )\n"
-"continue;\n"
-"\n"
-"if ( useDB ){\n"
-"var x = tempcoll.findOne( { _id : data.key } );\n"
-"if ( x ){\n"
-"data.values[data.count++] = x.value;\n"
-"}\n"
-"}\n"
-"\n"
-"var r = $reduce( data.key , data.values.slice( 0 , data.count ) );\n"
-"if ( r && r.length && r[0] ){\n"
-"data.values = r;\n"
-"data.count = r.length;\n"
-"}\n"
-"else{\n"
-"data.values[0] = r;\n"
-"data.count = 1;\n"
-"}\n"
-"\n"
-"$max = Math.max( $max , data.count );\n"
-"\n"
-"if ( useDB ){\n"
-"if ( data.count == 1 ){\n"
-"tempcoll.save( { _id : data.key , value : data.values[0] } );\n"
-"}\n"
-"else {\n"
-"tempcoll.save( { _id : data.key , value : data.values.slice( 0 , data.count ) } );\n"
-"}\n"
-"}\n"
-"}\n"
-"}\n"
-"\n"
-"MR.check = function(){\n"
-"if ( $max < 2000 && $arr.length < 1000 ){\n"
-"return 0;\n"
-"}\n"
-"MR.doReduce();\n"
-"if ( $max < 2000 && $arr.length < 1000 ){\n"
-"return 1;\n"
-"}\n"
-"MR.doReduce( true );\n"
-"$arr = [];\n"
-"$max = 0;\n"
-"reset_num();\n"
-"gc();\n"
-"return 2;\n"
-"}\n"
-"\n"
-"MR.finalize = function(){\n"
-"tempcoll.find().forEach(\n"
-"function(z){\n"
-"z.value = $finalize( z._id , z.value );\n"
-"tempcoll.save( z );\n"
-"}\n"
-");\n"
-"}\n"
-;
-extern const JSFile mr;
-const JSFile mr = { "shell/mr.js" , _jscode_raw_mr };
-const StringData _jscode_raw_query =
-"// query.js\n"
-"\n"
-"if ( typeof DBQuery == \"undefined\" ){\n"
-"DBQuery = function( mongo , db , collection , ns , query , fields , limit , skip , batchSize , options ){\n"
-"\n"
-"this._mongo = mongo; // 0\n"
-"this._db = db; // 1\n"
-"this._collection = collection; // 2\n"
-"this._ns = ns; // 3\n"
-"\n"
-"this._query = query || {}; // 4\n"
-"this._fields = fields; // 5\n"
-"this._limit = limit || 0; // 6\n"
-"this._skip = skip || 0; // 7\n"
-"this._batchSize = batchSize || 0;\n"
-"this._options = options || 0;\n"
-"\n"
-"this._cursor = null;\n"
-"this._numReturned = 0;\n"
-"this._special = false;\n"
-"this._prettyShell = false;\n"
-"}\n"
-"print( \"DBQuery probably won't have array access \" );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.help = function () {\n"
-"print(\"find() modifiers\")\n"
-"print(\"\\t.sort( {...} )\")\n"
-"print(\"\\t.limit( n )\")\n"
-"print(\"\\t.skip( n )\")\n"
-"print(\"\\t.count() - total # of objects matching query, ignores skip,limit\")\n"
-"print(\"\\t.size() - total # of objects cursor would return, honors skip,limit\")\n"
-"print(\"\\t.explain([verbose])\")\n"
-"print(\"\\t.hint(...)\")\n"
-"print(\"\\t.showDiskLoc() - adds a $diskLoc field to each returned object\")\n"
-"print(\"\\nCursor methods\");\n"
-"print(\"\\t.forEach( func )\")\n"
-"print(\"\\t.map( func )\")\n"
-"print(\"\\t.hasNext()\")\n"
-"print(\"\\t.next()\")\n"
-"}\n"
-"\n"
-"DBQuery.prototype.clone = function(){\n"
-"var q = new DBQuery( this._mongo , this._db , this._collection , this._ns ,\n"
-"this._query , this._fields ,\n"
-"this._limit , this._skip , this._batchSize , this._options );\n"
-"q._special = this._special;\n"
-"return q;\n"
-"}\n"
-"\n"
-"DBQuery.prototype._ensureSpecial = function(){\n"
-"if ( this._special )\n"
-"return;\n"
-"\n"
-"var n = { query : this._query };\n"
-"this._query = n;\n"
-"this._special = true;\n"
-"}\n"
-"\n"
-"DBQuery.prototype._checkModify = function(){\n"
-"if ( this._cursor )\n"
-"throw \"query already executed\";\n"
-"}\n"
-"\n"
-"DBQuery.prototype._exec = function(){\n"
-"if ( ! this._cursor ){\n"
-"assert.eq( 0 , this._numReturned );\n"
-"this._cursor = this._mongo.find( this._ns , this._query , this._fields , this._limit , this._skip , this._batchSize , this._options );\n"
-"this._cursorSeen = 0;\n"
-"}\n"
-"return this._cursor;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.limit = function( limit ){\n"
-"this._checkModify();\n"
-"this._limit = limit;\n"
-"return this;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.batchSize = function( batchSize ){\n"
-"this._checkModify();\n"
-"this._batchSize = batchSize;\n"
-"return this;\n"
-"}\n"
-"\n"
-"\n"
-"DBQuery.prototype.addOption = function( option ){\n"
-"this._options |= option;\n"
-"return this;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.skip = function( skip ){\n"
-"this._checkModify();\n"
-"this._skip = skip;\n"
-"return this;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.hasNext = function(){\n"
-"this._exec();\n"
-"\n"
-"if ( this._limit > 0 && this._cursorSeen >= this._limit )\n"
-"return false;\n"
-"var o = this._cursor.hasNext();\n"
-"return o;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.next = function(){\n"
-"this._exec();\n"
-"\n"
-"var o = this._cursor.hasNext();\n"
-"if ( o )\n"
-"this._cursorSeen++;\n"
-"else\n"
-"throw \"error hasNext: \" + o;\n"
-"\n"
-"var ret = this._cursor.next();\n"
-"if ( ret.$err && this._numReturned == 0 && ! this.hasNext() )\n"
-"throw \"error: \" + tojson( ret );\n"
-"\n"
-"this._numReturned++;\n"
-"return ret;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.objsLeftInBatch = function(){\n"
-"this._exec();\n"
-"\n"
-"var ret = this._cursor.objsLeftInBatch();\n"
-"if ( ret.$err )\n"
-"throw \"error: \" + tojson( ret );\n"
-"\n"
-"return ret;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.toArray = function(){\n"
-"if ( this._arr )\n"
-"return this._arr;\n"
-"\n"
-"var a = [];\n"
-"while ( this.hasNext() )\n"
-"a.push( this.next() );\n"
-"this._arr = a;\n"
-"return a;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.count = function( applySkipLimit ){\n"
-"var cmd = { count: this._collection.getName() };\n"
-"if ( this._query ){\n"
-"if ( this._special )\n"
-"cmd.query = this._query.query;\n"
-"else\n"
-"cmd.query = this._query;\n"
-"}\n"
-"cmd.fields = this._fields || {};\n"
-"\n"
-"if ( applySkipLimit ){\n"
-"if ( this._limit )\n"
-"cmd.limit = this._limit;\n"
-"if ( this._skip )\n"
-"cmd.skip = this._skip;\n"
-"}\n"
-"\n"
-"var res = this._db.runCommand( cmd );\n"
-"if( res && res.n != null ) return res.n;\n"
-"throw \"count failed: \" + tojson( res );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.size = function(){\n"
-"return this.count( true );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.countReturn = function(){\n"
-"var c = this.count();\n"
-"\n"
-"if ( this._skip )\n"
-"c = c - this._skip;\n"
-"\n"
-"if ( this._limit > 0 && this._limit < c )\n"
-"return this._limit;\n"
-"\n"
-"return c;\n"
-"}\n"
-"\n"
-"/**\n"
-"* iterative count - only for testing\n"
-"*/\n"
-"DBQuery.prototype.itcount = function(){\n"
-"var num = 0;\n"
-"while ( this.hasNext() ){\n"
-"num++;\n"
-"this.next();\n"
-"}\n"
-"return num;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.length = function(){\n"
-"return this.toArray().length;\n"
-"}\n"
-"\n"
-"DBQuery.prototype._addSpecial = function( name , value ){\n"
-"this._ensureSpecial();\n"
-"this._query[name] = value;\n"
-"return this;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.sort = function( sortBy ){\n"
-"return this._addSpecial( \"orderby\" , sortBy );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.hint = function( hint ){\n"
-"return this._addSpecial( \"$hint\" , hint );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.min = function( min ) {\n"
-"return this._addSpecial( \"$min\" , min );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.max = function( max ) {\n"
-"return this._addSpecial( \"$max\" , max );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.showDiskLoc = function() {\n"
-"return this._addSpecial( \"$showDiskLoc\" , true);\n"
-"}\n"
-"\n"
-"DBQuery.prototype.forEach = function( func ){\n"
-"while ( this.hasNext() )\n"
-"func( this.next() );\n"
-"}\n"
-"\n"
-"DBQuery.prototype.map = function( func ){\n"
-"var a = [];\n"
-"while ( this.hasNext() )\n"
-"a.push( func( this.next() ) );\n"
-"return a;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.arrayAccess = function( idx ){\n"
-"return this.toArray()[idx];\n"
-"}\n"
-"\n"
-"DBQuery.prototype.explain = function (verbose) {\n"
-"/* verbose=true --> include allPlans, oldPlan fields */\n"
-"var n = this.clone();\n"
-"n._ensureSpecial();\n"
-"n._query.$explain = true;\n"
-"n._limit = Math.abs(n._limit) * -1;\n"
-"var e = n.next();\n"
-"\n"
-"function cleanup(obj){\n"
-"if (typeof(obj) != 'object'){\n"
-"return;\n"
-"}\n"
-"\n"
-"delete obj.allPlans;\n"
-"delete obj.oldPlan;\n"
-"\n"
-"if (typeof(obj.length) == 'number'){\n"
-"for (var i=0; i < obj.length; i++){\n"
-"cleanup(obj[i]);\n"
-"}\n"
-"}\n"
-"\n"
-"if (obj.shards){\n"
-"for (var key in obj.shards){\n"
-"cleanup(obj.shards[key]);\n"
-"}\n"
-"}\n"
-"\n"
-"if (obj.clauses){\n"
-"cleanup(obj.clauses);\n"
-"}\n"
-"}\n"
-"\n"
-"if (!verbose)\n"
-"cleanup(e);\n"
-"\n"
-"return e;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.snapshot = function(){\n"
-"this._ensureSpecial();\n"
-"this._query.$snapshot = true;\n"
-"return this;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.pretty = function(){\n"
-"this._prettyShell = true;\n"
-"return this;\n"
-"}\n"
-"\n"
-"DBQuery.prototype.shellPrint = function(){\n"
-"try {\n"
-"var n = 0;\n"
-"while ( this.hasNext() && n < DBQuery.shellBatchSize ){\n"
-"var s = this._prettyShell ? tojson( this.next() ) : tojson( this.next() , \"\" , true );\n"
-"print( s );\n"
-"n++;\n"
-"}\n"
-"if ( this.hasNext() ){\n"
-"print( \"has more\" );\n"
-"___it___ = this;\n"
-"}\n"
-"else {\n"
-"___it___ = null;\n"
-"}\n"
-"}\n"
-"catch ( e ){\n"
-"print( e );\n"
-"}\n"
-"\n"
-"}\n"
-"\n"
-"DBQuery.prototype.toString = function(){\n"
-"return \"DBQuery: \" + this._ns + \" -> \" + tojson( this.query );\n"
-"}\n"
-"\n"
-"DBQuery.shellBatchSize = 20;\n"
-;
-extern const JSFile query;
-const JSFile query = { "shell/query.js" , _jscode_raw_query };
-const StringData _jscode_raw_collection =
-"// @file collection.js - DBCollection support in the mongo shell\n"
-"// db.colName is a DBCollection object\n"
-"// or db[\"colName\"]\n"
-"\n"
-"if ( ( typeof DBCollection ) == \"undefined\" ){\n"
-"DBCollection = function( mongo , db , shortName , fullName ){\n"
-"this._mongo = mongo;\n"
-"this._db = db;\n"
-"this._shortName = shortName;\n"
-"this._fullName = fullName;\n"
-"\n"
-"this.verify();\n"
-"}\n"
-"}\n"
-"\n"
-"DBCollection.prototype.verify = function(){\n"
-"assert( this._fullName , \"no fullName\" );\n"
-"assert( this._shortName , \"no shortName\" );\n"
-"assert( this._db , \"no db\" );\n"
-"\n"
-"assert.eq( this._fullName , this._db._name + \".\" + this._shortName , \"name mismatch\" );\n"
-"\n"
-"assert( this._mongo , \"no mongo in DBCollection\" );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.getName = function(){\n"
-"return this._shortName;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.help = function () {\n"
-"var shortName = this.getName();\n"
-"print(\"DBCollection help\");\n"
-"print(\"\\tdb.\" + shortName + \".find().help() - show DBCursor help\");\n"
-"print(\"\\tdb.\" + shortName + \".count()\");\n"
-"print(\"\\tdb.\" + shortName + \".dataSize()\");\n"
-"print(\"\\tdb.\" + shortName + \".distinct( key ) - eg. db.\" + shortName + \".distinct( 'x' )\");\n"
-"print(\"\\tdb.\" + shortName + \".drop() drop the collection\");\n"
-"print(\"\\tdb.\" + shortName + \".dropIndex(name)\");\n"
-"print(\"\\tdb.\" + shortName + \".dropIndexes()\");\n"
-"print(\"\\tdb.\" + shortName + \".ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups\");\n"
-"print(\"\\tdb.\" + shortName + \".reIndex()\");\n"
-"print(\"\\tdb.\" + shortName + \".find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.\");\n"
-"print(\"\\t e.g. db.\" + shortName + \".find( {x:77} , {name:1, x:1} )\");\n"
-"print(\"\\tdb.\" + shortName + \".find(...).count()\");\n"
-"print(\"\\tdb.\" + shortName + \".find(...).limit(n)\");\n"
-"print(\"\\tdb.\" + shortName + \".find(...).skip(n)\");\n"
-"print(\"\\tdb.\" + shortName + \".find(...).sort(...)\");\n"
-"print(\"\\tdb.\" + shortName + \".findOne([query])\");\n"
-"print(\"\\tdb.\" + shortName + \".findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )\");\n"
-"print(\"\\tdb.\" + shortName + \".getDB() get DB object associated with collection\");\n"
-"print(\"\\tdb.\" + shortName + \".getIndexes()\");\n"
-"print(\"\\tdb.\" + shortName + \".group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )\");\n"
-"print(\"\\tdb.\" + shortName + \".mapReduce( mapFunction , reduceFunction , <optional params> )\");\n"
-"print(\"\\tdb.\" + shortName + \".remove(query)\");\n"
-"print(\"\\tdb.\" + shortName + \".renameCollection( newName , <dropTarget> ) renames the collection.\");\n"
-"print(\"\\tdb.\" + shortName + \".runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name\");\n"
-"print(\"\\tdb.\" + shortName + \".save(obj)\");\n"
-"print(\"\\tdb.\" + shortName + \".stats()\");\n"
-"print(\"\\tdb.\" + shortName + \".storageSize() - includes free space allocated to this collection\");\n"
-"print(\"\\tdb.\" + shortName + \".totalIndexSize() - size in bytes of all the indexes\");\n"
-"print(\"\\tdb.\" + shortName + \".totalSize() - storage allocated for all data and indexes\");\n"
-"print(\"\\tdb.\" + shortName + \".update(query, object[, upsert_bool, multi_bool])\");\n"
-"print(\"\\tdb.\" + shortName + \".validate( <full> ) - SLOW\");;\n"
-"print(\"\\tdb.\" + shortName + \".getShardVersion() - only for use with sharding\");\n"
-"print(\"\\tdb.\" + shortName + \".getShardDistribution() - prints statistics about data distribution in the cluster\");\n"
-"return __magicNoPrint;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.getFullName = function(){\n"
-"return this._fullName;\n"
-"}\n"
-"DBCollection.prototype.getMongo = function(){\n"
-"return this._db.getMongo();\n"
-"}\n"
-"DBCollection.prototype.getDB = function(){\n"
-"return this._db;\n"
-"}\n"
-"\n"
-"DBCollection.prototype._dbCommand = function( cmd , params ){\n"
-"if ( typeof( cmd ) == \"object\" )\n"
-"return this._db._dbCommand( cmd );\n"
-"\n"
-"var c = {};\n"
-"c[cmd] = this.getName();\n"
-"if ( params )\n"
-"Object.extend( c , params );\n"
-"return this._db._dbCommand( c );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.runCommand = DBCollection.prototype._dbCommand;\n"
-"\n"
-"DBCollection.prototype._massageObject = function( q ){\n"
-"if ( ! q )\n"
-"return {};\n"
-"\n"
-"var type = typeof q;\n"
-"\n"
-"if ( type == \"function\" )\n"
-"return { $where : q };\n"
-"\n"
-"if ( q.isObjectId )\n"
-"return { _id : q };\n"
-"\n"
-"if ( type == \"object\" )\n"
-"return q;\n"
-"\n"
-"if ( type == \"string\" ){\n"
-"if ( q.length == 24 )\n"
-"return { _id : q };\n"
-"\n"
-"return { $where : q };\n"
-"}\n"
-"\n"
-"throw \"don't know how to massage : \" + type;\n"
-"\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype._validateObject = function( o ){\n"
-"if ( o._ensureSpecial && o._checkModify )\n"
-"throw \"can't save a DBQuery object\";\n"
-"}\n"
-"\n"
-"DBCollection._allowedFields = { $id : 1 , $ref : 1 , $db : 1 , $MinKey : 1, $MaxKey : 1 };\n"
-"\n"
-"DBCollection.prototype._validateForStorage = function( o ){\n"
-"this._validateObject( o );\n"
-"for ( var k in o ){\n"
-"if ( k.indexOf( \".\" ) >= 0 ) {\n"
-"throw \"can't have . in field names [\" + k + \"]\" ;\n"
-"}\n"
-"\n"
-"if ( k.indexOf( \"$\" ) == 0 && ! DBCollection._allowedFields[k] ) {\n"
-"throw \"field names cannot start with $ [\" + k + \"]\";\n"
-"}\n"
-"\n"
-"if ( o[k] !== null && typeof( o[k] ) === \"object\" ) {\n"
-"this._validateForStorage( o[k] );\n"
-"}\n"
-"}\n"
-"};\n"
-"\n"
-"\n"
-"DBCollection.prototype.find = function( query , fields , limit , skip ){\n"
-"return new DBQuery( this._mongo , this._db , this ,\n"
-"this._fullName , this._massageObject( query ) , fields , limit , skip );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.findOne = function( query , fields ){\n"
-"var cursor = this._mongo.find( this._fullName , this._massageObject( query ) || {} , fields ,\n"
-"-1 /* limit */ , 0 /* skip*/, 0 /* batchSize */ , 0 /* options */ );\n"
-"if ( ! cursor.hasNext() )\n"
-"return null;\n"
-"var ret = cursor.next();\n"
-"if ( cursor.hasNext() ) throw \"findOne has more than 1 result!\";\n"
-"if ( ret.$err )\n"
-"throw \"error \" + tojson( ret );\n"
-"return ret;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.insert = function( obj , _allow_dot ){\n"
-"if ( ! obj )\n"
-"throw \"no object passed to insert!\";\n"
-"if ( ! _allow_dot ) {\n"
-"this._validateForStorage( obj );\n"
-"}\n"
-"if ( typeof( obj._id ) == \"undefined\" ){\n"
-"var tmp = obj; // don't want to modify input\n"
-"obj = {_id: new ObjectId()};\n"
-"for (var key in tmp){\n"
-"obj[key] = tmp[key];\n"
-"}\n"
-"}\n"
-"this._mongo.insert( this._fullName , obj );\n"
-"this._lastID = obj._id;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.remove = function( t , justOne ){\n"
-"for ( var k in t ){\n"
-"if ( k == \"_id\" && typeof( t[k] ) == \"undefined\" ){\n"
-"throw \"can't have _id set to undefined in a remove expression\"\n"
-"}\n"
-"}\n"
-"this._mongo.remove( this._fullName , this._massageObject( t ) , justOne ? true : false );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.update = function( query , obj , upsert , multi ){\n"
-"assert( query , \"need a query\" );\n"
-"assert( obj , \"need an object\" );\n"
-"\n"
-"var firstKey = null;\n"
-"for (var k in obj) { firstKey = k; break; }\n"
-"\n"
-"if (firstKey != null && firstKey[0] == '$') {\n"
-"// for mods we only validate partially, for example keys may have dots\n"
-"this._validateObject( obj );\n"
-"} else {\n"
-"// we're basically inserting a brand new object, do full validation\n"
-"this._validateForStorage( obj );\n"
-"}\n"
-"this._mongo.update( this._fullName , query , obj , upsert ? true : false , multi ? true : false );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.save = function( obj ){\n"
-"if ( obj == null || typeof( obj ) == \"undefined\" )\n"
-"throw \"can't save a null\";\n"
-"\n"
-"if ( typeof( obj ) == \"number\" || typeof( obj) == \"string\" )\n"
-"throw \"can't save a number or string\"\n"
-"\n"
-"if ( typeof( obj._id ) == \"undefined\" ){\n"
-"obj._id = new ObjectId();\n"
-"return this.insert( obj );\n"
-"}\n"
-"else {\n"
-"return this.update( { _id : obj._id } , obj , true );\n"
-"}\n"
-"}\n"
-"\n"
-"DBCollection.prototype._genIndexName = function( keys ){\n"
-"var name = \"\";\n"
-"for ( var k in keys ){\n"
-"var v = keys[k];\n"
-"if ( typeof v == \"function\" )\n"
-"continue;\n"
-"\n"
-"if ( name.length > 0 )\n"
-"name += \"_\";\n"
-"name += k + \"_\";\n"
-"\n"
-"if ( typeof v == \"number\" )\n"
-"name += v;\n"
-"}\n"
-"return name;\n"
-"}\n"
-"\n"
-"DBCollection.prototype._indexSpec = function( keys, options ) {\n"
-"var ret = { ns : this._fullName , key : keys , name : this._genIndexName( keys ) };\n"
-"\n"
-"if ( ! options ){\n"
-"}\n"
-"else if ( typeof ( options ) == \"string\" )\n"
-"ret.name = options;\n"
-"else if ( typeof ( options ) == \"boolean\" )\n"
-"ret.unique = true;\n"
-"else if ( typeof ( options ) == \"object\" ){\n"
-"if ( options.length ){\n"
-"var nb = 0;\n"
-"for ( var i=0; i<options.length; i++ ){\n"
-"if ( typeof ( options[i] ) == \"string\" )\n"
-"ret.name = options[i];\n"
-"else if ( typeof( options[i] ) == \"boolean\" ){\n"
-"if ( options[i] ){\n"
-"if ( nb == 0 )\n"
-"ret.unique = true;\n"
-"if ( nb == 1 )\n"
-"ret.dropDups = true;\n"
-"}\n"
-"nb++;\n"
-"}\n"
-"}\n"
-"}\n"
-"else {\n"
-"Object.extend( ret , options );\n"
-"}\n"
-"}\n"
-"else {\n"
-"throw \"can't handle: \" + typeof( options );\n"
-"}\n"
-"/*\n"
-"return ret;\n"
-"\n"
-"var name;\n"
-"var nTrue = 0;\n"
-"\n"
-"if ( ! isObject( options ) ) {\n"
-"options = [ options ];\n"
-"}\n"
-"\n"
-"if ( options.length ){\n"
-"for( var i = 0; i < options.length; ++i ) {\n"
-"var o = options[ i ];\n"
-"if ( isString( o ) ) {\n"
-"ret.name = o;\n"
-"} else if ( typeof( o ) == \"boolean\" ) {\n"
-"if ( o ) {\n"
-"++nTrue;\n"
-"}\n"
-"}\n"
-"}\n"
-"if ( nTrue > 0 ) {\n"
-"ret.unique = true;\n"
-"}\n"
-"if ( nTrue > 1 ) {\n"
-"ret.dropDups = true;\n"
-"}\n"
-"}\n"
-"*/\n"
-"return ret;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.createIndex = function( keys , options ){\n"
-"var o = this._indexSpec( keys, options );\n"
-"this._db.getCollection( \"system.indexes\" ).insert( o , true );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.ensureIndex = function( keys , options ){\n"
-"var name = this._indexSpec( keys, options ).name;\n"
-"this._indexCache = this._indexCache || {};\n"
-"if ( this._indexCache[ name ] ){\n"
-"return;\n"
-"}\n"
-"\n"
-"this.createIndex( keys , options );\n"
-"if ( this.getDB().getLastError() == \"\" ) {\n"
-"this._indexCache[name] = true;\n"
-"}\n"
-"}\n"
-"\n"
-"DBCollection.prototype.resetIndexCache = function(){\n"
-"this._indexCache = {};\n"
-"}\n"
-"\n"
-"DBCollection.prototype.reIndex = function() {\n"
-"return this._db.runCommand({ reIndex: this.getName() });\n"
-"}\n"
-"\n"
-"DBCollection.prototype.dropIndexes = function(){\n"
-"this.resetIndexCache();\n"
-"\n"
-"var res = this._db.runCommand( { deleteIndexes: this.getName(), index: \"*\" } );\n"
-"assert( res , \"no result from dropIndex result\" );\n"
-"if ( res.ok )\n"
-"return res;\n"
-"\n"
-"if ( res.errmsg.match( /not found/ ) )\n"
-"return res;\n"
-"\n"
-"throw \"error dropping indexes : \" + tojson( res );\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype.drop = function(){\n"
-"if ( arguments.length > 0 )\n"
-"throw \"drop takes no argument\";\n"
-"this.resetIndexCache();\n"
-"var ret = this._db.runCommand( { drop: this.getName() } );\n"
-"if ( ! ret.ok ){\n"
-"if ( ret.errmsg == \"ns not found\" )\n"
-"return false;\n"
-"throw \"drop failed: \" + tojson( ret );\n"
-"}\n"
-"return true;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.findAndModify = function(args){\n"
-"var cmd = { findandmodify: this.getName() };\n"
-"for (var key in args){\n"
-"cmd[key] = args[key];\n"
-"}\n"
-"\n"
-"var ret = this._db.runCommand( cmd );\n"
-"if ( ! ret.ok ){\n"
-"if (ret.errmsg == \"No matching object found\"){\n"
-"return null;\n"
-"}\n"
-"throw \"findAndModifyFailed failed: \" + tojson( ret.errmsg );\n"
-"}\n"
-"return ret.value;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.renameCollection = function( newName , dropTarget ){\n"
-"return this._db._adminCommand( { renameCollection : this._fullName ,\n"
-"to : this._db._name + \".\" + newName ,\n"
-"dropTarget : dropTarget } )\n"
-"}\n"
-"\n"
-"DBCollection.prototype.validate = function(full) {\n"
-"var cmd = { validate: this.getName() };\n"
-"\n"
-"if (typeof(full) == 'object') // support arbitrary options here\n"
-"Object.extend(cmd, full);\n"
-"else\n"
-"cmd.full = full;\n"
-"\n"
-"var res = this._db.runCommand( cmd );\n"
-"\n"
-"if (typeof(res.valid) == 'undefined') {\n"
-"// old-style format just put everything in a string. Now using proper fields\n"
-"\n"
-"res.valid = false;\n"
-"\n"
-"var raw = res.result || res.raw;\n"
-"\n"
-"if ( raw ){\n"
-"var str = \"-\" + tojson( raw );\n"
-"res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );\n"
-"\n"
-"var p = /lastExtentSize:(\\d+)/;\n"
-"var r = p.exec( str );\n"
-"if ( r ){\n"
-"res.lastExtentSize = Number( r[1] );\n"
-"}\n"
-"}\n"
-"}\n"
-"\n"
-"return res;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.getShardVersion = function(){\n"
-"return this._db._adminCommand( { getShardVersion : this._fullName } );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.getIndexes = function(){\n"
-"return this.getDB().getCollection( \"system.indexes\" ).find( { ns : this.getFullName() } ).toArray();\n"
-"}\n"
-"\n"
-"DBCollection.prototype.getIndices = DBCollection.prototype.getIndexes;\n"
-"DBCollection.prototype.getIndexSpecs = DBCollection.prototype.getIndexes;\n"
-"\n"
-"DBCollection.prototype.getIndexKeys = function(){\n"
-"return this.getIndexes().map(\n"
-"function(i){\n"
-"return i.key;\n"
-"}\n"
-");\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype.count = function( x ){\n"
-"return this.find( x ).count();\n"
-"}\n"
-"\n"
-"/**\n"
-"* Drop free lists. Normally not used.\n"
-"* Note this only does the collection itself, not the namespaces of its indexes (see cleanAll).\n"
-"*/\n"
-"DBCollection.prototype.clean = function() {\n"
-"return this._dbCommand( { clean: this.getName() } );\n"
-"}\n"
-"\n"
-"\n"
-"\n"
-"/**\n"
-"* <p>Drop a specified index.</p>\n"
-"*\n"
-"* <p>\n"
-"* Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to\n"
-"* see example data.)\n"
-"* </p>\n"
-"*\n"
-"* <p>Note : alpha: space is not reclaimed </p>\n"
-"* @param {String} name of index to delete.\n"
-"* @return A result object. result.ok will be true if successful.\n"
-"*/\n"
-"DBCollection.prototype.dropIndex = function(index) {\n"
-"assert(index , \"need to specify index to dropIndex\" );\n"
-"\n"
-"if ( ! isString( index ) && isObject( index ) )\n"
-"index = this._genIndexName( index );\n"
-"\n"
-"var res = this._dbCommand( \"deleteIndexes\" ,{ index: index } );\n"
-"this.resetIndexCache();\n"
-"return res;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.copyTo = function( newName ){\n"
-"return this.getDB().eval(\n"
-"function( collName , newName ){\n"
-"var from = db[collName];\n"
-"var to = db[newName];\n"
-"to.ensureIndex( { _id : 1 } );\n"
-"var count = 0;\n"
-"\n"
-"var cursor = from.find();\n"
-"while ( cursor.hasNext() ){\n"
-"var o = cursor.next();\n"
-"count++;\n"
-"to.save( o );\n"
-"}\n"
-"\n"
-"return count;\n"
-"} , this.getName() , newName\n"
-");\n"
-"}\n"
-"\n"
-"DBCollection.prototype.getCollection = function( subName ){\n"
-"return this._db.getCollection( this._shortName + \".\" + subName );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.stats = function( scale ){\n"
-"return this._db.runCommand( { collstats : this._shortName , scale : scale } );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.dataSize = function(){\n"
-"return this.stats().size;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.storageSize = function(){\n"
-"return this.stats().storageSize;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.totalIndexSize = function( verbose ){\n"
-"var stats = this.stats();\n"
-"if (verbose){\n"
-"for (var ns in stats.indexSizes){\n"
-"print( ns + \"\\t\" + stats.indexSizes[ns] );\n"
-"}\n"
-"}\n"
-"return stats.totalIndexSize;\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype.totalSize = function(){\n"
-"var total = this.storageSize();\n"
-"var mydb = this._db;\n"
-"var shortName = this._shortName;\n"
-"this.getIndexes().forEach(\n"
-"function( spec ){\n"
-"var coll = mydb.getCollection( shortName + \".$\" + spec.name );\n"
-"var mysize = coll.storageSize();\n"
-"//print( coll + \"\\t\" + mysize + \"\\t\" + tojson( coll.validate() ) );\n"
-"total += coll.dataSize();\n"
-"}\n"
-");\n"
-"return total;\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype.convertToCapped = function( bytes ){\n"
-"if ( ! bytes )\n"
-"throw \"have to specify # of bytes\";\n"
-"return this._dbCommand( { convertToCapped : this._shortName , size : bytes } )\n"
-"}\n"
-"\n"
-"DBCollection.prototype.exists = function(){\n"
-"return this._db.system.namespaces.findOne( { name : this._fullName } );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.isCapped = function(){\n"
-"var e = this.exists();\n"
-"return ( e && e.options && e.options.capped ) ? true : false;\n"
-"}\n"
-"\n"
-"DBCollection.prototype._distinct = function( keyString , query ){\n"
-"return this._dbCommand( { distinct : this._shortName , key : keyString , query : query || {} } );\n"
-"if ( ! res.ok )\n"
-"throw \"distinct failed: \" + tojson( res );\n"
-"return res.values;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.distinct = function( keyString , query ){\n"
-"var res = this._distinct( keyString , query );\n"
-"if ( ! res.ok )\n"
-"throw \"distinct failed: \" + tojson( res );\n"
-"return res.values;\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype.group = function( params ){\n"
-"params.ns = this._shortName;\n"
-"return this._db.group( params );\n"
-"}\n"
-"\n"
-"DBCollection.prototype.groupcmd = function( params ){\n"
-"params.ns = this._shortName;\n"
-"return this._db.groupcmd( params );\n"
-"}\n"
-"\n"
-"MapReduceResult = function( db , o ){\n"
-"Object.extend( this , o );\n"
-"this._o = o;\n"
-"this._keys = Object.keySet( o );\n"
-"this._db = db;\n"
-"if ( this.result != null ) {\n"
-"this._coll = this._db.getCollection( this.result );\n"
-"}\n"
-"}\n"
-"\n"
-"MapReduceResult.prototype._simpleKeys = function(){\n"
-"return this._o;\n"
-"}\n"
-"\n"
-"MapReduceResult.prototype.find = function(){\n"
-"if ( this.results )\n"
-"return this.results;\n"
-"return DBCollection.prototype.find.apply( this._coll , arguments );\n"
-"}\n"
-"\n"
-"MapReduceResult.prototype.drop = function(){\n"
-"if ( this._coll ) {\n"
-"return this._coll.drop();\n"
-"}\n"
-"}\n"
-"\n"
-"/**\n"
-"* just for debugging really\n"
-"*/\n"
-"MapReduceResult.prototype.convertToSingleObject = function(){\n"
-"var z = {};\n"
-"var it = this.results != null ? this.results : this._coll.find();\n"
-"it.forEach( function(a){ z[a._id] = a.value; } );\n"
-"return z;\n"
-"}\n"
-"\n"
-"DBCollection.prototype.convertToSingleObject = function(valueField){\n"
-"var z = {};\n"
-"this.find().forEach( function(a){ z[a._id] = a[valueField]; } );\n"
-"return z;\n"
-"}\n"
-"\n"
-"/**\n"
-"* @param optional object of optional fields;\n"
-"*/\n"
-"DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString ){\n"
-"var c = { mapreduce : this._shortName , map : map , reduce : reduce };\n"
-"assert( optionsOrOutString , \"need to supply an optionsOrOutString\" )\n"
-"\n"
-"if ( typeof( optionsOrOutString ) == \"string\" )\n"
-"c[\"out\"] = optionsOrOutString;\n"
-"else\n"
-"Object.extend( c , optionsOrOutString );\n"
-"\n"
-"var raw = this._db.runCommand( c );\n"
-"if ( ! raw.ok ){\n"
-"__mrerror__ = raw;\n"
-"throw \"map reduce failed:\" + tojson(raw);\n"
-"}\n"
-"return new MapReduceResult( this._db , raw );\n"
-"\n"
-"}\n"
-"\n"
-"DBCollection.prototype.toString = function(){\n"
-"return this.getFullName();\n"
-"}\n"
-"\n"
-"DBCollection.prototype.toString = function(){\n"
-"return this.getFullName();\n"
-"}\n"
-"\n"
-"\n"
-"DBCollection.prototype.tojson = DBCollection.prototype.toString;\n"
-"\n"
-"DBCollection.prototype.shellPrint = DBCollection.prototype.toString;\n"
-"\n"
-"DBCollection.autocomplete = function(obj){\n"
-"var colls = DB.autocomplete(obj.getDB());\n"
-"var ret = [];\n"
-"for (var i=0; i<colls.length; i++){\n"
-"var c = colls[i];\n"
-"if (c.length <= obj.getName().length) continue;\n"
-"if (c.slice(0,obj.getName().length+1) != obj.getName()+'.') continue;\n"
-"\n"
-"ret.push(c.slice(obj.getName().length+1));\n"
-"}\n"
-"return ret;\n"
-"}\n"
-"\n"
-"\n"
-"// Sharding additions\n"
-"\n"
-"/*\n"
-"Usage :\n"
-"\n"
-"mongo <mongos>\n"
-"> load('path-to-file/shardingAdditions.js')\n"
-"Loading custom sharding extensions...\n"
-"true\n"
-"\n"
-"> var collection = db.getMongo().getCollection(\"foo.bar\")\n"
-"> collection.getShardDistribution() // prints statistics related to the collection's data distribution\n"
-"\n"
-"> collection.getSplitKeysForChunks() // generates split points for all chunks in the collection, based on the\n"
-"// default maxChunkSize or alternately a specified chunk size\n"
-"> collection.getSplitKeysForChunks( 10 ) // Mb\n"
-"\n"
-"> var splitter = collection.getSplitKeysForChunks() // by default, the chunks are not split, the keys are just\n"
-"// found. A splitter function is returned which will actually\n"
-"// do the splits.\n"
-"\n"
-"> splitter() // ! Actually executes the splits on the cluster !\n"
-"\n"
-"*/\n"
-"\n"
-"DBCollection.prototype.getShardDistribution = function(){\n"
-"\n"
-"var stats = this.stats()\n"
-"\n"
-"if( ! stats.sharded ){\n"
-"print( \"Collection \" + this + \" is not sharded.\" )\n"
-"return\n"
-"}\n"
-"\n"
-"var config = this.getMongo().getDB(\"config\")\n"
-"\n"
-"var numChunks = 0\n"
-"\n"
-"for( var shard in stats.shards ){\n"
-"\n"
-"var shardDoc = config.shards.findOne({ _id : shard })\n"
-"\n"
-"print( \"\\nShard \" + shard + \" at \" + shardDoc.host )\n"
-"\n"
-"var shardStats = stats.shards[ shard ]\n"
-"\n"
-"var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray()\n"
-"\n"
-"numChunks += chunks.length\n"
-"\n"
-"var estChunkData = shardStats.size / chunks.length\n"
-"var estChunkCount = Math.floor( shardStats.count / chunks.length )\n"
-"\n"
-"print( \" data : \" + sh._dataFormat( shardStats.size ) +\n"
-"\" docs : \" + shardStats.count +\n"
-"\" chunks : \" + chunks.length )\n"
-"print( \" estimated data per chunk : \" + sh._dataFormat( estChunkData ) )\n"
-"print( \" estimated docs per chunk : \" + estChunkCount )\n"
-"\n"
-"}\n"
-"\n"
-"print( \"\\nTotals\" )\n"
-"print( \" data : \" + sh._dataFormat( stats.size ) +\n"
-"\" docs : \" + stats.count +\n"
-"\" chunks : \" + numChunks )\n"
-"for( var shard in stats.shards ){\n"
-"\n"
-"var shardStats = stats.shards[ shard ]\n"
-"\n"
-"var estDataPercent = Math.floor( shardStats.size / stats.size * 10000 ) / 100\n"
-"var estDocPercent = Math.floor( shardStats.count / stats.count * 10000 ) / 100\n"
-"\n"
-"print( \" Shard \" + shard + \" contains \" + estDataPercent + \"% data, \" + estDocPercent + \"% docs in cluster, \" +\n"
-"\"avg obj size on shard : \" + sh._dataFormat( stats.shards[ shard ].avgObjSize ) )\n"
-"}\n"
-"\n"
-"print( \"\\n\" )\n"
-"\n"
-"}\n"
-"\n"
-"// In testing phase, use with caution\n"
-"DBCollection.prototype._getSplitKeysForChunks = function( chunkSize ){\n"
-"\n"
-"var stats = this.stats()\n"
-"\n"
-"if( ! stats.sharded ){\n"
-"print( \"Collection \" + this + \" is not sharded.\" )\n"
-"return\n"
-"}\n"
-"\n"
-"var config = this.getMongo().getDB(\"config\")\n"
-"\n"
-"if( ! chunkSize ){\n"
-"chunkSize = config.settings.findOne({ _id : \"chunksize\" }).value\n"
-"print( \"Chunk size not set, using default of \" + chunkSize + \"Mb\" )\n"
-"}\n"
-"else{\n"
-"print( \"Using chunk size of \" + chunkSize + \"Mb\" )\n"
-"}\n"
-"\n"
-"var shardDocs = config.shards.find().toArray()\n"
-"\n"
-"var allSplitPoints = {}\n"
-"var numSplits = 0\n"
-"\n"
-"for( var i = 0; i < shardDocs.length; i++ ){\n"
-"\n"
-"var shardDoc = shardDocs[i]\n"
-"var shard = shardDoc._id\n"
-"var host = shardDoc.host\n"
-"var sconn = new Mongo( host )\n"
-"\n"
-"var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray()\n"
-"\n"
-"print( \"\\nGetting split points for chunks on shard \" + shard + \" at \" + host )\n"
-"\n"
-"var splitPoints = []\n"
-"\n"
-"for( var j = 0; j < chunks.length; j++ ){\n"
-"var chunk = chunks[j]\n"
-"var result = sconn.getDB(\"admin\").runCommand({ splitVector : this + \"\", min : chunk.min, max : chunk.max, maxChunkSize : chunkSize })\n"
-"if( ! result.ok ){\n"
-"print( \" Had trouble getting split keys for chunk \" + sh._pchunk( chunk ) + \" :\\n\" )\n"
-"printjson( result )\n"
-"}\n"
-"else{\n"
-"splitPoints = splitPoints.concat( result.splitKeys )\n"
-"\n"
-"if( result.splitKeys.length > 0 )\n"
-"print( \" Added \" + result.splitKeys.length + \" split points for chunk \" + sh._pchunk( chunk ) )\n"
-"}\n"
-"}\n"
-"\n"
-"print( \"Total splits for shard \" + shard + \" : \" + splitPoints.length )\n"
-"\n"
-"numSplits += splitPoints.length\n"
-"allSplitPoints[ shard ] = splitPoints\n"
-"\n"
-"}\n"
-"\n"
-"// Get most recent migration\n"
-"var migration = config.changelog.find({ what : /^move.*/ }).sort({ time : -1 }).limit( 1 ).toArray()\n"
-"if( migration.length == 0 )\n"
-"print( \"\\nNo migrations found in changelog.\" )\n"
-"else {\n"
-"migration = migration[0]\n"
-"print( \"\\nMost recent migration activity was on \" + migration.ns + \" at \" + migration.time )\n"
-"}\n"
-"\n"
-"var admin = this.getMongo().getDB(\"admin\")\n"
-"var coll = this\n"
-"var splitFunction = function(){\n"
-"\n"
-"// Turn off the balancer, just to be safe\n"
-"print( \"Turning off balancer...\" )\n"
-"config.settings.update({ _id : \"balancer\" }, { $set : { stopped : true } }, true )\n"
-"print( \"Sleeping for 30s to allow balancers to detect change. To be extra safe, check config.changelog\" +\n"
-"\" for recent migrations.\" )\n"
-"sleep( 30000 )\n"
-"\n"
-"for( shard in allSplitPoints ){\n"
-"for( var i = 0; i < allSplitPoints[ shard ].length; i++ ){\n"
-"var splitKey = allSplitPoints[ shard ][i]\n"
-"print( \"Splitting at \" + tojson( splitKey ) )\n"
-"printjson( admin.runCommand({ split : coll + \"\", middle : splitKey }) )\n"
-"}\n"
-"}\n"
-"\n"
-"print( \"Turning the balancer back on.\" )\n"
-"config.settings.update({ _id : \"balancer\" }, { $set : { stopped : false } } )\n"
-"sleep( 1 )\n"
-"}\n"
-"\n"
-"print( \"\\nGenerated \" + numSplits + \" split keys, run output function to perform splits.\\n\" +\n"
-"\" ex : \\n\" +\n"
-"\" > var splitter = <collection>.getSplitKeysForChunks()\\n\" +\n"
-"\" > splitter() // Execute splits on cluster !\\n\" )\n"
-"\n"
-"return splitFunction\n"
-"\n"
-"}\n"
-"\n"
-"\n"
-"\n"
-"\n"
-;
-extern const JSFile collection;
-const JSFile collection = { "shell/collection.js" , _jscode_raw_collection };
-} // namespace JSFiles
-} // namespace mongo
diff --git a/shell/mr.js b/shell/mr.js
deleted file mode 100644
index 7b0814dd557..00000000000
--- a/shell/mr.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// mr.js
-
-MR = {};
-
-MR.init = function(){
- $max = 0;
- $arr = [];
- emit = MR.emit;
- $numEmits = 0;
- $numReduces = 0;
- $numReducesToDB = 0;
- gc(); // this is just so that keep memory size sane
-}
-
-MR.cleanup = function(){
- MR.init();
- gc();
-}
-
-MR.emit = function(k,v){
- $numEmits++;
- var num = nativeHelper.apply( get_num_ , [ k ] );
- var data = $arr[num];
- if ( ! data ){
- data = { key : k , values : new Array(1000) , count : 0 };
- $arr[num] = data;
- }
- data.values[data.count++] = v;
- $max = Math.max( $max , data.count );
-}
-
-MR.doReduce = function( useDB ){
- $numReduces++;
- if ( useDB )
- $numReducesToDB++;
- $max = 0;
- for ( var i=0; i<$arr.length; i++){
- var data = $arr[i];
- if ( ! data )
- continue;
-
- if ( useDB ){
- var x = tempcoll.findOne( { _id : data.key } );
- if ( x ){
- data.values[data.count++] = x.value;
- }
- }
-
- var r = $reduce( data.key , data.values.slice( 0 , data.count ) );
- if ( r && r.length && r[0] ){
- data.values = r;
- data.count = r.length;
- }
- else{
- data.values[0] = r;
- data.count = 1;
- }
-
- $max = Math.max( $max , data.count );
-
- if ( useDB ){
- if ( data.count == 1 ){
- tempcoll.save( { _id : data.key , value : data.values[0] } );
- }
- else {
- tempcoll.save( { _id : data.key , value : data.values.slice( 0 , data.count ) } );
- }
- }
- }
-}
-
-MR.check = function(){
- if ( $max < 2000 && $arr.length < 1000 ){
- return 0;
- }
- MR.doReduce();
- if ( $max < 2000 && $arr.length < 1000 ){
- return 1;
- }
- MR.doReduce( true );
- $arr = [];
- $max = 0;
- reset_num();
- gc();
- return 2;
-}
-
-MR.finalize = function(){
- tempcoll.find().forEach(
- function(z){
- z.value = $finalize( z._id , z.value );
- tempcoll.save( z );
- }
- );
-}
diff --git a/shell/msvc/mongo.ico b/shell/msvc/mongo.ico
deleted file mode 100755
index 1eba9ed5131..00000000000
--- a/shell/msvc/mongo.ico
+++ /dev/null
Binary files differ
diff --git a/shell/msvc/mongo.sln b/shell/msvc/mongo.sln
deleted file mode 100644
index 01c9e1e6e40..00000000000
--- a/shell/msvc/mongo.sln
+++ /dev/null
@@ -1,20 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 11.00
-# Visual Studio 2010
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mongo", "mongo.vcxproj", "{FE959BD8-8EE2-4555-AE59-9FA14FFD410E}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Win32 = Debug|Win32
- Release|Win32 = Release|Win32
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {FE959BD8-8EE2-4555-AE59-9FA14FFD410E}.Debug|Win32.ActiveCfg = Debug|Win32
- {FE959BD8-8EE2-4555-AE59-9FA14FFD410E}.Debug|Win32.Build.0 = Debug|Win32
- {FE959BD8-8EE2-4555-AE59-9FA14FFD410E}.Release|Win32.ActiveCfg = Release|Win32
- {FE959BD8-8EE2-4555-AE59-9FA14FFD410E}.Release|Win32.Build.0 = Release|Win32
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/shell/msvc/mongo.vcxproj b/shell/msvc/mongo.vcxproj
deleted file mode 100644
index eb6ffe1f989..00000000000
--- a/shell/msvc/mongo.vcxproj
+++ /dev/null
@@ -1,262 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup Label="ProjectConfigurations">
- <ProjectConfiguration Include="Debug|Win32">
- <Configuration>Debug</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|Win32">
- <Configuration>Release</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- </ItemGroup>
- <PropertyGroup Label="Globals">
- <ProjectGuid>{FE959BD8-8EE2-4555-AE59-9FA14FFD410E}</ProjectGuid>
- <Keyword>Win32Proj</Keyword>
- <RootNamespace>mongo</RootNamespace>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <CharacterSet>Unicode</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>Unicode</CharacterSet>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
- <ImportGroup Label="ExtensionSettings">
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <PropertyGroup Label="UserMacros" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <LinkIncremental>true</LinkIncremental>
- <LibraryPath>\boost\lib\vs2010_32\;$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib</LibraryPath>
- <ExecutablePath>$(VCInstallDir)bin;$(WindowsSdkDir)bin\NETFX 4.0 Tools;$(WindowsSdkDir)bin;$(VSInstallDir)Common7\Tools\bin;$(VSInstallDir)Common7\tools;$(VSInstallDir)Common7\ide;$(ProgramFiles)\HTML Help Workshop;$(FrameworkSDKDir)\bin;$(MSBuildToolsPath32);$(VSInstallDir);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
- <IncludePath>..\..\third_party\js-1.7;..\..\third_party\pcre-7.4;..\..\;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include</IncludePath>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <IncludePath>..\..\third_party\js-1.7;..\..\third_party\pcre-7.4;..\..\;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include</IncludePath>
- <LinkIncremental>false</LinkIncremental>
- <LibraryPath>\boost\lib\vs2010_32\;$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib</LibraryPath>
- </PropertyGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <ClCompile>
- <PrecompiledHeader>Use</PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;XP_WIN;HAVE_CONFIG_H;OLDJS;MONGO_EXPOSE_MACROS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>\boost\</AdditionalIncludeDirectories>
- <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
- <DisableSpecificWarnings>4355;4800;4267;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <AdditionalDependencies>ws2_32.lib;psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>Use</PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;XP_WIN;HAVE_CONFIG_H;OLDJS;MONGO_EXPOSE_MACROS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>\boost\</AdditionalIncludeDirectories>
- <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
- <MultiProcessorCompilation>true</MultiProcessorCompilation>
- <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
- <DisableSpecificWarnings>4355;4800;4267;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalDependencies>ws2_32.lib;psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemGroup>
- <ClCompile Include="..\..\bson\oid.cpp" />
- <ClCompile Include="..\..\client\clientOnly.cpp" />
- <ClCompile Include="..\..\client\connpool.cpp" />
- <ClCompile Include="..\..\client\dbclient_rs.cpp" />
- <ClCompile Include="..\..\client\syncclusterconnection.cpp" />
- <ClCompile Include="..\..\db\commands.cpp" />
- <ClCompile Include="..\..\db\lasterror.cpp" />
- <ClCompile Include="..\..\db\nonce.cpp" />
- <ClCompile Include="..\..\third_party\pcre-7.4\pcrecpp.cc">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_compile.c">
- <PrecompiledHeader>NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_config.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_chartables.c">
- <PrecompiledHeader>NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_stringpiece.cc">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\scripting\bench.cpp" />
- <ClCompile Include="..\..\scripting\engine_spidermonkey.cpp" />
- <ClCompile Include="..\..\scripting\utils.cpp" />
- <ClCompile Include="..\..\s\shardconnection.cpp" />
- <ClCompile Include="..\..\third_party\linenoise\linenoise.cpp">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\util\background.cpp" />
- <ClCompile Include="..\..\util\concurrency\spin_lock.cpp" />
- <ClCompile Include="..\..\util\log.cpp" />
- <ClCompile Include="..\..\util\mmap.cpp" />
- <ClCompile Include="..\..\util\net\listen.cpp" />
- <ClCompile Include="..\..\util\net\message.cpp" />
- <ClCompile Include="..\..\util\net\message_port.cpp" />
- <ClCompile Include="..\..\util\net\sock.cpp" />
- <ClCompile Include="..\..\util\password.cpp" />
- <ClCompile Include="..\..\util\ramlog.cpp" />
- <ClCompile Include="..\..\util\text.cpp" />
- <ClCompile Include="..\..\util\mmap_win.cpp" />
- <ClCompile Include="..\..\util\processinfo_win32.cpp" />
- <ClCompile Include="..\..\util\assert_util.cpp" />
- <ClCompile Include="..\..\util\md5main.cpp" />
- <ClCompile Include="..\..\util\md5.c">
- <PrecompiledHeader>NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\util\base64.cpp" />
- <ClCompile Include="..\..\util\debug_util.cpp" />
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_dfa_exec.c">
- <PrecompiledHeader>NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_exec.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_fullinfo.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_get.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_globals.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_info.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_maketables.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_newline.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_ord2utf8.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_refcount.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_study.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_tables.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_try_flipped.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_ucp_searchfuncs.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_valid_utf8.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_version.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_xclass.c">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\..\client\dbclient.cpp" />
- <ClCompile Include="..\..\client\dbclientcursor.cpp" />
- <ClCompile Include="..\..\db\common.cpp" />
- <ClCompile Include="..\..\db\jsobj.cpp" />
- <ClCompile Include="..\..\db\json.cpp" />
- <ClCompile Include="..\..\pch.cpp">
- <PrecompiledHeader>Create</PrecompiledHeader>
- <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
- </ClCompile>
- <ClCompile Include="..\..\scripting\engine.cpp" />
- <ClCompile Include="..\..\util\concurrency\vars.cpp" />
- <ClCompile Include="..\..\util\util.cpp" />
- <ClCompile Include="..\..\util\version.cpp" />
- <ClCompile Include="..\dbshell.cpp" />
- <ClCompile Include="..\mongo-server.cpp">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\mongo_vstudio.cpp">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- </ClCompile>
- <ClCompile Include="..\shell_utils.cpp" />
- </ItemGroup>
- <ItemGroup>
- <None Include="..\..\SConstruct" />
- <None Include="..\collection.js" />
- <None Include="..\db.js" />
- <None Include="..\mongo.js" />
- <None Include="..\mr.js" />
- <None Include="..\query.js" />
- <None Include="..\servers.js" />
- <None Include="..\utils.js" />
- </ItemGroup>
- <ItemGroup>
- <Library Include="..\..\..\js\js32d.lib">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
- </Library>
- <Library Include="..\..\..\js\js32r.lib">
- <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
- </Library>
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="..\..\db\lasterror.h" />
- </ItemGroup>
- <ItemGroup>
- <ResourceCompile Include="..\..\db\db.rc" />
- </ItemGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
- <ImportGroup Label="ExtensionTargets">
- </ImportGroup>
-</Project> \ No newline at end of file
diff --git a/shell/msvc/mongo.vcxproj.filters b/shell/msvc/mongo.vcxproj.filters
deleted file mode 100644
index 15c6295cdb4..00000000000
--- a/shell/msvc/mongo.vcxproj.filters
+++ /dev/null
@@ -1,288 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup>
- <Filter Include="Resource Files">
- <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
- <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
- </Filter>
- <Filter Include="util">
- <UniqueIdentifier>{2a0d6120-434d-4732-ac31-2a7bf077f6ee}</UniqueIdentifier>
- </Filter>
- <Filter Include="util\concurrency">
- <UniqueIdentifier>{a1e59094-b70c-463a-8dc1-691efe337f14}</UniqueIdentifier>
- </Filter>
- <Filter Include="scripting">
- <UniqueIdentifier>{2d0fd975-0cc9-43dc-ac8e-53cb8c3a0040}</UniqueIdentifier>
- </Filter>
- <Filter Include="bson">
- <UniqueIdentifier>{a33442e2-39da-4c70-8310-6de9fa70cd71}</UniqueIdentifier>
- </Filter>
- <Filter Include="db">
- <UniqueIdentifier>{1044ce7b-72c4-4892-82c0-f46d8708a6ff}</UniqueIdentifier>
- </Filter>
- <Filter Include="client">
- <UniqueIdentifier>{fc0f6c1a-9627-4254-9b5e-0bcb8b3257f3}</UniqueIdentifier>
- </Filter>
- <Filter Include="shared source files">
- <UniqueIdentifier>{30b62472-d7a7-4b8a-8a07-d7d341bc6252}</UniqueIdentifier>
- </Filter>
- <Filter Include="pcre">
- <UniqueIdentifier>{291e0d72-13ca-42d7-b0fd-2e7b5f89639f}</UniqueIdentifier>
- </Filter>
- <Filter Include="shell">
- <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
- <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
- </Filter>
- <Filter Include="_js files">
- <UniqueIdentifier>{473e7192-9f2a-47c5-ad95-e5b75d4f48f9}</UniqueIdentifier>
- </Filter>
- <Filter Include="shell\generated_from_js">
- <UniqueIdentifier>{96e4c411-7ab4-4bcd-b7c6-a33059f5d492}</UniqueIdentifier>
- </Filter>
- <Filter Include="thirdparty">
- <UniqueIdentifier>{5eca87ab-5987-4fb0-97be-e80cc721e328}</UniqueIdentifier>
- </Filter>
- <Filter Include="util\net">
- <UniqueIdentifier>{a672576c-7b77-4950-b04e-7d2c65784bf5}</UniqueIdentifier>
- </Filter>
- </ItemGroup>
- <ItemGroup>
- <ClCompile Include="..\dbshell.cpp">
- <Filter>shell</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\version.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\concurrency\vars.cpp">
- <Filter>util\concurrency</Filter>
- </ClCompile>
- <ClCompile Include="..\..\scripting\engine.cpp">
- <Filter>scripting</Filter>
- </ClCompile>
- <ClCompile Include="..\..\db\jsobj.cpp">
- <Filter>db</Filter>
- </ClCompile>
- <ClCompile Include="..\..\client\dbclient.cpp">
- <Filter>client</Filter>
- </ClCompile>
- <ClCompile Include="..\..\client\dbclientcursor.cpp">
- <Filter>client</Filter>
- </ClCompile>
- <ClCompile Include="..\..\pch.cpp" />
- <ClCompile Include="..\..\client\connpool.cpp">
- <Filter>client</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\processinfo_win32.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\db\commands.cpp">
- <Filter>db</Filter>
- </ClCompile>
- <ClCompile Include="..\..\scripting\utils.cpp">
- <Filter>scripting</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\assert_util.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\background.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\base64.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\client\clientOnly.cpp">
- <Filter>client</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\mmap.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\md5main.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\util.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\client\syncclusterconnection.cpp">
- <Filter>client</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\mmap_win.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\s\shardconnection.cpp">
- <Filter>shared source files</Filter>
- </ClCompile>
- <ClCompile Include="..\shell_utils.cpp">
- <Filter>shell</Filter>
- </ClCompile>
- <ClCompile Include="..\..\scripting\engine_spidermonkey.cpp">
- <Filter>scripting</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\password.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\db\common.cpp">
- <Filter>db</Filter>
- </ClCompile>
- <ClCompile Include="..\mongo_vstudio.cpp">
- <Filter>shell\generated_from_js</Filter>
- </ClCompile>
- <ClCompile Include="..\mongo-server.cpp">
- <Filter>shell\generated_from_js</Filter>
- </ClCompile>
- <ClCompile Include="..\..\scripting\bench.cpp">
- <Filter>scripting</Filter>
- </ClCompile>
- <ClCompile Include="..\..\bson\oid.cpp">
- <Filter>bson</Filter>
- </ClCompile>
- <ClCompile Include="..\..\client\dbclient_rs.cpp">
- <Filter>client</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\linenoise\linenoise.cpp">
- <Filter>thirdparty</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\concurrency\spin_lock.cpp">
- <Filter>util\concurrency</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_compile.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_config.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_dfa_exec.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_exec.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_fullinfo.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_get.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_globals.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_info.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_maketables.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_newline.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_ord2utf8.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_refcount.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_stringpiece.cc">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_study.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_tables.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_try_flipped.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_ucp_searchfuncs.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_valid_utf8.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_version.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_xclass.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcrecpp.cc">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\db\json.cpp">
- <Filter>db</Filter>
- </ClCompile>
- <ClCompile Include="..\..\db\lasterror.cpp">
- <Filter>db</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\log.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\db\nonce.cpp">
- <Filter>db</Filter>
- </ClCompile>
- <ClCompile Include="..\..\third_party\pcre-7.4\pcre_chartables.c">
- <Filter>pcre</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\debug_util.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\md5.c">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\text.cpp">
- <Filter>util</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\net\listen.cpp">
- <Filter>util\net</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\net\message.cpp">
- <Filter>util\net</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\net\message_port.cpp">
- <Filter>util\net</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\net\sock.cpp">
- <Filter>util\net</Filter>
- </ClCompile>
- <ClCompile Include="..\..\util\ramlog.cpp">
- <Filter>util</Filter>
- </ClCompile>
- </ItemGroup>
- <ItemGroup>
- <None Include="..\..\SConstruct" />
- <None Include="..\collection.js">
- <Filter>_js files</Filter>
- </None>
- <None Include="..\db.js">
- <Filter>_js files</Filter>
- </None>
- <None Include="..\mongo.js">
- <Filter>_js files</Filter>
- </None>
- <None Include="..\mr.js">
- <Filter>_js files</Filter>
- </None>
- <None Include="..\query.js">
- <Filter>_js files</Filter>
- </None>
- <None Include="..\servers.js">
- <Filter>_js files</Filter>
- </None>
- <None Include="..\utils.js">
- <Filter>_js files</Filter>
- </None>
- </ItemGroup>
- <ItemGroup>
- <Library Include="..\..\..\js\js32d.lib" />
- <Library Include="..\..\..\js\js32r.lib" />
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="..\..\db\lasterror.h">
- <Filter>db</Filter>
- </ClInclude>
- </ItemGroup>
- <ItemGroup>
- <ResourceCompile Include="..\..\db\db.rc">
- <Filter>Resource Files</Filter>
- </ResourceCompile>
- </ItemGroup>
-</Project> \ No newline at end of file
diff --git a/shell/query.js b/shell/query.js
deleted file mode 100644
index 78734caf44e..00000000000
--- a/shell/query.js
+++ /dev/null
@@ -1,317 +0,0 @@
-// query.js
-
-if ( typeof DBQuery == "undefined" ){
- DBQuery = function( mongo , db , collection , ns , query , fields , limit , skip , batchSize , options ){
-
- this._mongo = mongo; // 0
- this._db = db; // 1
- this._collection = collection; // 2
- this._ns = ns; // 3
-
- this._query = query || {}; // 4
- this._fields = fields; // 5
- this._limit = limit || 0; // 6
- this._skip = skip || 0; // 7
- this._batchSize = batchSize || 0;
- this._options = options || 0;
-
- this._cursor = null;
- this._numReturned = 0;
- this._special = false;
- this._prettyShell = false;
- }
- print( "DBQuery probably won't have array access " );
-}
-
-DBQuery.prototype.help = function () {
- print("find() modifiers")
- print("\t.sort( {...} )")
- print("\t.limit( n )")
- print("\t.skip( n )")
- print("\t.count() - total # of objects matching query, ignores skip,limit")
- print("\t.size() - total # of objects cursor would return, honors skip,limit")
- print("\t.explain([verbose])")
- print("\t.hint(...)")
- print("\t.showDiskLoc() - adds a $diskLoc field to each returned object")
- print("\nCursor methods");
- print("\t.forEach( func )")
- print("\t.map( func )")
- print("\t.hasNext()")
- print("\t.next()")
-}
-
-DBQuery.prototype.clone = function(){
- var q = new DBQuery( this._mongo , this._db , this._collection , this._ns ,
- this._query , this._fields ,
- this._limit , this._skip , this._batchSize , this._options );
- q._special = this._special;
- return q;
-}
-
-DBQuery.prototype._ensureSpecial = function(){
- if ( this._special )
- return;
-
- var n = { query : this._query };
- this._query = n;
- this._special = true;
-}
-
-DBQuery.prototype._checkModify = function(){
- if ( this._cursor )
- throw "query already executed";
-}
-
-DBQuery.prototype._exec = function(){
- if ( ! this._cursor ){
- assert.eq( 0 , this._numReturned );
- this._cursor = this._mongo.find( this._ns , this._query , this._fields , this._limit , this._skip , this._batchSize , this._options );
- this._cursorSeen = 0;
- }
- return this._cursor;
-}
-
-DBQuery.prototype.limit = function( limit ){
- this._checkModify();
- this._limit = limit;
- return this;
-}
-
-DBQuery.prototype.batchSize = function( batchSize ){
- this._checkModify();
- this._batchSize = batchSize;
- return this;
-}
-
-
-DBQuery.prototype.addOption = function( option ){
- this._options |= option;
- return this;
-}
-
-DBQuery.prototype.skip = function( skip ){
- this._checkModify();
- this._skip = skip;
- return this;
-}
-
-DBQuery.prototype.hasNext = function(){
- this._exec();
-
- if ( this._limit > 0 && this._cursorSeen >= this._limit )
- return false;
- var o = this._cursor.hasNext();
- return o;
-}
-
-DBQuery.prototype.next = function(){
- this._exec();
-
- var o = this._cursor.hasNext();
- if ( o )
- this._cursorSeen++;
- else
- throw "error hasNext: " + o;
-
- var ret = this._cursor.next();
- if ( ret.$err && this._numReturned == 0 && ! this.hasNext() )
- throw "error: " + tojson( ret );
-
- this._numReturned++;
- return ret;
-}
-
-DBQuery.prototype.objsLeftInBatch = function(){
- this._exec();
-
- var ret = this._cursor.objsLeftInBatch();
- if ( ret.$err )
- throw "error: " + tojson( ret );
-
- return ret;
-}
-
-DBQuery.prototype.toArray = function(){
- if ( this._arr )
- return this._arr;
-
- var a = [];
- while ( this.hasNext() )
- a.push( this.next() );
- this._arr = a;
- return a;
-}
-
-DBQuery.prototype.count = function( applySkipLimit ){
- var cmd = { count: this._collection.getName() };
- if ( this._query ){
- if ( this._special )
- cmd.query = this._query.query;
- else
- cmd.query = this._query;
- }
- cmd.fields = this._fields || {};
-
- if ( applySkipLimit ){
- if ( this._limit )
- cmd.limit = this._limit;
- if ( this._skip )
- cmd.skip = this._skip;
- }
-
- var res = this._db.runCommand( cmd );
- if( res && res.n != null ) return res.n;
- throw "count failed: " + tojson( res );
-}
-
-DBQuery.prototype.size = function(){
- return this.count( true );
-}
-
-DBQuery.prototype.countReturn = function(){
- var c = this.count();
-
- if ( this._skip )
- c = c - this._skip;
-
- if ( this._limit > 0 && this._limit < c )
- return this._limit;
-
- return c;
-}
-
-/**
-* iterative count - only for testing
-*/
-DBQuery.prototype.itcount = function(){
- var num = 0;
- while ( this.hasNext() ){
- num++;
- this.next();
- }
- return num;
-}
-
-DBQuery.prototype.length = function(){
- return this.toArray().length;
-}
-
-DBQuery.prototype._addSpecial = function( name , value ){
- this._ensureSpecial();
- this._query[name] = value;
- return this;
-}
-
-DBQuery.prototype.sort = function( sortBy ){
- return this._addSpecial( "orderby" , sortBy );
-}
-
-DBQuery.prototype.hint = function( hint ){
- return this._addSpecial( "$hint" , hint );
-}
-
-DBQuery.prototype.min = function( min ) {
- return this._addSpecial( "$min" , min );
-}
-
-DBQuery.prototype.max = function( max ) {
- return this._addSpecial( "$max" , max );
-}
-
-DBQuery.prototype.showDiskLoc = function() {
- return this._addSpecial( "$showDiskLoc" , true);
-}
-
-DBQuery.prototype.forEach = function( func ){
- while ( this.hasNext() )
- func( this.next() );
-}
-
-DBQuery.prototype.map = function( func ){
- var a = [];
- while ( this.hasNext() )
- a.push( func( this.next() ) );
- return a;
-}
-
-DBQuery.prototype.arrayAccess = function( idx ){
- return this.toArray()[idx];
-}
-
-DBQuery.prototype.explain = function (verbose) {
- /* verbose=true --> include allPlans, oldPlan fields */
- var n = this.clone();
- n._ensureSpecial();
- n._query.$explain = true;
- n._limit = Math.abs(n._limit) * -1;
- var e = n.next();
-
- function cleanup(obj){
- if (typeof(obj) != 'object'){
- return;
- }
-
- delete obj.allPlans;
- delete obj.oldPlan;
-
- if (typeof(obj.length) == 'number'){
- for (var i=0; i < obj.length; i++){
- cleanup(obj[i]);
- }
- }
-
- if (obj.shards){
- for (var key in obj.shards){
- cleanup(obj.shards[key]);
- }
- }
-
- if (obj.clauses){
- cleanup(obj.clauses);
- }
- }
-
- if (!verbose)
- cleanup(e);
-
- return e;
-}
-
-DBQuery.prototype.snapshot = function(){
- this._ensureSpecial();
- this._query.$snapshot = true;
- return this;
-}
-
-DBQuery.prototype.pretty = function(){
- this._prettyShell = true;
- return this;
-}
-
-DBQuery.prototype.shellPrint = function(){
- try {
- var n = 0;
- while ( this.hasNext() && n < DBQuery.shellBatchSize ){
- var s = this._prettyShell ? tojson( this.next() ) : tojson( this.next() , "" , true );
- print( s );
- n++;
- }
- if ( this.hasNext() ){
- print( "has more" );
- ___it___ = this;
- }
- else {
- ___it___ = null;
- }
- }
- catch ( e ){
- print( e );
- }
-
-}
-
-DBQuery.prototype.toString = function(){
- return "DBQuery: " + this._ns + " -> " + tojson( this.query );
-}
-
-DBQuery.shellBatchSize = 20;
diff --git a/shell/servers.js b/shell/servers.js
deleted file mode 100755
index efbd9b66dae..00000000000
--- a/shell/servers.js
+++ /dev/null
@@ -1,2052 +0,0 @@
-_parsePath = function() {
- var dbpath = "";
- for( var i = 0; i < arguments.length; ++i )
- if ( arguments[ i ] == "--dbpath" )
- dbpath = arguments[ i + 1 ];
-
- if ( dbpath == "" )
- throw "No dbpath specified";
-
- return dbpath;
-}
-
-_parsePort = function() {
- var port = "";
- for( var i = 0; i < arguments.length; ++i )
- if ( arguments[ i ] == "--port" )
- port = arguments[ i + 1 ];
-
- if ( port == "" )
- throw "No port specified";
- return port;
-}
-
-connectionURLTheSame = function( a , b ){
- if ( a == b )
- return true;
-
- if ( ! a || ! b )
- return false;
-
- a = a.split( "/" )[0]
- b = b.split( "/" )[0]
-
- return a == b;
-}
-
-assert( connectionURLTheSame( "foo" , "foo" ) )
-assert( ! connectionURLTheSame( "foo" , "bar" ) )
-
-assert( connectionURLTheSame( "foo/a,b" , "foo/b,a" ) )
-assert( ! connectionURLTheSame( "foo/a,b" , "bar/a,b" ) )
-
-createMongoArgs = function( binaryName , args ){
- var fullArgs = [ binaryName ];
-
- if ( args.length == 1 && isObject( args[0] ) ){
- var o = args[0];
- for ( var k in o ){
- if ( o.hasOwnProperty(k) ){
- if ( k == "v" && isNumber( o[k] ) ){
- var n = o[k];
- if ( n > 0 ){
- if ( n > 10 ) n = 10;
- var temp = "-";
- while ( n-- > 0 ) temp += "v";
- fullArgs.push( temp );
- }
- }
- else {
- fullArgs.push( "--" + k );
- if ( o[k] != "" )
- fullArgs.push( "" + o[k] );
- }
- }
- }
- }
- else {
- for ( var i=0; i<args.length; i++ )
- fullArgs.push( args[i] )
- }
-
- return fullArgs;
-}
-
-__nextPort = 27000;
-startMongodTest = function (port, dirname, restart, extraOptions ) {
- if (!port)
- port = __nextPort++;
- var f = startMongodEmpty;
- if (restart)
- f = startMongodNoReset;
- if (!dirname)
- dirname = "" + port; // e.g., data/db/27000
-
- var useHostname = false;
- if (extraOptions) {
- useHostname = extraOptions.useHostname;
- delete extraOptions.useHostname;
- }
-
-
- var options =
- {
- port: port,
- dbpath: "/data/db/" + dirname,
- noprealloc: "",
- smallfiles: "",
- oplogSize: "40",
- nohttpinterface: ""
- };
-
- if( jsTestOptions().noJournal ) options["nojournal"] = ""
- if( jsTestOptions().noJournalPrealloc ) options["nopreallocj"] = ""
-
- if ( extraOptions )
- Object.extend( options , extraOptions );
-
- var conn = f.apply(null, [ options ] );
-
- conn.name = (useHostname ? getHostName() : "localhost") + ":" + port;
- return conn;
-}
-
-// Start a mongod instance and return a 'Mongo' object connected to it.
-// This function's arguments are passed as command line arguments to mongod.
-// The specified 'dbpath' is cleared if it exists, created if not.
-// var conn = startMongodEmpty("--port", 30000, "--dbpath", "asdf");
-startMongodEmpty = function () {
- var args = createMongoArgs("mongod", arguments);
-
- var dbpath = _parsePath.apply(null, args);
- resetDbpath(dbpath);
-
- return startMongoProgram.apply(null, args);
-}
-startMongod = function () {
- print("startMongod WARNING DELETES DATA DIRECTORY THIS IS FOR TESTING ONLY");
- return startMongodEmpty.apply(null, arguments);
-}
-startMongodNoReset = function(){
- var args = createMongoArgs( "mongod" , arguments );
- return startMongoProgram.apply( null, args );
-}
-
-startMongos = function(){
- return startMongoProgram.apply( null, createMongoArgs( "mongos" , arguments ) );
-}
-
-/* Start mongod or mongos and return a Mongo() object connected to there.
- This function's first argument is "mongod" or "mongos" program name, \
- and subsequent arguments to this function are passed as
- command line arguments to the program.
-*/
-startMongoProgram = function(){
- var port = _parsePort.apply( null, arguments );
-
- _startMongoProgram.apply( null, arguments );
-
- var m;
- assert.soon
- ( function() {
- try {
- m = new Mongo( "127.0.0.1:" + port );
- return true;
- } catch( e ) {
- }
- return false;
- }, "unable to connect to mongo program on port " + port, 600 * 1000 );
-
- return m;
-}
-
-// Start a mongo program instance. This function's first argument is the
-// program name, and subsequent arguments to this function are passed as
-// command line arguments to the program. Returns pid of the spawned program.
-startMongoProgramNoConnect = function() {
- return _startMongoProgram.apply( null, arguments );
-}
-
-myPort = function() {
- var m = db.getMongo();
- if ( m.host.match( /:/ ) )
- return m.host.match( /:(.*)/ )[ 1 ];
- else
- return 27017;
-}
-
-/**
- * otherParams can be:
- * * useHostname to use the hostname (instead of localhost)
- */
-ShardingTest = function( testName , numShards , verboseLevel , numMongos , otherParams ){
-
- // Check if testName is an object, if so, pull params from there
- var keyFile = undefined
- if( testName && ! testName.charAt ){
- var params = testName
- testName = params.name || "test"
- numShards = params.shards || 2
- verboseLevel = params.verbose || 0
- numMongos = params.mongos || 1
- otherParams = params.other || {}
- keyFile = params.keyFile || otherParams.keyFile
- }
-
- this._testName = testName;
-
- if ( ! otherParams )
- otherParams = {}
- this._connections = [];
-
- if ( otherParams.sync && numShards < 3 )
- throw "if you want sync, you need at least 3 servers";
-
- var localhost = otherParams.useHostname ? getHostName() : "localhost";
-
- this._alldbpaths = []
-
- if ( otherParams.rs ){
- localhost = getHostName();
- // start replica sets
- this._rs = []
- for ( var i=0; i<numShards; i++){
- var setName = testName + "-rs" + i;
-
- var rsDefaults = { oplogSize : 40, nodes : 3 }
- var rsParams = otherParams["rs" + i]
-
- for( var param in rsParams ){
- rsDefaults[param] = rsParams[param]
- }
-
- var numReplicas = rsDefaults.nodes || otherParams.numReplicas || 3
- delete rsDefaults.nodes
-
- var rs = new ReplSetTest( { name : setName , nodes : numReplicas , startPort : 31100 + ( i * 100 ), keyFile : keyFile } );
- this._rs[i] = { setName : setName , test : rs , nodes : rs.startSet( rsDefaults ) , url : rs.getURL() };
- rs.initiate();
-
- }
-
- for ( var i=0; i<numShards; i++){
- var rs = this._rs[i].test;
- rs.getMaster().getDB( "admin" ).foo.save( { x : 1 } )
- rs.awaitReplication();
- var xxx = new Mongo( rs.getURL() );
- xxx.name = rs.getURL();
- this._connections.push( xxx )
- this["shard" + i] = xxx
- }
-
- this._configServers = []
- for ( var i=0; i<3; i++ ){
- var options = otherParams.extraOptions
- if( keyFile ) options["keyFile"] = keyFile
- var conn = startMongodTest( 30000 + i , testName + "-config" + i, false, options );
- this._alldbpaths.push( testName + "-config" + i )
- this._configServers.push( conn );
- }
-
- this._configDB = localhost + ":30000," + localhost + ":30001," + localhost + ":30002";
- this._configConnection = new Mongo( this._configDB );
- if (!otherParams.noChunkSize) {
- this._configConnection.getDB( "config" ).settings.insert( { _id : "chunksize" , value : otherParams.chunksize || 50 } );
- }
- }
- else {
- for ( var i=0; i<numShards; i++){
- var options = { useHostname : otherParams.useHostname }
- if( keyFile ) options["keyFile"] = keyFile
- var conn = startMongodTest( 30000 + i , testName + i, 0, options );
- this._alldbpaths.push( testName +i )
- this._connections.push( conn );
- this["shard" + i] = conn
- }
-
- if ( otherParams.sync ){
- this._configDB = localhost+":30000,"+localhost+":30001,"+localhost+":30002";
- this._configConnection = new Mongo( this._configDB );
- this._configConnection.getDB( "config" ).settings.insert( { _id : "chunksize" , value : otherParams.chunksize || 50 } );
- }
- else {
- this._configDB = localhost + ":30000";
- this._connections[0].getDB( "config" ).settings.insert( { _id : "chunksize" , value : otherParams.chunksize || 50 } );
- }
- }
-
- this._mongos = [];
- var startMongosPort = 31000;
- for ( var i=0; i<(numMongos||1); i++ ){
- var myPort = startMongosPort - i;
- print("ShardingTest config: "+this._configDB);
- var opts = { port : startMongosPort - i , v : verboseLevel || 0 , configdb : this._configDB };
- if( keyFile ) opts["keyFile"] = keyFile
- for (var j in otherParams.extraOptions) {
- opts[j] = otherParams.extraOptions[j];
- }
- var conn = startMongos( opts );
- conn.name = localhost + ":" + myPort;
- this._mongos.push( conn );
- if ( i == 0 ) {
- this.s = conn;
- }
- this["s" + i] = conn
- }
-
- var admin = this.admin = this.s.getDB( "admin" );
- this.config = this.s.getDB( "config" );
-
- if ( ! otherParams.manualAddShard ){
- this._connections.forEach(
- function(z){
- var n = z.name;
- if ( ! n ){
- n = z.host;
- if ( ! n )
- n = z;
- }
- print( "ShardingTest going to add shard: " + n )
- x = admin.runCommand( { addshard : n } );
- printjson( x )
- }
- );
- }
-}
-
-ShardingTest.prototype.getRSEntry = function( setName ){
- for ( var i=0; i<this._rs.length; i++ )
- if ( this._rs[i].setName == setName )
- return this._rs[i];
- throw "can't find rs: " + setName;
-}
-
-ShardingTest.prototype.getDB = function( name ){
- return this.s.getDB( name );
-}
-
-ShardingTest.prototype.getServerName = function( dbname ){
- var x = this.config.databases.findOne( { _id : "" + dbname } );
- if ( x )
- return x.primary;
- this.config.databases.find().forEach( printjson );
- throw "couldn't find dbname: " + dbname + " total: " + this.config.databases.count();
-}
-
-
-ShardingTest.prototype.getNonPrimaries = function( dbname ){
- var x = this.config.databases.findOne( { _id : dbname } );
- if ( ! x ){
- this.config.databases.find().forEach( printjson );
- throw "couldn't find dbname: " + dbname + " total: " + this.config.databases.count();
- }
-
- return this.config.shards.find( { _id : { $ne : x.primary } } ).map( function(z){ return z._id; } )
-}
-
-
-ShardingTest.prototype.getConnNames = function(){
- var names = [];
- for ( var i=0; i<this._connections.length; i++ ){
- names.push( this._connections[i].name );
- }
- return names;
-}
-
-ShardingTest.prototype.getServer = function( dbname ){
- var name = this.getServerName( dbname );
-
- var x = this.config.shards.findOne( { _id : name } );
- if ( x )
- name = x.host;
-
- var rsName = null;
- if ( name.indexOf( "/" ) > 0 )
- rsName = name.substring( 0 , name.indexOf( "/" ) );
-
- for ( var i=0; i<this._connections.length; i++ ){
- var c = this._connections[i];
- if ( connectionURLTheSame( name , c.name ) ||
- connectionURLTheSame( rsName , c.name ) )
- return c;
- }
-
- throw "can't find server for: " + dbname + " name:" + name;
-
-}
-
-ShardingTest.prototype.normalize = function( x ){
- var z = this.config.shards.findOne( { host : x } );
- if ( z )
- return z._id;
- return x;
-}
-
-ShardingTest.prototype.getOther = function( one ){
- if ( this._connections.length < 2 )
- throw "getOther only works with 2 servers";
-
- if ( one._mongo )
- one = one._mongo
-
- for( var i = 0; i < this._connections.length; i++ ){
- if( this._connections[i] != one ) return this._connections[i]
- }
-
- return null
-}
-
-ShardingTest.prototype.getAnother = function( one ){
- if(this._connections.length < 2)
- throw "getAnother() only works with multiple servers";
-
- if ( one._mongo )
- one = one._mongo
-
- for(var i = 0; i < this._connections.length; i++){
- if(this._connections[i] == one)
- return this._connections[(i + 1) % this._connections.length];
- }
-}
-
-ShardingTest.prototype.getFirstOther = function( one ){
- for ( var i=0; i<this._connections.length; i++ ){
- if ( this._connections[i] != one )
- return this._connections[i];
- }
- throw "impossible";
-}
-
-ShardingTest.prototype.stop = function(){
- for ( var i=0; i<this._mongos.length; i++ ){
- stopMongoProgram( 31000 - i );
- }
- for ( var i=0; i<this._connections.length; i++){
- stopMongod( 30000 + i );
- }
- if ( this._rs ){
- for ( var i=0; i<this._rs.length; i++ ){
- this._rs[i].test.stopSet( 15 );
- }
- }
- if ( this._alldbpaths ){
- for( i=0; i<this._alldbpaths.length; i++ ){
- resetDbpath( "/data/db/" + this._alldbpaths[i] );
- }
- }
-
- print('*** ShardingTest ' + this._testName + " completed successfully ***");
-}
-
-ShardingTest.prototype.adminCommand = function(cmd){
- var res = this.admin.runCommand( cmd );
- if ( res && res.ok == 1 )
- return true;
-
- throw "command " + tojson( cmd ) + " failed: " + tojson( res );
-}
-
-ShardingTest.prototype._rangeToString = function(r){
- return tojsononeline( r.min ) + " -> " + tojsononeline( r.max );
-}
-
-ShardingTest.prototype.printChangeLog = function(){
- var s = this;
- this.config.changelog.find().forEach(
- function(z){
- var msg = z.server + "\t" + z.time + "\t" + z.what;
- for ( i=z.what.length; i<15; i++ )
- msg += " ";
- msg += " " + z.ns + "\t";
- if ( z.what == "split" ){
- msg += s._rangeToString( z.details.before ) + " -->> (" + s._rangeToString( z.details.left ) + "),(" + s._rangeToString( z.details.right ) + ")";
- }
- else if (z.what == "multi-split" ){
- msg += s._rangeToString( z.details.before ) + " -->> (" + z.details.number + "/" + z.details.of + " " + s._rangeToString( z.details.chunk ) + ")";
- }
- else {
- msg += tojsononeline( z.details );
- }
-
- print( "ShardingTest " + msg )
- }
- );
-
-}
-
-ShardingTest.prototype.getChunksString = function( ns ){
- var q = {}
- if ( ns )
- q.ns = ns;
-
- var s = "";
- this.config.chunks.find( q ).sort( { ns : 1 , min : 1 } ).forEach(
- function(z){
- s += " " + z._id + "\t" + z.lastmod.t + "|" + z.lastmod.i + "\t" + tojson(z.min) + " -> " + tojson(z.max) + " " + z.shard + " " + z.ns + "\n";
- }
- );
-
- return s;
-}
-
-ShardingTest.prototype.printChunks = function( ns ){
- print( "ShardingTest " + this.getChunksString( ns ) );
-}
-
-ShardingTest.prototype.printShardingStatus = function(){
- printShardingStatus( this.config );
-}
-
-ShardingTest.prototype.printCollectionInfo = function( ns , msg ){
- var out = "";
- if ( msg )
- out += msg + "\n";
- out += "sharding collection info: " + ns + "\n";
- for ( var i=0; i<this._connections.length; i++ ){
- var c = this._connections[i];
- out += " mongod " + c + " " + tojson( c.getCollection( ns ).getShardVersion() , " " , true ) + "\n";
- }
- for ( var i=0; i<this._mongos.length; i++ ){
- var c = this._mongos[i];
- out += " mongos " + c + " " + tojson( c.getCollection( ns ).getShardVersion() , " " , true ) + "\n";
- }
-
- out += this.getChunksString( ns );
-
- print( "ShardingTest " + out );
-}
-
-printShardingStatus = function( configDB , verbose ){
- if (configDB === undefined)
- configDB = db.getSisterDB('config')
-
- var version = configDB.getCollection( "version" ).findOne();
- if ( version == null ){
- print( "printShardingStatus: not a shard db!" );
- return;
- }
-
- var raw = "";
- var output = function(s){
- raw += s + "\n";
- }
- output( "--- Sharding Status --- " );
- output( " sharding version: " + tojson( configDB.getCollection( "version" ).findOne() ) );
-
- output( " shards:" );
- configDB.shards.find().sort( { _id : 1 } ).forEach(
- function(z){
- output( "\t" + tojsononeline( z ) );
- }
- );
-
- output( " databases:" );
- configDB.databases.find().sort( { name : 1 } ).forEach(
- function(db){
- output( "\t" + tojsononeline(db,"",true) );
-
- if (db.partitioned){
- configDB.collections.find( { _id : new RegExp( "^" + db._id + "\\." ) } ).sort( { _id : 1 } ).forEach(
- function( coll ){
- if ( coll.dropped == false ){
- output("\t\t" + coll._id + " chunks:");
-
- res = configDB.chunks.group( { cond : { ns : coll._id } , key : { shard : 1 } , reduce : function( doc , out ){ out.nChunks++; } , initial : { nChunks : 0 } } );
- var totalChunks = 0;
- res.forEach( function(z){
- totalChunks += z.nChunks;
- output( "\t\t\t\t" + z.shard + "\t" + z.nChunks );
- } )
-
- if ( totalChunks < 20 || verbose ){
- configDB.chunks.find( { "ns" : coll._id } ).sort( { min : 1 } ).forEach(
- function(chunk){
- output( "\t\t\t" + tojson( chunk.min ) + " -->> " + tojson( chunk.max ) +
- " on : " + chunk.shard + " " + tojson( chunk.lastmod ) );
- }
- );
- }
- else {
- output( "\t\t\ttoo many chunks to print, use verbose if you want to force print" );
- }
- }
- }
- )
- }
- }
- );
-
- print( raw );
-}
-
-printShardingSizes = function(){
- configDB = db.getSisterDB('config')
-
- var version = configDB.getCollection( "version" ).findOne();
- if ( version == null ){
- print( "printShardingSizes : not a shard db!" );
- return;
- }
-
- var raw = "";
- var output = function(s){
- raw += s + "\n";
- }
- output( "--- Sharding Status --- " );
- output( " sharding version: " + tojson( configDB.getCollection( "version" ).findOne() ) );
-
- output( " shards:" );
- var shards = {};
- configDB.shards.find().forEach(
- function(z){
- shards[z._id] = new Mongo(z.host);
- output( " " + tojson(z) );
- }
- );
-
- var saveDB = db;
- output( " databases:" );
- configDB.databases.find().sort( { name : 1 } ).forEach(
- function(db){
- output( "\t" + tojson(db,"",true) );
-
- if (db.partitioned){
- configDB.collections.find( { _id : new RegExp( "^" + db._id + "\." ) } ).sort( { _id : 1 } ).forEach(
- function( coll ){
- output("\t\t" + coll._id + " chunks:");
- configDB.chunks.find( { "ns" : coll._id } ).sort( { min : 1 } ).forEach(
- function(chunk){
- var mydb = shards[chunk.shard].getDB(db._id)
- var out = mydb.runCommand({dataSize: coll._id,
- keyPattern: coll.key,
- min: chunk.min,
- max: chunk.max });
- delete out.millis;
- delete out.ok;
-
- output( "\t\t\t" + tojson( chunk.min ) + " -->> " + tojson( chunk.max ) +
- " on : " + chunk.shard + " " + tojson( out ) );
-
- }
- );
- }
- )
- }
- }
- );
-
- print( raw );
-}
-
-ShardingTest.prototype.sync = function(){
- this.adminCommand( "connpoolsync" );
-}
-
-ShardingTest.prototype.onNumShards = function( collName , dbName ){
- this.sync(); // we should sync since we're going directly to mongod here
- dbName = dbName || "test";
- var num=0;
- for ( var i=0; i<this._connections.length; i++ )
- if ( this._connections[i].getDB( dbName ).getCollection( collName ).count() > 0 )
- num++;
- return num;
-}
-
-
-ShardingTest.prototype.shardCounts = function( collName , dbName ){
- this.sync(); // we should sync since we're going directly to mongod here
- dbName = dbName || "test";
- var counts = {}
- for ( var i=0; i<this._connections.length; i++ )
- counts[i] = this._connections[i].getDB( dbName ).getCollection( collName ).count();
- return counts;
-}
-
-ShardingTest.prototype.chunkCounts = function( collName , dbName ){
- dbName = dbName || "test";
- var x = {}
-
- s.config.shards.find().forEach(
- function(z){
- x[z._id] = 0;
- }
- );
-
- s.config.chunks.find( { ns : dbName + "." + collName } ).forEach(
- function(z){
- if ( x[z.shard] )
- x[z.shard]++
- else
- x[z.shard] = 1;
- }
- );
- return x;
-
-}
-
-ShardingTest.prototype.chunkDiff = function( collName , dbName ){
- var c = this.chunkCounts( collName , dbName );
- var min = 100000000;
- var max = 0;
- for ( var s in c ){
- if ( c[s] < min )
- min = c[s];
- if ( c[s] > max )
- max = c[s];
- }
- print( "ShardingTest input: " + tojson( c ) + " min: " + min + " max: " + max );
- return max - min;
-}
-
-ShardingTest.prototype.getShard = function( coll, query ){
- var shards = this.getShards( coll, query )
- assert.eq( shards.length, 1 )
- return shards[0]
-}
-
-// Returns the shards on which documents matching a particular query reside
-ShardingTest.prototype.getShards = function( coll, query ){
- if( ! coll.getDB )
- coll = this.s.getCollection( coll )
-
- var explain = coll.find( query ).explain()
-
- var shards = []
-
- if( explain.shards ){
-
- for( var shardName in explain.shards ){
- for( var i = 0; i < explain.shards[shardName].length; i++ ){
- if( explain.shards[shardName][i].n && explain.shards[shardName][i].n > 0 )
- shards.push( shardName )
- }
- }
-
- }
-
- for( var i = 0; i < shards.length; i++ ){
- for( var j = 0; j < this._connections.length; j++ ){
- if ( connectionURLTheSame( this._connections[j].name , shards[i] ) ){
- shards[i] = this._connections[j]
- break;
- }
- }
- }
-
- return shards
-}
-
-ShardingTest.prototype.isSharded = function( collName ){
-
- var collName = "" + collName
- var dbName = undefined
-
- if( typeof collName.getCollectionNames == 'function' ){
- dbName = "" + collName
- collName = undefined
- }
-
- if( dbName ){
- var x = this.config.databases.findOne( { _id : dbname } )
- if( x ) return x.partitioned
- else return false
- }
-
- if( collName ){
- var x = this.config.collections.findOne( { _id : collName } )
- if( x ) return true
- else return false
- }
-
-}
-
-ShardingTest.prototype.shardGo = function( collName , key , split , move , dbName ){
-
- split = ( split != false ? ( split || key ) : split )
- move = ( split != false && move != false ? ( move || split ) : false )
-
- if( collName.getDB )
- dbName = "" + collName.getDB()
- else dbName = dbName || "test";
-
- var c = dbName + "." + collName;
- if( collName.getDB )
- c = "" + collName
-
- var isEmpty = this.s.getCollection( c ).count() == 0
-
- if( ! this.isSharded( dbName ) )
- this.s.adminCommand( { enableSharding : dbName } )
-
- var result = this.s.adminCommand( { shardcollection : c , key : key } )
- if( ! result.ok ){
- printjson( result )
- assert( false )
- }
-
- if( split == false ) return
-
- result = this.s.adminCommand( { split : c , middle : split } );
- if( ! result.ok ){
- printjson( result )
- assert( false )
- }
-
- if( move == false ) return
-
- var result = null
- for( var i = 0; i < 5; i++ ){
- result = this.s.adminCommand( { movechunk : c , find : move , to : this.getOther( this.getServer( dbName ) ).name } );
- if( result.ok ) break;
- sleep( 5 * 1000 );
- }
- printjson( result )
- assert( result.ok )
-
-};
-
-ShardingTest.prototype.shardColl = ShardingTest.prototype.shardGo
-
-ShardingTest.prototype.setBalancer = function( balancer ){
- if( balancer || balancer == undefined ){
- this.config.settings.update( { _id: "balancer" }, { $set : { stopped: false } } , true )
- }
- else if( balancer == false ){
- this.config.settings.update( { _id: "balancer" }, { $set : { stopped: true } } , true )
- }
-}
-
-/**
- * Run a mongod process.
- *
- * After initializing a MongodRunner, you must call start() on it.
- * @param {int} port port to run db on, use allocatePorts(num) to requision
- * @param {string} dbpath path to use
- * @param {boolean} peer pass in false (DEPRECATED, was used for replica pair host)
- * @param {boolean} arbiter pass in false (DEPRECATED, was used for replica pair host)
- * @param {array} extraArgs other arguments for the command line
- * @param {object} options other options include no_bind to not bind_ip to 127.0.0.1
- * (necessary for replica set testing)
- */
-MongodRunner = function( port, dbpath, peer, arbiter, extraArgs, options ) {
- this.port_ = port;
- this.dbpath_ = dbpath;
- this.peer_ = peer;
- this.arbiter_ = arbiter;
- this.extraArgs_ = extraArgs;
- this.options_ = options ? options : {};
-};
-
-/**
- * Start this mongod process.
- *
- * @param {boolean} reuseData If the data directory should be left intact (default is to wipe it)
- */
-MongodRunner.prototype.start = function( reuseData ) {
- var args = [];
- if ( reuseData ) {
- args.push( "mongod" );
- }
- args.push( "--port" );
- args.push( this.port_ );
- args.push( "--dbpath" );
- args.push( this.dbpath_ );
- args.push( "--nohttpinterface" );
- args.push( "--noprealloc" );
- args.push( "--smallfiles" );
- if (!this.options_.no_bind) {
- args.push( "--bind_ip" );
- args.push( "127.0.0.1" );
- }
- if ( this.extraArgs_ ) {
- args = args.concat( this.extraArgs_ );
- }
- removeFile( this.dbpath_ + "/mongod.lock" );
- if ( reuseData ) {
- return startMongoProgram.apply( null, args );
- } else {
- return startMongod.apply( null, args );
- }
-}
-
-MongodRunner.prototype.port = function() { return this.port_; }
-
-MongodRunner.prototype.toString = function() { return [ this.port_, this.dbpath_, this.peer_, this.arbiter_ ].toString(); }
-
-ToolTest = function( name ){
- this.name = name;
- this.port = allocatePorts(1)[0];
- this.baseName = "jstests_tool_" + name;
- this.root = "/data/db/" + this.baseName;
- this.dbpath = this.root + "/";
- this.ext = this.root + "_external/";
- this.extFile = this.root + "_external/a";
- resetDbpath( this.dbpath );
-}
-
-ToolTest.prototype.startDB = function( coll ){
- assert( ! this.m , "db already running" );
-
- this.m = startMongoProgram( "mongod" , "--port", this.port , "--dbpath" , this.dbpath , "--nohttpinterface", "--noprealloc" , "--smallfiles" , "--bind_ip", "127.0.0.1" );
- this.db = this.m.getDB( this.baseName );
- if ( coll )
- return this.db.getCollection( coll );
- return this.db;
-}
-
-ToolTest.prototype.stop = function(){
- if ( ! this.m )
- return;
- stopMongod( this.port );
- this.m = null;
- this.db = null;
-
- print('*** ' + this.name + " completed successfully ***");
-}
-
-ToolTest.prototype.runTool = function(){
- var a = [ "mongo" + arguments[0] ];
-
- var hasdbpath = false;
-
- for ( var i=1; i<arguments.length; i++ ){
- a.push( arguments[i] );
- if ( arguments[i] == "--dbpath" )
- hasdbpath = true;
- }
-
- if ( ! hasdbpath ){
- a.push( "--host" );
- a.push( "127.0.0.1:" + this.port );
- }
-
- return runMongoProgram.apply( null , a );
-}
-
-
-ReplTest = function( name, ports ){
- this.name = name;
- this.ports = ports || allocatePorts( 2 );
-}
-
-ReplTest.prototype.getPort = function( master ){
- if ( master )
- return this.ports[ 0 ];
- return this.ports[ 1 ]
-}
-
-ReplTest.prototype.getPath = function( master ){
- var p = "/data/db/" + this.name + "-";
- if ( master )
- p += "master";
- else
- p += "slave"
- return p;
-}
-
-ReplTest.prototype.getOptions = function( master , extra , putBinaryFirst, norepl ){
-
- if ( ! extra )
- extra = {};
-
- if ( ! extra.oplogSize )
- extra.oplogSize = "40";
-
- var a = []
- if ( putBinaryFirst )
- a.push( "mongod" )
- a.push( "--nohttpinterface", "--noprealloc", "--bind_ip" , "127.0.0.1" , "--smallfiles" );
-
- a.push( "--port" );
- a.push( this.getPort( master ) );
-
- a.push( "--dbpath" );
- a.push( this.getPath( master ) );
-
- if( jsTestOptions().noJournal ) a.push( "--nojournal" )
- if( jsTestOptions().noJournalPrealloc ) a.push( "--nopreallocj" )
-
- if ( !norepl ) {
- if ( master ){
- a.push( "--master" );
- }
- else {
- a.push( "--slave" );
- a.push( "--source" );
- a.push( "127.0.0.1:" + this.ports[0] );
- }
- }
-
- for ( var k in extra ){
- var v = extra[k];
- a.push( "--" + k );
- if ( v != null )
- a.push( v );
- }
-
- return a;
-}
-
-ReplTest.prototype.start = function( master , options , restart, norepl ){
- var lockFile = this.getPath( master ) + "/mongod.lock";
- removeFile( lockFile );
- var o = this.getOptions( master , options , restart, norepl );
-
-
- if ( restart )
- return startMongoProgram.apply( null , o );
- else
- return startMongod.apply( null , o );
-}
-
-ReplTest.prototype.stop = function( master , signal ){
- if ( arguments.length == 0 ){
- this.stop( true );
- this.stop( false );
- return;
- }
-
- print('*** ' + this.name + " completed successfully ***");
- return stopMongod( this.getPort( master ) , signal || 15 );
-}
-
-allocatePorts = function( n , startPort ) {
- var ret = [];
- var start = startPort || 31000;
- for( var i = start; i < start + n; ++i )
- ret.push( i );
- return ret;
-}
-
-
-SyncCCTest = function( testName , extraMongodOptions ){
- this._testName = testName;
- this._connections = [];
-
- for ( var i=0; i<3; i++ ){
- this._connections.push( startMongodTest( 30000 + i , testName + i , false, extraMongodOptions ) );
- }
-
- this.url = this._connections.map( function(z){ return z.name; } ).join( "," );
- this.conn = new Mongo( this.url );
-}
-
-SyncCCTest.prototype.stop = function(){
- for ( var i=0; i<this._connections.length; i++){
- stopMongod( 30000 + i );
- }
-
- print('*** ' + this._testName + " completed successfully ***");
-}
-
-SyncCCTest.prototype.checkHashes = function( dbname , msg ){
- var hashes = this._connections.map(
- function(z){
- return z.getDB( dbname ).runCommand( "dbhash" );
- }
- );
-
- for ( var i=1; i<hashes.length; i++ ){
- assert.eq( hashes[0].md5 , hashes[i].md5 , "checkHash on " + dbname + " " + msg + "\n" + tojson( hashes ) )
- }
-}
-
-SyncCCTest.prototype.tempKill = function( num ){
- num = num || 0;
- stopMongod( 30000 + num );
-}
-
-SyncCCTest.prototype.tempStart = function( num ){
- num = num || 0;
- this._connections[num] = startMongodTest( 30000 + num , this._testName + num , true );
-}
-
-
-function startParallelShell( jsCode, port ){
- assert( jsCode.indexOf( '"' ) == -1,
- "double quotes should not be used in jsCode because the windows shell will stip them out" );
- var x;
- if ( port ) {
- x = startMongoProgramNoConnect( "mongo" , "--port" , port , "--eval" , jsCode );
- } else {
- x = startMongoProgramNoConnect( "mongo" , "--eval" , jsCode , db ? db.getMongo().host : null );
- }
- return function(){
- waitProgram( x );
- };
-}
-
-var testingReplication = false;
-
-function skipIfTestingReplication(){
- if (testingReplication) {
- print("skipIfTestingReplication skipping");
- quit(0);
- }
-}
-
-ReplSetTest = function( opts ){
- this.name = opts.name || "testReplSet";
- this.host = opts.host || getHostName();
- this.numNodes = opts.nodes || 0;
- this.oplogSize = opts.oplogSize || 40;
- this.useSeedList = opts.useSeedList || false;
- this.bridged = opts.bridged || false;
- this.ports = [];
- this.keyFile = opts.keyFile
-
- this.startPort = opts.startPort || 31000;
-
- if(this.bridged) {
- this.bridgePorts = [];
-
- var allPorts = allocatePorts( this.numNodes * 2 , this.startPort );
- for(var i=0; i < this.numNodes; i++) {
- this.ports[i] = allPorts[i*2];
- this.bridgePorts[i] = allPorts[i*2 + 1];
- }
-
- this.initBridges();
- }
- else {
- this.ports = allocatePorts( this.numNodes , this.startPort );
- }
-
- this.nodes = [];
- this.nodeIds = {};
- this.initLiveNodes();
-
- Object.extend( this, ReplSetTest.Health )
- Object.extend( this, ReplSetTest.State )
-
-}
-
-ReplSetTest.prototype.initBridges = function() {
- for(var i=0; i<this.ports.length; i++) {
- startMongoProgram( "mongobridge", "--port", this.bridgePorts[i], "--dest", this.host + ":" + this.ports[i] );
- }
-}
-
-// List of nodes as host:port strings.
-ReplSetTest.prototype.nodeList = function() {
- var list = [];
- for(var i=0; i<this.ports.length; i++) {
- list.push( this.host + ":" + this.ports[i]);
- }
-
- return list;
-}
-
-// Here we store a reference to all reachable nodes.
-ReplSetTest.prototype.initLiveNodes = function(){
- this.liveNodes = {master: null, slaves: []};
- this.nodeIds = {};
-}
-
-ReplSetTest.prototype.getNodeId = function(node) {
-
- var result = this.nodeIds[node]
- if( result ) return result
-
- if( node.toFixed ) return node
- return node.nodeId
-
-}
-
-ReplSetTest.prototype.getPort = function( n ){
- if( n.getDB ){
- // is a connection, look up
- for( var i = 0; i < this.nodes.length; i++ ){
- if( this.nodes[i] == n ){
- n = i
- break
- }
- }
- }
-
- if ( typeof(n) == "object" && n.floatApprox )
- n = n.floatApprox
-
- // this is a hack for NumberInt
- if ( n == 0 )
- n = 0;
-
- print( "ReplSetTest n: " + n + " ports: " + tojson( this.ports ) + "\t" + this.ports[n] + " " + typeof(n) );
- return this.ports[ n ];
-}
-
-ReplSetTest.prototype.getPath = function( n ){
-
- if( n.host )
- n = this.getNodeId( n )
-
- var p = "/data/db/" + this.name + "-"+n;
- if ( ! this._alldbpaths )
- this._alldbpaths = [ p ];
- else
- this._alldbpaths.push( p );
- return p;
-}
-
-ReplSetTest.prototype.getReplSetConfig = function() {
- var cfg = {};
-
- cfg['_id'] = this.name;
- cfg.members = [];
-
- for(i=0; i<this.ports.length; i++) {
- member = {};
- member['_id'] = i;
-
- if(this.bridged)
- var port = this.bridgePorts[i];
- else
- var port = this.ports[i];
-
- member['host'] = this.host + ":" + port;
- cfg.members.push(member);
- }
-
- return cfg;
-}
-
-ReplSetTest.prototype.getURL = function(){
- var hosts = [];
-
- for(i=0; i<this.ports.length; i++) {
-
- // Don't include this node in the replica set list
- if(this.bridged && this.ports[i] == this.ports[n]) {
- continue;
- }
-
- var port;
- // Connect on the right port
- if(this.bridged) {
- port = this.bridgePorts[i];
- }
- else {
- port = this.ports[i];
- }
-
- var str = this.host + ":" + port;
- hosts.push(str);
- }
-
- return this.name + "/" + hosts.join(",");
-}
-
-ReplSetTest.prototype.getOptions = function( n , extra , putBinaryFirst ){
-
- if ( ! extra )
- extra = {};
-
- if ( ! extra.oplogSize )
- extra.oplogSize = this.oplogSize;
-
- var a = []
-
-
- if ( putBinaryFirst )
- a.push( "mongod" );
-
- if ( extra.noReplSet ) {
- delete extra.noReplSet;
- }
- else {
- a.push( "--replSet" );
-
- if( this.useSeedList ) {
- a.push( this.getURL() );
- }
- else {
- a.push( this.name );
- }
- }
-
- a.push( "--noprealloc", "--smallfiles" );
-
- a.push( "--rest" );
-
- a.push( "--port" );
- a.push( this.getPort( n ) );
-
- a.push( "--dbpath" );
- a.push( this.getPath( ( n.host ? this.getNodeId( n ) : n ) ) );
-
- if( this.keyFile ){
- a.push( "--keyFile" )
- a.push( keyFile )
- }
-
- if( jsTestOptions().noJournal ) a.push( "--nojournal" )
- if( jsTestOptions().noJournalPrealloc ) a.push( "--nopreallocj" )
-
- for ( var k in extra ){
- var v = extra[k];
- a.push( "--" + k );
- if ( v != null ){
- if( v.replace ){
- v = v.replace(/\$node/g, "" + ( n.host ? this.getNodeId( n ) : n ) )
- v = v.replace(/\$set/g, this.name )
- v = v.replace(/\$path/g, this.getPath( n ) )
- }
- a.push( v );
- }
- }
-
- return a;
-}
-
-ReplSetTest.prototype.startSet = function(options) {
- var nodes = [];
- print( "ReplSetTest Starting Set" );
-
- for(n=0; n<this.ports.length; n++) {
- node = this.start(n, options);
- nodes.push(node);
- }
-
- this.nodes = nodes;
- return this.nodes;
-}
-
-ReplSetTest.prototype.callIsMaster = function() {
-
- var master = null;
- this.initLiveNodes();
-
- for(var i=0; i<this.nodes.length; i++) {
-
- try {
- var n = this.nodes[i].getDB('admin').runCommand({ismaster:1});
-
- if(n['ismaster'] == true) {
- master = this.nodes[i];
- this.liveNodes.master = master;
- this.nodeIds[master] = i;
- master.nodeId = i
- }
- else {
- this.nodes[i].setSlaveOk();
- this.liveNodes.slaves.push(this.nodes[i]);
- this.nodeIds[this.nodes[i]] = i;
- this.nodes[i].nodeId = i
- }
-
- }
- catch(err) {
- print("ReplSetTest Could not call ismaster on node " + i);
- }
- }
-
- return master || false;
-}
-
-ReplSetTest.awaitRSClientHosts = function( conn, host, hostOk, rs ) {
-
- if( host.length ){
- for( var i = 0; i < host.length; i++ ) this.awaitOk( conn, host[i] )
- return
- }
-
- if( hostOk == undefined ) hostOk = { ok : true }
- if( host.host ) host = host.host
- if( rs && rs.getMaster ) rs = rs.name
-
- print( "Awaiting " + host + " to be " + tojson( hostOk ) + " for " + conn + " (rs: " + rs + ")" )
-
- var tests = 0
- assert.soon( function() {
- var rsClientHosts = conn.getDB( "admin" ).runCommand( "connPoolStats" )[ "replicaSets" ]
- if( tests++ % 10 == 0 )
- printjson( rsClientHosts )
-
- for ( rsName in rsClientHosts ){
- if( rs && rs != rsName ) continue
- for ( var i = 0; i < rsClientHosts[rsName].hosts.length; i++ ){
- var clientHost = rsClientHosts[rsName].hosts[ i ];
- if( clientHost.addr != host ) continue
-
- // Check that *all* host properties are set correctly
- var propOk = true
- for( var prop in hostOk ){
- if( clientHost[prop] != hostOk[prop] ){
- propOk = false
- break
- }
- }
-
- if( propOk ) return true;
-
- }
- }
- return false;
- }, "timed out waiting for replica set client to recognize hosts",
- 3 * 20 * 1000 /* ReplicaSetMonitorWatcher updates every 20s */ )
-
-}
-
-ReplSetTest.prototype.awaitSecondaryNodes = function( timeout ) {
- var master = this.getMaster();
- var slaves = this.liveNodes.slaves;
- var len = slaves.length;
-
- this.attempt({context: this, timeout: 60000, desc: "Awaiting secondaries"}, function() {
- var ready = true;
- for(var i=0; i<len; i++) {
- ready = ready && slaves[i].getDB("admin").runCommand({ismaster: 1})['secondary'];
- }
-
- return ready;
- });
-}
-
-ReplSetTest.prototype.getMaster = function( timeout ) {
- var tries = 0;
- var sleepTime = 500;
- var t = timeout || 000;
- var master = null;
-
- master = this.attempt({context: this, timeout: 60000, desc: "Finding master"}, this.callIsMaster);
- return master;
-}
-
-ReplSetTest.prototype.getPrimary = ReplSetTest.prototype.getMaster
-
-ReplSetTest.prototype.getSecondaries = function( timeout ){
- var master = this.getMaster( timeout )
- var secs = []
- for( var i = 0; i < this.nodes.length; i++ ){
- if( this.nodes[i] != master ){
- secs.push( this.nodes[i] )
- }
- }
- return secs
-}
-
-ReplSetTest.prototype.getSecondary = function( timeout ){
- return this.getSecondaries( timeout )[0];
-}
-
-ReplSetTest.prototype.status = function( timeout ){
- var master = this.callIsMaster()
- if( ! master ) master = this.liveNodes.slaves[0]
- return master.getDB("admin").runCommand({replSetGetStatus: 1})
-}
-
-// Add a node to the test set
-ReplSetTest.prototype.add = function( config ) {
- if(this.ports.length == 0) {
- var nextPort = allocatePorts( 1, this.startPort )[0];
- }
- else {
- var nextPort = this.ports[this.ports.length-1] + 1;
- }
- print("ReplSetTest Next port: " + nextPort);
- this.ports.push(nextPort);
- printjson(this.ports);
-
- var nextId = this.nodes.length;
- printjson(this.nodes);
- print("ReplSetTest nextId:" + nextId);
- var newNode = this.start(nextId);
- this.nodes.push(newNode);
-
- return newNode;
-}
-
-ReplSetTest.prototype.remove = function( nodeId ) {
- this.nodes.splice( nodeId, 1 );
- this.ports.splice( nodeId, 1 );
-}
-
-// Pass this method a function to call repeatedly until
-// that function returns true. Example:
-// attempt({timeout: 20000, desc: "get master"}, function() { // return false until success })
-ReplSetTest.prototype.attempt = function( opts, func ) {
- var timeout = opts.timeout || 1000;
- var tries = 0;
- var sleepTime = 500;
- var result = null;
- var context = opts.context || this;
-
- while((result = func.apply(context)) == false) {
- tries += 1;
- sleep(sleepTime);
- if( tries * sleepTime > timeout) {
- throw('[' + opts['desc'] + ']' + " timed out after " + timeout + "ms ( " + tries + " tries )");
- }
- }
-
- return result;
-}
-
-ReplSetTest.prototype.initiate = function( cfg , initCmd , timeout ) {
- var master = this.nodes[0].getDB("admin");
- var config = cfg || this.getReplSetConfig();
- var cmd = {};
- var cmdKey = initCmd || 'replSetInitiate';
- var timeout = timeout || 30000;
- cmd[cmdKey] = config;
- printjson(cmd);
-
- this.attempt({timeout: timeout, desc: "Initiate replica set"}, function() {
- var result = master.runCommand(cmd);
- printjson(result);
- return result['ok'] == 1;
- });
-}
-
-ReplSetTest.prototype.reInitiate = function() {
- var master = this.nodes[0];
- var c = master.getDB("local")['system.replset'].findOne();
- var config = this.getReplSetConfig();
- config.version = c.version + 1;
- this.initiate( config , 'replSetReconfig' );
-}
-
-ReplSetTest.prototype.getLastOpTimeWritten = function() {
- this.getMaster();
- this.attempt({context : this, desc : "awaiting oplog query"},
- function() {
- try {
- this.latest = this.liveNodes.master.getDB("local")['oplog.rs'].find({}).sort({'$natural': -1}).limit(1).next()['ts'];
- }
- catch(e) {
- print("ReplSetTest caught exception " + e);
- return false;
- }
- return true;
- });
-};
-
-ReplSetTest.prototype.awaitReplication = function(timeout) {
- timeout = timeout || 30000;
-
- this.getLastOpTimeWritten();
-
- print("ReplSetTest " + this.latest);
-
- this.attempt({context: this, timeout: timeout, desc: "awaiting replication"},
- function() {
- try {
- var synced = true;
- for(var i=0; i<this.liveNodes.slaves.length; i++) {
- var slave = this.liveNodes.slaves[i];
-
- // Continue if we're connected to an arbiter
- if(res = slave.getDB("admin").runCommand({replSetGetStatus: 1})) {
- if(res.myState == 7) {
- continue;
- }
- }
-
- slave.getDB("admin").getMongo().setSlaveOk();
- var log = slave.getDB("local")['oplog.rs'];
- if(log.find({}).sort({'$natural': -1}).limit(1).hasNext()) {
- var entry = log.find({}).sort({'$natural': -1}).limit(1).next();
- printjson( entry );
- var ts = entry['ts'];
- print("ReplSetTest await TS for " + slave + " is " + ts.t+":"+ts.i + " and latest is " + this.latest.t+":"+this.latest.i);
-
- if (this.latest.t < ts.t || (this.latest.t == ts.t && this.latest.i < ts.i)) {
- this.latest = this.liveNodes.master.getDB("local")['oplog.rs'].find({}).sort({'$natural': -1}).limit(1).next()['ts'];
- }
-
- print("ReplSetTest await oplog size for " + slave + " is " + log.count());
- synced = (synced && friendlyEqual(this.latest,ts))
- }
- else {
- synced = false;
- }
- }
-
- if(synced) {
- print("ReplSetTest await synced=" + synced);
- }
- return synced;
- }
- catch (e) {
- print("ReplSetTest.awaitReplication: caught exception "+e);
-
- // we might have a new master now
- this.getLastOpTimeWritten();
-
- return false;
- }
- });
-}
-
-ReplSetTest.prototype.getHashes = function( db ){
- this.getMaster();
- var res = {};
- res.master = this.liveNodes.master.getDB( db ).runCommand( "dbhash" )
- res.slaves = this.liveNodes.slaves.map( function(z){ return z.getDB( db ).runCommand( "dbhash" ); } )
- return res;
-}
-
-/**
- * Starts up a server. Options are saved by default for subsequent starts.
- *
- *
- * Options { remember : true } re-applies the saved options from a prior start.
- * Options { noRemember : true } ignores the current properties.
- * Options { appendOptions : true } appends the current options to those remembered.
- * Options { startClean : true } clears the data directory before starting.
- *
- * @param @param {int|conn|[int|conn]} n array or single server number (0, 1, 2, ...) or conn
- * @param {object} [options]
- * @param {boolean} [restart] If false, the data directory will be cleared
- * before the server starts. Defaults to false.
- *
- */
-ReplSetTest.prototype.start = function( n , options , restart , wait ){
-
- if( n.length ){
-
- var nodes = n
- var started = []
-
- for( var i = 0; i < nodes.length; i++ ){
- if( this.start( nodes[i], Object.extend({}, options), restart, wait ) ){
- started.push( nodes[i] )
- }
- }
-
- return started
-
- }
-
- print( "ReplSetTest n is : " + n )
-
- var lockFile = this.getPath( n ) + "/mongod.lock";
- removeFile( lockFile );
-
- options = options || {}
- var noRemember = options.noRemember
- delete options.noRemember
- var appendOptions = options.appendOptions
- delete options.appendOptions
- var startClean = options.startClean
- delete options.startClean
-
- if( restart && options.remember ){
- delete options.remember
-
- var oldOptions = {}
- if( this.savedStartOptions && this.savedStartOptions[n] ){
- oldOptions = this.savedStartOptions[n]
- }
-
- var newOptions = options
- var options = {}
- Object.extend( options, oldOptions )
- Object.extend( options, newOptions )
-
- }
-
- var shouldRemember = ( ! restart && ! noRemember ) || ( restart && appendOptions )
-
- if ( shouldRemember ){
- this.savedStartOptions = this.savedStartOptions || {}
- this.savedStartOptions[n] = options
- }
-
- if( tojson(options) != tojson({}) )
- printjson(options)
-
- var o = this.getOptions( n , options , restart && ! startClean );
-
- print("ReplSetTest " + (restart ? "(Re)" : "") + "Starting....");
- print("ReplSetTest " + o );
-
- var rval = null
- if ( restart ) {
- n = this.getNodeId( n )
- this.nodes[n] = ( startClean ? startMongod.apply( null , o ) : startMongoProgram.apply( null , o ) );
- this.nodes[n].host = this.nodes[n].host.replace( "127.0.0.1", this.host )
- if( shouldRemember ) this.savedStartOptions[this.nodes[n]] = options
- printjson( this.nodes )
- rval = this.nodes[n];
- }
- else {
- var conn = startMongod.apply( null , o );
- if( shouldRemember ) this.savedStartOptions[conn] = options
- conn.host = conn.host.replace( "127.0.0.1", this.host )
- rval = conn;
- }
-
- wait = wait || false
- if( ! wait.toFixed ){
- if( wait ) wait = 0
- else wait = -1
- }
-
- if( rval == null || wait < 0 ) return rval
-
- // Wait for startup
- this.waitForHealth( rval, this.UP, wait )
-
- return rval
-
-}
-
-
-/**
- * Restarts a db without clearing the data directory by default. If the server is not
- * stopped first, this function will not work.
- *
- * Option { startClean : true } forces clearing the data directory.
- *
- * @param {int|conn|[int|conn]} n array or single server number (0, 1, 2, ...) or conn
- */
-ReplSetTest.prototype.restart = function( n , options, signal, wait ){
- // Can specify wait as third parameter, if using default signal
- if( signal == true || signal == false ){
- wait = signal
- signal = undefined
- }
-
- this.stop( n, signal, wait && wait.toFixed ? wait : true )
- return this.start( n , options , true, wait );
-}
-
-ReplSetTest.prototype.stopMaster = function( signal , wait ) {
- var master = this.getMaster();
- var master_id = this.getNodeId( master );
- return this.stop( master_id , signal , wait );
-}
-
-// Stops a particular node or nodes, specified by conn or id
-ReplSetTest.prototype.stop = function( n , signal, wait /* wait for stop */ ){
-
- // Flatten array of nodes to stop
- if( n.length ){
- nodes = n
-
- var stopped = []
- for( var i = 0; i < nodes.length; i++ ){
- if( this.stop( nodes[i], signal, wait ) )
- stopped.push( nodes[i] )
- }
-
- return stopped
- }
-
-
- // Can specify wait as second parameter, if using default signal
- if( signal == true || signal == false ){
- wait = signal
- signal = undefined
- }
-
- wait = wait || false
- if( ! wait.toFixed ){
- if( wait ) wait = 0
- else wait = -1
- }
-
- var port = this.getPort( n );
- print('ReplSetTest stop *** Shutting down mongod in port ' + port + ' ***');
- var ret = stopMongod( port , signal || 15 );
-
- if( ! ret || wait < 0 ) return ret
-
- // Wait for shutdown
- this.waitForHealth( n, this.DOWN, wait )
-
- return true
-}
-
-
-ReplSetTest.prototype.stopSet = function( signal , forRestart ) {
- for(i=0; i < this.ports.length; i++) {
- this.stop( i, signal );
- }
- if ( ! forRestart && this._alldbpaths ){
- print("ReplSetTest stopSet deleting all dbpaths");
- for( i=0; i<this._alldbpaths.length; i++ ){
- resetDbpath( this._alldbpaths[i] );
- }
- }
-
- print('ReplSetTest stopSet *** Shut down repl set - test worked ****' )
-};
-
-
-/**
- * Waits until there is a master node
- */
-ReplSetTest.prototype.waitForMaster = function( timeout ){
-
- var master = undefined
-
- this.attempt({context: this, timeout: timeout, desc: "waiting for master"}, function() {
- return ( master = this.getMaster() )
- });
-
- return master
-}
-
-
-/**
- * Wait for a health indicator to go to a particular state or states.
- *
- * @param node is a single node or list of nodes, by id or conn
- * @param state is a single state or list of states
- *
- */
-ReplSetTest.prototype.waitForHealth = function( node, state, timeout ){
- this.waitForIndicator( node, state, "health", timeout )
-}
-
-/**
- * Wait for a state indicator to go to a particular state or states.
- *
- * @param node is a single node or list of nodes, by id or conn
- * @param state is a single state or list of states
- *
- */
-ReplSetTest.prototype.waitForState = function( node, state, timeout ){
- this.waitForIndicator( node, state, "state", timeout )
-}
-
-/**
- * Wait for a rs indicator to go to a particular state or states.
- *
- * @param node is a single node or list of nodes, by id or conn
- * @param states is a single state or list of states
- * @param ind is the indicator specified
- *
- */
-ReplSetTest.prototype.waitForIndicator = function( node, states, ind, timeout ){
-
- if( node.length ){
-
- var nodes = node
- for( var i = 0; i < nodes.length; i++ ){
- if( states.length )
- this.waitForIndicator( nodes[i], states[i], ind, timeout )
- else
- this.waitForIndicator( nodes[i], states, ind, timeout )
- }
-
- return;
- }
-
- timeout = timeout || 30000;
-
- if( ! node.getDB ){
- node = this.nodes[node]
- }
-
- if( ! states.length ) states = [ states ]
-
- print( "ReplSetTest waitForIndicator " + ind )
- printjson( states )
- print( "ReplSetTest waitForIndicator from node " + node )
-
- var lastTime = null
- var currTime = new Date().getTime()
- var status = undefined
-
- this.attempt({context: this, timeout: timeout, desc: "waiting for state indicator " + ind + " for " + timeout + "ms" }, function() {
-
- status = this.status()
-
- if( lastTime == null || ( currTime = new Date().getTime() ) - (1000 * 5) > lastTime ){
- if( lastTime == null ) print( "ReplSetTest waitForIndicator Initial status ( timeout : " + timeout + " ) :" )
- printjson( status )
- lastTime = new Date().getTime()
- }
-
- if (typeof status.members == 'undefined') {
- return false;
- }
-
- for( var i = 0; i < status.members.length; i++ ){
- if( status.members[i].name == node.host ){
- for( var j = 0; j < states.length; j++ ){
- if( status.members[i][ind] == states[j] ) return true;
- }
- }
- }
-
- return false
-
- });
-
- print( "ReplSetTest waitForIndicator final status:" )
- printjson( status )
-
-}
-
-ReplSetTest.Health = {}
-ReplSetTest.Health.UP = 1
-ReplSetTest.Health.DOWN = 0
-
-ReplSetTest.State = {}
-ReplSetTest.State.PRIMARY = 1
-ReplSetTest.State.SECONDARY = 2
-ReplSetTest.State.RECOVERING = 3
-
-/**
- * Overflows a replica set secondary or secondaries, specified by id or conn.
- */
-ReplSetTest.prototype.overflow = function( secondaries ){
-
- // Create a new collection to overflow, allow secondaries to replicate
- var master = this.getMaster()
- var overflowColl = master.getCollection( "_overflow.coll" )
- overflowColl.insert({ replicated : "value" })
- this.awaitReplication()
-
- this.stop( secondaries, undefined, 5 * 60 * 1000 )
-
- var count = master.getDB("local").oplog.rs.count();
- var prevCount = -1;
-
- // Keep inserting till we hit our capped coll limits
- while (count != prevCount) {
-
- print("ReplSetTest overflow inserting 10000");
-
- for (var i = 0; i < 10000; i++) {
- overflowColl.insert({ overflow : "value" });
- }
- prevCount = count;
- this.awaitReplication();
-
- count = master.getDB("local").oplog.rs.count();
-
- print( "ReplSetTest overflow count : " + count + " prev : " + prevCount );
-
- }
-
- // Restart all our secondaries and wait for recovery state
- this.start( secondaries, { remember : true }, true, true )
- this.waitForState( secondaries, this.RECOVERING, 5 * 60 * 1000 )
-
-}
-
-
-
-
-/**
- * Bridging allows you to test network partitioning. For example, you can set
- * up a replica set, run bridge(), then kill the connection between any two
- * nodes x and y with partition(x, y).
- *
- * Once you have called bridging, you cannot reconfigure the replica set.
- */
-ReplSetTest.prototype.bridge = function() {
- if (this.bridges) {
- print("ReplSetTest bridge bridges have already been created!");
- return;
- }
-
- var n = this.nodes.length;
-
- // create bridges
- this.bridges = [];
- for (var i=0; i<n; i++) {
- var nodeBridges = [];
- for (var j=0; j<n; j++) {
- if (i == j) {
- continue;
- }
- nodeBridges[j] = new ReplSetBridge(this, i, j);
- }
- this.bridges.push(nodeBridges);
- }
- print("ReplSetTest bridge bridges: " + this.bridges);
-
- // restart everyone independently
- this.stopSet(null, true);
- for (var i=0; i<n; i++) {
- this.restart(i, {noReplSet : true});
- }
-
- // create new configs
- for (var i=0; i<n; i++) {
- config = this.nodes[i].getDB("local").system.replset.findOne();
-
- if (!config) {
- print("ReplSetTest bridge couldn't find config for "+this.nodes[i]);
- printjson(this.nodes[i].getDB("local").system.namespaces.find().toArray());
- assert(false);
- }
-
- var updateMod = {"$set" : {}};
- for (var j = 0; j<config.members.length; j++) {
- if (config.members[j].host == this.host+":"+this.ports[i]) {
- continue;
- }
-
- updateMod['$set']["members."+j+".host"] = this.bridges[i][j].host;
- }
- print("ReplSetTest bridge for node " + i + ":");
- printjson(updateMod);
- this.nodes[i].getDB("local").system.replset.update({},updateMod);
- }
-
- this.stopSet(null, true);
-
- // start set
- for (var i=0; i<n; i++) {
- this.restart(i);
- }
-
- return this.getMaster();
-};
-
-/**
- * This kills the bridge between two nodes. As parameters, specify the from and
- * to node numbers.
- *
- * For example, with a three-member replica set, we'd have nodes 0, 1, and 2,
- * with the following bridges: 0->1, 0->2, 1->0, 1->2, 2->0, 2->1. We can kill
- * the connection between nodes 0 and 2 by calling replTest.partition(0,2) or
- * replTest.partition(2,0) (either way is identical). Then the replica set would
- * have the following bridges: 0->1, 1->0, 1->2, 2->1.
- */
-ReplSetTest.prototype.partition = function(from, to) {
- this.bridges[from][to].stop();
- this.bridges[to][from].stop();
-};
-
-/**
- * This reverses a partition created by partition() above.
- */
-ReplSetTest.prototype.unPartition = function(from, to) {
- this.bridges[from][to].start();
- this.bridges[to][from].start();
-};
-
-ReplSetBridge = function(rst, from, to) {
- var n = rst.nodes.length;
-
- var startPort = rst.startPort+n;
- this.port = (startPort+(from*n+to));
- this.host = rst.host+":"+this.port;
-
- this.dest = rst.host+":"+rst.ports[to];
- this.start();
-};
-
-ReplSetBridge.prototype.start = function() {
- var args = ["mongobridge", "--port", this.port, "--dest", this.dest];
- print("ReplSetBridge starting: "+tojson(args));
- this.bridge = startMongoProgram.apply( null , args );
- print("ReplSetBridge started " + this.bridge);
-};
-
-ReplSetBridge.prototype.stop = function() {
- print("ReplSetBridge stopping: " + this.port);
- stopMongod(this.port);
-};
-
-ReplSetBridge.prototype.toString = function() {
- return this.host+" -> "+this.dest;
-};
diff --git a/shell/shell_utils.cpp b/shell/shell_utils.cpp
deleted file mode 100644
index e09309c640b..00000000000
--- a/shell/shell_utils.cpp
+++ /dev/null
@@ -1,959 +0,0 @@
-// utils.cpp
-/*
- * Copyright 2010 10gen Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "pch.h"
-
-#include <boost/thread/xtime.hpp>
-
-#include <cstring>
-#include <cstdio>
-#include <cstdlib>
-#include <assert.h>
-#include <iostream>
-#include <map>
-#include <sstream>
-#include <vector>
-#include <fcntl.h>
-
-#ifdef _WIN32
-# include <io.h>
-# define SIGKILL 9
-#else
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <signal.h>
-# include <sys/stat.h>
-# include <sys/wait.h>
-#endif
-
-#include "utils.h"
-#include "../client/dbclient.h"
-#include "../util/md5.hpp"
-#include "../util/processinfo.h"
-#include "../util/text.h"
-#include "../util/heapcheck.h"
-#include "../util/time_support.h"
-#include "../util/file.h"
-
-namespace mongo {
-
- DBClientWithCommands *latestConn = 0;
- extern bool dbexitCalled;
-
-#ifdef _WIN32
- inline int close(int fd) { return _close(fd); }
- inline int read(int fd, void* buf, size_t size) { return _read(fd, buf, size); }
- inline int pipe(int fds[2]) { return _pipe(fds, 4096, _O_TEXT | _O_NOINHERIT); }
-#endif
-
- namespace JSFiles {
- extern const JSFile servers;
- }
-
- // these functions have not been audited for thread safety - currently they are called with an exclusive js mutex
- namespace shellUtils {
-
- Scope* theScope = 0;
-
- std::string _dbConnect;
- std::string _dbAuth;
-
- const char *argv0 = 0;
- void RecordMyLocation( const char *_argv0 ) { argv0 = _argv0; }
-
- // helpers
-
- BSONObj makeUndefined() {
- BSONObjBuilder b;
- b.appendUndefined( "" );
- return b.obj();
- }
- const BSONObj undefined_ = makeUndefined();
-
- BSONObj encapsulate( const BSONObj &obj ) {
- return BSON( "" << obj );
- }
-
- // real methods
-
- void goingAwaySoon();
- BSONObj Quit(const BSONObj& args, void* data) {
- // If not arguments are given first element will be EOO, which
- // converts to the integer value 0.
- goingAwaySoon();
- int exit_code = int( args.firstElement().number() );
- ::exit(exit_code);
- return undefined_;
- }
-
- BSONObj JSGetMemInfo( const BSONObj& args, void* data ) {
- ProcessInfo pi;
- uassert( 10258 , "processinfo not supported" , pi.supported() );
-
- BSONObjBuilder e;
- e.append( "virtual" , pi.getVirtualMemorySize() );
- e.append( "resident" , pi.getResidentSize() );
-
- BSONObjBuilder b;
- b.append( "ret" , e.obj() );
-
- return b.obj();
- }
-
-
-#ifndef MONGO_SAFE_SHELL
-
- BSONObj listFiles(const BSONObj& _args, void* data) {
- static BSONObj cd = BSON( "0" << "." );
- BSONObj args = _args.isEmpty() ? cd : _args;
-
- uassert( 10257 , "need to specify 1 argument to listFiles" , args.nFields() == 1 );
-
- BSONArrayBuilder lst;
-
- string rootname = args.firstElement().valuestrsafe();
- path root( rootname );
- stringstream ss;
- ss << "listFiles: no such directory: " << rootname;
- string msg = ss.str();
- uassert( 12581, msg.c_str(), boost::filesystem::exists( root ) );
-
- directory_iterator end;
- directory_iterator i( root);
-
- while ( i != end ) {
- path p = *i;
- BSONObjBuilder b;
- b << "name" << p.string();
- b.appendBool( "isDirectory", is_directory( p ) );
- if ( ! is_directory( p ) ) {
- try {
- b.append( "size" , (double)file_size( p ) );
- }
- catch ( ... ) {
- i++;
- continue;
- }
- }
-
- lst.append( b.obj() );
- i++;
- }
-
- BSONObjBuilder ret;
- ret.appendArray( "", lst.done() );
- return ret.obj();
- }
-
- BSONObj ls(const BSONObj& args, void* data) {
- BSONObj o = listFiles(args, data);
- if( !o.isEmpty() ) {
- for( BSONObj::iterator i = o.firstElement().Obj().begin(); i.more(); ) {
- BSONObj f = i.next().Obj();
- cout << f["name"].String();
- if( f["isDirectory"].trueValue() ) cout << '/';
- cout << '\n';
- }
- cout.flush();
- }
- return BSONObj();
- }
-
- BSONObj cd(const BSONObj& args, void* data) {
-#if defined(_WIN32)
- std::wstring dir = toWideString( args.firstElement().String().c_str() );
- if( SetCurrentDirectory(dir.c_str()) )
- return BSONObj();
-#else
- string dir = args.firstElement().String();
- /* if( chdir(dir.c_str) ) == 0 )
- return BSONObj();
- */
- if( 1 ) return BSON(""<<"implementation not done for posix");
-#endif
- return BSON( "" << "change directory failed" );
- }
-
- BSONObj pwd(const BSONObj&, void* data) {
- boost::filesystem::path p = boost::filesystem::current_path();
- return BSON( "" << p.string() );
- }
-
- BSONObj hostname(const BSONObj&, void* data) {
- return BSON( "" << getHostName() );
- }
-
- static BSONElement oneArg(const BSONObj& args) {
- uassert( 12597 , "need to specify 1 argument" , args.nFields() == 1 );
- return args.firstElement();
- }
-
- const int CANT_OPEN_FILE = 13300;
-
- BSONObj cat(const BSONObj& args, void* data) {
- BSONElement e = oneArg(args);
- stringstream ss;
- ifstream f(e.valuestrsafe());
- uassert(CANT_OPEN_FILE, "couldn't open file", f.is_open() );
-
- streamsize sz = 0;
- while( 1 ) {
- char ch = 0;
- // slow...maybe change one day
- f.get(ch);
- if( ch == 0 ) break;
- ss << ch;
- sz += 1;
- uassert(13301, "cat() : file to big to load as a variable", sz < 1024 * 1024 * 16);
- }
- return BSON( "" << ss.str() );
- }
-
- BSONObj md5sumFile(const BSONObj& args, void* data) {
- BSONElement e = oneArg(args);
- stringstream ss;
- FILE* f = fopen(e.valuestrsafe(), "rb");
- uassert(CANT_OPEN_FILE, "couldn't open file", f );
-
- md5digest d;
- md5_state_t st;
- md5_init(&st);
-
- enum {BUFLEN = 4*1024};
- char buffer[BUFLEN];
- int bytes_read;
- while( (bytes_read = fread(buffer, 1, BUFLEN, f)) ) {
- md5_append( &st , (const md5_byte_t*)(buffer) , bytes_read );
- }
-
- md5_finish(&st, d);
- return BSON( "" << digestToString( d ) );
- }
-
- BSONObj mkdir(const BSONObj& args, void* data) {
- boost::filesystem::create_directories(args.firstElement().String());
- return BSON( "" << true );
- }
-
- BSONObj removeFile(const BSONObj& args, void* data) {
- BSONElement e = oneArg(args);
- bool found = false;
-
- path root( e.valuestrsafe() );
- if ( boost::filesystem::exists( root ) ) {
- found = true;
- boost::filesystem::remove_all( root );
- }
-
- BSONObjBuilder b;
- b.appendBool( "removed" , found );
- return b.obj();
- }
-
- /**
- * @param args - [ name, byte index ]
- * In this initial implementation, all bits in the specified byte are flipped.
- */
- BSONObj fuzzFile(const BSONObj& args, void* data) {
- uassert( 13619, "fuzzFile takes 2 arguments", args.nFields() == 2 );
- shared_ptr< File > f( new File() );
- f->open( args.getStringField( "0" ) );
- uassert( 13620, "couldn't open file to fuzz", !f->bad() && f->is_open() );
-
- char c;
- f->read( args.getIntField( "1" ), &c, 1 );
- c = ~c;
- f->write( args.getIntField( "1" ), &c, 1 );
-
- return undefined_;
- // f close is implicit
- }
-
- map< int, pair< pid_t, int > > dbs;
- map< pid_t, int > shells;
-#ifdef _WIN32
- map< pid_t, HANDLE > handles;
-#endif
-
- mongo::mutex mongoProgramOutputMutex("mongoProgramOutputMutex");
- stringstream mongoProgramOutput_;
-
- void goingAwaySoon() {
- mongo::mutex::scoped_lock lk( mongoProgramOutputMutex );
- mongo::dbexitCalled = true;
- }
-
- void writeMongoProgramOutputLine( int port, int pid, const char *line ) {
- mongo::mutex::scoped_lock lk( mongoProgramOutputMutex );
- if( mongo::dbexitCalled ) throw "program is terminating";
- stringstream buf;
- if ( port > 0 )
- buf << " m" << port << "| " << line;
- else
- buf << "sh" << pid << "| " << line;
- cout << buf.str() << endl;
- mongoProgramOutput_ << buf.str() << endl;
- }
-
- // only returns last 100000 characters
- BSONObj RawMongoProgramOutput( const BSONObj &args, void* data ) {
- mongo::mutex::scoped_lock lk( mongoProgramOutputMutex );
- string out = mongoProgramOutput_.str();
- size_t len = out.length();
- if ( len > 100000 )
- out = out.substr( len - 100000, 100000 );
- return BSON( "" << out );
- }
-
- BSONObj ClearRawMongoProgramOutput( const BSONObj &args, void* data ) {
- mongo::mutex::scoped_lock lk( mongoProgramOutputMutex );
- mongoProgramOutput_.str( "" );
- return undefined_;
- }
-
- class ProgramRunner {
- vector<string> argv_;
- int port_;
- int pipe_;
- pid_t pid_;
- public:
- pid_t pid() const { return pid_; }
- int port() const { return port_; }
-
- boost::filesystem::path find(string prog) {
- boost::filesystem::path p = prog;
-#ifdef _WIN32
- p = change_extension(p, ".exe");
-#endif
-
- if( boost::filesystem::exists(p) ) {
-#ifndef _WIN32
- p = boost::filesystem::initial_path() / p;
-#endif
- return p;
- }
-
- {
- boost::filesystem::path t = boost::filesystem::current_path() / p;
- if( boost::filesystem::exists(t) ) return t;
- }
- try {
- if( theScope->type("_path") == String ) {
- string path = theScope->getString("_path");
- if( !path.empty() ) {
- boost::filesystem::path t = boost::filesystem::path(path) / p;
- if( boost::filesystem::exists(t) ) return t;
- }
- }
- }
- catch(...) { }
- {
- boost::filesystem::path t = boost::filesystem::initial_path() / p;
- if( boost::filesystem::exists(t) ) return t;
- }
- return p; // not found; might find via system path
- }
-
- ProgramRunner( const BSONObj &args , bool isMongoProgram=true) {
- assert( !args.isEmpty() );
-
- string program( args.firstElement().valuestrsafe() );
- assert( !program.empty() );
- boost::filesystem::path programPath = find(program);
-
- if (isMongoProgram) {
-#if 0
- if (program == "mongos") {
- argv_.push_back("valgrind");
- argv_.push_back("--log-file=/tmp/mongos-%p.valgrind");
- argv_.push_back("--leak-check=yes");
- argv_.push_back("--suppressions=valgrind.suppressions");
- //argv_.push_back("--error-exitcode=1");
- argv_.push_back("--");
- }
-#endif
- }
-
- argv_.push_back( programPath.native_file_string() );
-
- port_ = -1;
-
- BSONObjIterator j( args );
- j.next(); // skip program name (handled above)
- while(j.more()) {
- BSONElement e = j.next();
- string str;
- if ( e.isNumber() ) {
- stringstream ss;
- ss << e.number();
- str = ss.str();
- }
- else {
- assert( e.type() == mongo::String );
- str = e.valuestr();
- }
- if ( str == "--port" )
- port_ = -2;
- else if ( port_ == -2 )
- port_ = strtol( str.c_str(), 0, 10 );
- argv_.push_back(str);
- }
-
- if ( program != "mongod" && program != "mongos" && program != "mongobridge" )
- port_ = 0;
- else {
- if ( port_ <= 0 )
- cout << "error: a port number is expected when running mongod (etc.) from the shell" << endl;
- assert( port_ > 0 );
- }
- if ( port_ > 0 && dbs.count( port_ ) != 0 ) {
- cerr << "count for port: " << port_ << " is not 0 is: " << dbs.count( port_ ) << endl;
- assert( dbs.count( port_ ) == 0 );
- }
- }
-
- void start() {
- int pipeEnds[ 2 ];
- assert( pipe( pipeEnds ) != -1 );
-
- fflush( 0 );
- launch_process(pipeEnds[1]); //sets pid_
-
- {
- stringstream ss;
- ss << "shell: started program";
- for (unsigned i=0; i < argv_.size(); i++)
- ss << " " << argv_[i];
- ss << '\n';
- cout << ss.str(); cout.flush();
- }
-
- if ( port_ > 0 )
- dbs.insert( make_pair( port_, make_pair( pid_, pipeEnds[ 1 ] ) ) );
- else
- shells.insert( make_pair( pid_, pipeEnds[ 1 ] ) );
- pipe_ = pipeEnds[ 0 ];
- }
-
- // Continue reading output
- void operator()() {
- try {
- // This assumes there aren't any 0's in the mongo program output.
- // Hope that's ok.
- const unsigned bufSize = 128 * 1024;
- char buf[ bufSize ];
- char temp[ bufSize ];
- char *start = buf;
- while( 1 ) {
- int lenToRead = ( bufSize - 1 ) - ( start - buf );
- if ( lenToRead <= 0 ) {
- cout << "error: lenToRead: " << lenToRead << endl;
- cout << "first 300: " << string(buf,0,300) << endl;
- }
- assert( lenToRead > 0 );
- int ret = read( pipe_, (void *)start, lenToRead );
- if( mongo::dbexitCalled )
- break;
- assert( ret != -1 );
- start[ ret ] = '\0';
- if ( strlen( start ) != unsigned( ret ) )
- writeMongoProgramOutputLine( port_, pid_, "WARNING: mongod wrote null bytes to output" );
- char *last = buf;
- for( char *i = strchr( buf, '\n' ); i; last = i + 1, i = strchr( last, '\n' ) ) {
- *i = '\0';
- writeMongoProgramOutputLine( port_, pid_, last );
- }
- if ( ret == 0 ) {
- if ( *last )
- writeMongoProgramOutputLine( port_, pid_, last );
- close( pipe_ );
- break;
- }
- if ( last != buf ) {
- strcpy( temp, last );
- strcpy( buf, temp );
- }
- else {
- assert( strlen( buf ) < bufSize );
- }
- start = buf + strlen( buf );
- }
- }
- catch(...) {
- }
- }
- void launch_process(int child_stdout) {
-#ifdef _WIN32
- stringstream ss;
- for( unsigned i=0; i < argv_.size(); i++ ) {
- if (i) ss << ' ';
- if (argv_[i].find(' ') == string::npos)
- ss << argv_[i];
- else
- ss << '"' << argv_[i] << '"';
- }
-
- string args = ss.str();
-
- boost::scoped_array<TCHAR> args_tchar (new TCHAR[args.size() + 1]);
- size_t i;
- for(i=0; i < args.size(); i++)
- args_tchar[i] = args[i];
- args_tchar[i] = 0;
-
- HANDLE h = (HANDLE)_get_osfhandle(child_stdout);
- assert(h != INVALID_HANDLE_VALUE);
- assert(SetHandleInformation(h, HANDLE_FLAG_INHERIT, 1));
-
- STARTUPINFO si;
- ZeroMemory(&si, sizeof(si));
- si.cb = sizeof(si);
- si.hStdError = h;
- si.hStdOutput = h;
- si.dwFlags |= STARTF_USESTDHANDLES;
-
- PROCESS_INFORMATION pi;
- ZeroMemory(&pi, sizeof(pi));
-
- bool success = CreateProcess( NULL, args_tchar.get(), NULL, NULL, true, 0, NULL, NULL, &si, &pi) != 0;
- {
- stringstream ss;
- ss << "couldn't start process " << argv_[0];
- uassert(14042, ss.str(), success);
- }
-
- CloseHandle(pi.hThread);
-
- pid_ = pi.dwProcessId;
- handles.insert( make_pair( pid_, pi.hProcess ) );
-
-#else
-
- pid_ = fork();
- assert( pid_ != -1 );
-
- if ( pid_ == 0 ) {
- // DON'T ASSERT IN THIS BLOCK - very bad things will happen
-
- const char** argv = new const char* [argv_.size()+1]; // don't need to free - in child
- for (unsigned i=0; i < argv_.size(); i++) {
- argv[i] = argv_[i].c_str();
- }
- argv[argv_.size()] = 0;
-
- if ( dup2( child_stdout, STDOUT_FILENO ) == -1 ||
- dup2( child_stdout, STDERR_FILENO ) == -1 ) {
- cout << "Unable to dup2 child output: " << errnoWithDescription() << endl;
- ::_Exit(-1); //do not pass go, do not call atexit handlers
- }
-
- const char** env = new const char* [2]; // don't need to free - in child
- env[0] = NULL;
-#if defined(HEAP_CHECKING)
- env[0] = "HEAPCHECK=normal";
- env[1] = NULL;
-
- // Heap-check for mongos only. 'argv[0]' must be in the path format.
- if ( argv_[0].find("mongos") != string::npos) {
- execvpe( argv[ 0 ], const_cast<char**>(argv) , const_cast<char**>(env) );
- }
-#endif // HEAP_CHECKING
-
- execvp( argv[ 0 ], const_cast<char**>(argv) );
-
- cout << "Unable to start program " << argv[0] << ' ' << errnoWithDescription() << endl;
- ::_Exit(-1);
- }
-
-#endif
- }
- };
-
- //returns true if process exited
- bool wait_for_pid(pid_t pid, bool block=true, int* exit_code=NULL) {
-#ifdef _WIN32
- assert(handles.count(pid));
- HANDLE h = handles[pid];
-
- if (block)
- WaitForSingleObject(h, INFINITE);
-
- DWORD tmp;
- if(GetExitCodeProcess(h, &tmp)) {
- if ( tmp == STILL_ACTIVE ) {
- return false;
- }
- CloseHandle(h);
- handles.erase(pid);
- if (exit_code)
- *exit_code = tmp;
- return true;
- }
- else {
- return false;
- }
-#else
- int tmp;
- bool ret = (pid == waitpid(pid, &tmp, (block ? 0 : WNOHANG)));
- if (exit_code)
- *exit_code = WEXITSTATUS(tmp);
- return ret;
-
-#endif
- }
-
- BSONObj WaitProgram( const BSONObj& a, void* data ) {
- int pid = oneArg( a ).numberInt();
- BSONObj x = BSON( "" << wait_for_pid( pid ) );
- shells.erase( pid );
- return x;
- }
-
- BSONObj WaitMongoProgramOnPort( const BSONObj &a, void* data ) {
- int port = oneArg( a ).numberInt();
- uassert( 13621, "no known mongo program on port", dbs.count( port ) != 0 );
- log() << "waiting port: " << port << ", pid: " << dbs[ port ].first << endl;
- bool ret = wait_for_pid( dbs[ port ].first );
- if ( ret ) {
- dbs.erase( port );
- }
- return BSON( "" << ret );
- }
-
- BSONObj StartMongoProgram( const BSONObj &a, void* data ) {
- _nokillop = true;
- ProgramRunner r( a );
- r.start();
- boost::thread t( r );
- return BSON( string( "" ) << int( r.pid() ) );
- }
-
- BSONObj RunMongoProgram( const BSONObj &a, void* data ) {
- ProgramRunner r( a );
- r.start();
- boost::thread t( r );
- int exit_code;
- wait_for_pid( r.pid(), true, &exit_code );
- if ( r.port() > 0 ) {
- dbs.erase( r.port() );
- }
- else {
- shells.erase( r.pid() );
- }
- return BSON( string( "" ) << exit_code );
- }
-
- BSONObj RunProgram(const BSONObj &a, void* data) {
- ProgramRunner r( a, false );
- r.start();
- boost::thread t( r );
- int exit_code;
- wait_for_pid(r.pid(), true, &exit_code);
- shells.erase( r.pid() );
- return BSON( string( "" ) << exit_code );
- }
-
- BSONObj ResetDbpath( const BSONObj &a, void* data ) {
- assert( a.nFields() == 1 );
- string path = a.firstElement().valuestrsafe();
- assert( !path.empty() );
- if ( boost::filesystem::exists( path ) )
- boost::filesystem::remove_all( path );
- boost::filesystem::create_directory( path );
- return undefined_;
- }
-
- void copyDir( const path &from, const path &to ) {
- directory_iterator end;
- directory_iterator i( from );
- while( i != end ) {
- path p = *i;
- if ( p.leaf() != "mongod.lock" ) {
- if ( is_directory( p ) ) {
- path newDir = to / p.leaf();
- boost::filesystem::create_directory( newDir );
- copyDir( p, newDir );
- }
- else {
- boost::filesystem::copy_file( p, to / p.leaf() );
- }
- }
- ++i;
- }
- }
-
- // NOTE target dbpath will be cleared first
- BSONObj CopyDbpath( const BSONObj &a, void* data ) {
- assert( a.nFields() == 2 );
- BSONObjIterator i( a );
- string from = i.next().str();
- string to = i.next().str();
- assert( !from.empty() );
- assert( !to.empty() );
- if ( boost::filesystem::exists( to ) )
- boost::filesystem::remove_all( to );
- boost::filesystem::create_directory( to );
- copyDir( from, to );
- return undefined_;
- }
-
- inline void kill_wrapper(pid_t pid, int sig, int port) {
-#ifdef _WIN32
- if (sig == SIGKILL || port == 0) {
- assert( handles.count(pid) );
- TerminateProcess(handles[pid], 1); // returns failure for "zombie" processes.
- }
- else {
- DBClientConnection conn;
- conn.connect("127.0.0.1:" + BSONObjBuilder::numStr(port));
- try {
- conn.simpleCommand("admin", NULL, "shutdown");
- }
- catch (...) {
- //Do nothing. This command never returns data to the client and the driver doesn't like that.
- }
- }
-#else
- int x = kill( pid, sig );
- if ( x ) {
- if ( errno == ESRCH ) {
- }
- else {
- cout << "killFailed: " << errnoWithDescription() << endl;
- assert( x == 0 );
- }
- }
-
-#endif
- }
-
- int killDb( int port, pid_t _pid, int signal ) {
- pid_t pid;
- int exitCode = 0;
- if ( port > 0 ) {
- if( dbs.count( port ) != 1 ) {
- cout << "No db started on port: " << port << endl;
- return 0;
- }
- pid = dbs[ port ].first;
- }
- else {
- pid = _pid;
- }
-
- kill_wrapper( pid, signal, port );
-
- int i = 0;
- for( ; i < 130; ++i ) {
- if ( i == 30 ) {
- char now[64];
- time_t_to_String(time(0), now);
- now[ 20 ] = 0;
- cout << now << " process on port " << port << ", with pid " << pid << " not terminated, sending sigkill" << endl;
- kill_wrapper( pid, SIGKILL, port );
- }
- if(wait_for_pid(pid, false, &exitCode))
- break;
- sleepmillis( 1000 );
- }
- if ( i == 130 ) {
- char now[64];
- time_t_to_String(time(0), now);
- now[ 20 ] = 0;
- cout << now << " failed to terminate process on port " << port << ", with pid " << pid << endl;
- assert( "Failed to terminate process" == 0 );
- }
-
- if ( port > 0 ) {
- close( dbs[ port ].second );
- dbs.erase( port );
- }
- else {
- close( shells[ pid ] );
- shells.erase( pid );
- }
- // FIXME I think the intention here is to do an extra sleep only when SIGKILL is sent to the child process.
- // We may want to change the 4 below to 29, since values of i greater than that indicate we sent a SIGKILL.
- if ( i > 4 || signal == SIGKILL ) {
- sleepmillis( 4000 ); // allow operating system to reclaim resources
- }
-
- return exitCode;
- }
-
- int getSignal( const BSONObj &a ) {
- int ret = SIGTERM;
- if ( a.nFields() == 2 ) {
- BSONObjIterator i( a );
- i.next();
- BSONElement e = i.next();
- assert( e.isNumber() );
- ret = int( e.number() );
- }
- return ret;
- }
-
- /** stopMongoProgram(port[, signal]) */
- BSONObj StopMongoProgram( const BSONObj &a, void* data ) {
- assert( a.nFields() == 1 || a.nFields() == 2 );
- uassert( 15853 , "stopMongo needs a number" , a.firstElement().isNumber() );
- int port = int( a.firstElement().number() );
- int code = killDb( port, 0, getSignal( a ) );
- cout << "shell: stopped mongo program on port " << port << endl;
- return BSON( "" << (double)code );
- }
-
- BSONObj StopMongoProgramByPid( const BSONObj &a, void* data ) {
- assert( a.nFields() == 1 || a.nFields() == 2 );
- uassert( 15852 , "stopMongoByPid needs a number" , a.firstElement().isNumber() );
- int pid = int( a.firstElement().number() );
- int code = killDb( 0, pid, getSignal( a ) );
- cout << "shell: stopped mongo program on pid " << pid << endl;
- return BSON( "" << (double)code );
- }
-
- void KillMongoProgramInstances() {
- vector< int > ports;
- for( map< int, pair< pid_t, int > >::iterator i = dbs.begin(); i != dbs.end(); ++i )
- ports.push_back( i->first );
- for( vector< int >::iterator i = ports.begin(); i != ports.end(); ++i )
- killDb( *i, 0, SIGTERM );
- vector< pid_t > pids;
- for( map< pid_t, int >::iterator i = shells.begin(); i != shells.end(); ++i )
- pids.push_back( i->first );
- for( vector< pid_t >::iterator i = pids.begin(); i != pids.end(); ++i )
- killDb( 0, *i, SIGTERM );
- }
-#else // ndef MONGO_SAFE_SHELL
- void KillMongoProgramInstances() {}
-#endif
-
- MongoProgramScope::~MongoProgramScope() {
- DESTRUCTOR_GUARD(
- KillMongoProgramInstances();
- ClearRawMongoProgramOutput( BSONObj(), 0 );
- )
- }
-
- unsigned _randomSeed;
-
- BSONObj JSSrand( const BSONObj &a, void* data ) {
- uassert( 12518, "srand requires a single numeric argument",
- a.nFields() == 1 && a.firstElement().isNumber() );
- _randomSeed = (unsigned)a.firstElement().numberLong(); // grab least significant digits
- return undefined_;
- }
-
- BSONObj JSRand( const BSONObj &a, void* data ) {
- uassert( 12519, "rand accepts no arguments", a.nFields() == 0 );
- unsigned r;
-#if !defined(_WIN32)
- r = rand_r( &_randomSeed );
-#else
- r = rand(); // seed not used in this case
-#endif
- return BSON( "" << double( r ) / ( double( RAND_MAX ) + 1 ) );
- }
-
- BSONObj isWindows(const BSONObj& a, void* data) {
- uassert( 13006, "isWindows accepts no arguments", a.nFields() == 0 );
-#ifdef _WIN32
- return BSON( "" << true );
-#else
- return BSON( "" << false );
-#endif
- }
-
- BSONObj getHostName(const BSONObj& a, void* data) {
- uassert( 13411, "getHostName accepts no arguments", a.nFields() == 0 );
- char buf[260]; // HOST_NAME_MAX is usually 255
- assert(gethostname(buf, 260) == 0);
- buf[259] = '\0';
- return BSON("" << buf);
-
- }
-
- void installShellUtils( Scope& scope ) {
- theScope = &scope;
- scope.injectNative( "quit", Quit );
- scope.injectNative( "getMemInfo" , JSGetMemInfo );
- scope.injectNative( "_srand" , JSSrand );
- scope.injectNative( "_rand" , JSRand );
- scope.injectNative( "_isWindows" , isWindows );
-
-#ifndef MONGO_SAFE_SHELL
- //can't launch programs
- scope.injectNative( "_startMongoProgram", StartMongoProgram );
- scope.injectNative( "runProgram", RunProgram );
- scope.injectNative( "run", RunProgram );
- scope.injectNative( "runMongoProgram", RunMongoProgram );
- scope.injectNative( "stopMongod", StopMongoProgram );
- scope.injectNative( "stopMongoProgram", StopMongoProgram );
- scope.injectNative( "stopMongoProgramByPid", StopMongoProgramByPid );
- scope.injectNative( "rawMongoProgramOutput", RawMongoProgramOutput );
- scope.injectNative( "clearRawMongoProgramOutput", ClearRawMongoProgramOutput );
- scope.injectNative( "waitProgram" , WaitProgram );
- scope.injectNative( "waitMongoProgramOnPort" , WaitMongoProgramOnPort );
-
- scope.injectNative( "getHostName" , getHostName );
- scope.injectNative( "removeFile" , removeFile );
- scope.injectNative( "fuzzFile" , fuzzFile );
- scope.injectNative( "listFiles" , listFiles );
- scope.injectNative( "ls" , ls );
- scope.injectNative( "pwd", pwd );
- scope.injectNative( "cd", cd );
- scope.injectNative( "cat", cat );
- scope.injectNative( "hostname", hostname);
- scope.injectNative( "resetDbpath", ResetDbpath );
- scope.injectNative( "copyDbpath", CopyDbpath );
- scope.injectNative( "md5sumFile", md5sumFile );
- scope.injectNative( "mkdir" , mkdir );
-#endif
- }
-
- void initScope( Scope &scope ) {
- scope.externalSetup();
- mongo::shellUtils::installShellUtils( scope );
- scope.execSetup(JSFiles::servers);
-
- if ( !_dbConnect.empty() ) {
- uassert( 12513, "connect failed", scope.exec( _dbConnect , "(connect)" , false , true , false ) );
- if ( !_dbAuth.empty() ) {
- installGlobalUtils( scope );
- uassert( 12514, "login failed", scope.exec( _dbAuth , "(auth)" , true , true , false ) );
- }
- }
- }
-
- // connstr, myuris
- map< string, set<string> > _allMyUris;
- mongo::mutex _allMyUrisMutex("_allMyUrisMutex");
- bool _nokillop = false;
- void onConnect( DBClientWithCommands &c ) {
- latestConn = &c;
- if ( _nokillop ) {
- return;
- }
- BSONObj info;
- if ( c.runCommand( "admin", BSON( "whatsmyuri" << 1 ), info ) ) {
- string connstr = dynamic_cast<DBClientBase&>(c).getServerAddress();
- mongo::mutex::scoped_lock lk( _allMyUrisMutex );
- _allMyUris[connstr].insert(info[ "you" ].str());
- }
- }
- }
-}
diff --git a/shell/utils.h b/shell/utils.h
deleted file mode 100644
index 03b3f97d7ae..00000000000
--- a/shell/utils.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// utils.h
-/*
- * Copyright 2010 10gen Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#pragma once
-
-#include "../scripting/engine.h"
-
-namespace mongo {
-
- namespace shellUtils {
-
- extern std::string _dbConnect;
- extern std::string _dbAuth;
- extern map< string, set<string> > _allMyUris;
- extern bool _nokillop;
-
- void RecordMyLocation( const char *_argv0 );
- void installShellUtils( Scope& scope );
-
- // Scoped management of mongo program instances. Simple implementation:
- // destructor kills all mongod instances created by the shell.
- struct MongoProgramScope {
- MongoProgramScope() {} // Avoid 'unused variable' warning.
- ~MongoProgramScope();
- };
- void KillMongoProgramInstances();
-
- void initScope( Scope &scope );
- void onConnect( DBClientWithCommands &c );
- }
-}
diff --git a/shell/utils.js b/shell/utils.js
deleted file mode 100644
index 4e206034d2a..00000000000
--- a/shell/utils.js
+++ /dev/null
@@ -1,1694 +0,0 @@
-__quiet = false;
-__magicNoPrint = { __magicNoPrint : 1111 }
-
-chatty = function(s){
- if ( ! __quiet )
- print( s );
-}
-
-friendlyEqual = function( a , b ){
- if ( a == b )
- return true;
-
- a = tojson(a,false,true);
- b = tojson(b,false,true);
-
- if ( a == b )
- return true;
-
- var clean = function( s ){
- s = s.replace( /NumberInt\((\-?\d+)\)/g , "$1" );
- return s;
- }
-
- a = clean(a);
- b = clean(b);
-
- if ( a == b )
- return true;
-
- return false;
-}
-
-printStackTrace = function(){
- try{
- throw new Error("Printing Stack Trace");
- } catch (e) {
- print(e.stack);
- }
-}
-
-doassert = function (msg) {
- if (msg.indexOf("assert") == 0)
- print(msg);
- else
- print("assert: " + msg);
- printStackTrace();
- throw msg;
-}
-
-assert = function( b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
- if ( b )
- return;
- doassert( msg == undefined ? "assert failed" : "assert failed : " + msg );
-}
-
-assert.automsg = function( b ) {
- assert( eval( b ), b );
-}
-
-assert._debug = false;
-
-assert.eq = function( a , b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( a == b )
- return;
-
- if ( ( a != null && b != null ) && friendlyEqual( a , b ) )
- return;
-
- doassert( "[" + tojson( a ) + "] != [" + tojson( b ) + "] are not equal : " + msg );
-}
-
-assert.eq.automsg = function( a, b ) {
- assert.eq( eval( a ), eval( b ), "[" + a + "] != [" + b + "]" );
-}
-
-assert.neq = function( a , b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
- if ( a != b )
- return;
-
- doassert( "[" + a + "] != [" + b + "] are equal : " + msg );
-}
-
-assert.contains = function( o, arr, msg ){
- var wasIn = false
-
- if( ! arr.length ){
- for( i in arr ){
- wasIn = arr[i] == o || ( ( arr[i] != null && o != null ) && friendlyEqual( arr[i] , o ) )
- return;
- if( wasIn ) break
- }
- }
- else {
- for( var i = 0; i < arr.length; i++ ){
- wasIn = arr[i] == o || ( ( arr[i] != null && o != null ) && friendlyEqual( arr[i] , o ) )
- if( wasIn ) break
- }
- }
-
- if( ! wasIn ) doassert( tojson( o ) + " was not in " + tojson( arr ) + " : " + msg )
-}
-
-assert.repeat = function( f, msg, timeout, interval ) {
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- var start = new Date();
- timeout = timeout || 30000;
- interval = interval || 200;
- var last;
- while( 1 ) {
-
- if ( typeof( f ) == "string" ){
- if ( eval( f ) )
- return;
- }
- else {
- if ( f() )
- return;
- }
-
- if ( ( new Date() ).getTime() - start.getTime() > timeout )
- break;
- sleep( interval );
- }
-}
-
-assert.soon = function( f, msg, timeout /*ms*/, interval ) {
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- var start = new Date();
- timeout = timeout || 30000;
- interval = interval || 200;
- var last;
- while( 1 ) {
-
- if ( typeof( f ) == "string" ){
- if ( eval( f ) )
- return;
- }
- else {
- if ( f() )
- return;
- }
-
- if ( ( new Date() ).getTime() - start.getTime() > timeout )
- doassert( "assert.soon failed: " + f + ", msg:" + msg );
- sleep( interval );
- }
-}
-
-assert.throws = function( func , params , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( params && typeof( params ) == "string" )
- throw "2nd argument to assert.throws has to be an array"
-
- try {
- func.apply( null , params );
- }
- catch ( e ){
- return e;
- }
-
- doassert( "did not throw exception: " + msg );
-}
-
-assert.throws.automsg = function( func, params ) {
- assert.throws( func, params, func.toString() );
-}
-
-assert.commandWorked = function( res , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( res.ok == 1 )
- return;
-
- doassert( "command failed: " + tojson( res ) + " : " + msg );
-}
-
-assert.commandFailed = function( res , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( res.ok == 0 )
- return;
-
- doassert( "command worked when it should have failed: " + tojson( res ) + " : " + msg );
-}
-
-assert.isnull = function( what , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( what == null )
- return;
-
- doassert( "supposed to null (" + ( msg || "" ) + ") was: " + tojson( what ) );
-}
-
-assert.lt = function( a , b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( a < b )
- return;
- doassert( a + " is not less than " + b + " : " + msg );
-}
-
-assert.gt = function( a , b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( a > b )
- return;
- doassert( a + " is not greater than " + b + " : " + msg );
-}
-
-assert.lte = function( a , b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( a <= b )
- return;
- doassert( a + " is not less than or eq " + b + " : " + msg );
-}
-
-assert.gte = function( a , b , msg ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if ( a >= b )
- return;
- doassert( a + " is not greater than or eq " + b + " : " + msg );
-}
-
-assert.between = function( a, b, c, msg, inclusive ){
- if ( assert._debug && msg ) print( "in assert for: " + msg );
-
- if( ( inclusive == undefined || inclusive == true ) &&
- a <= b && b <= c ) return;
- else if( a < b && b < c ) return;
-
- doassert( b + " is not between " + a + " and " + c + " : " + msg );
-}
-
-assert.betweenIn = function( a, b, c, msg ){ assert.between( a, b, c, msg, true ) }
-assert.betweenEx = function( a, b, c, msg ){ assert.between( a, b, c, msg, false ) }
-
-assert.close = function( a , b , msg , places ){
- if (places === undefined) {
- places = 4;
- }
- if (Math.round((a - b) * Math.pow(10, places)) === 0) {
- return;
- }
- doassert( a + " is not equal to " + b + " within " + places +
- " places, diff: " + (a-b) + " : " + msg );
-};
-
-Object.extend = function( dst , src , deep ){
- for ( var k in src ){
- var v = src[k];
- if ( deep && typeof(v) == "object" ){
- if ( "floatApprox" in v ) { // convert NumberLong properly
- eval( "v = " + tojson( v ) );
- } else {
- v = Object.extend( typeof ( v.length ) == "number" ? [] : {} , v , true );
- }
- }
- dst[k] = v;
- }
- return dst;
-}
-
-Object.merge = function( dst, src, deep ){
- var clone = Object.extend( {}, dst, deep )
- return Object.extend( clone, src, deep )
-}
-
-argumentsToArray = function( a ){
- var arr = [];
- for ( var i=0; i<a.length; i++ )
- arr[i] = a[i];
- return arr;
-}
-
-isString = function( x ){
- return typeof( x ) == "string";
-}
-
-isNumber = function(x){
- return typeof( x ) == "number";
-}
-
-isObject = function( x ){
- return typeof( x ) == "object";
-}
-
-String.prototype.trim = function() {
- return this.replace(/^\s+|\s+$/g,"");
-}
-String.prototype.ltrim = function() {
- return this.replace(/^\s+/,"");
-}
-String.prototype.rtrim = function() {
- return this.replace(/\s+$/,"");
-}
-
-Number.prototype.zeroPad = function(width) {
- var str = this + '';
- while (str.length < width)
- str = '0' + str;
- return str;
-}
-
-Date.timeFunc = function( theFunc , numTimes ){
-
- var start = new Date();
-
- numTimes = numTimes || 1;
- for ( var i=0; i<numTimes; i++ ){
- theFunc.apply( null , argumentsToArray( arguments ).slice( 2 ) );
- }
-
- return (new Date()).getTime() - start.getTime();
-}
-
-Date.prototype.tojson = function(){
-
- var UTC = Date.printAsUTC ? 'UTC' : '';
-
- var year = this['get'+UTC+'FullYear']().zeroPad(4);
- var month = (this['get'+UTC+'Month']() + 1).zeroPad(2);
- var date = this['get'+UTC+'Date']().zeroPad(2);
- var hour = this['get'+UTC+'Hours']().zeroPad(2);
- var minute = this['get'+UTC+'Minutes']().zeroPad(2);
- var sec = this['get'+UTC+'Seconds']().zeroPad(2)
-
- if (this['get'+UTC+'Milliseconds']())
- sec += '.' + this['get'+UTC+'Milliseconds']().zeroPad(3)
-
- var ofs = 'Z';
- if (!Date.printAsUTC){
- var ofsmin = this.getTimezoneOffset();
- if (ofsmin != 0){
- ofs = ofsmin > 0 ? '-' : '+'; // This is correct
- ofs += (ofsmin/60).zeroPad(2)
- ofs += (ofsmin%60).zeroPad(2)
- }
- }
-
- return 'ISODate("'+year+'-'+month+'-'+date+'T'+hour+':'+minute+':'+sec+ofs+'")';
-}
-
-Date.printAsUTC = true;
-
-
-ISODate = function(isoDateStr){
- if (!isoDateStr)
- return new Date();
-
- var isoDateRegex = /(\d{4})-?(\d{2})-?(\d{2})([T ](\d{2})(:?(\d{2})(:?(\d{2}(\.\d+)?))?)?(Z|([+-])(\d{2}):?(\d{2})?)?)?/;
- var res = isoDateRegex.exec(isoDateStr);
-
- if (!res)
- throw "invalid ISO date";
-
- var year = parseInt(res[1],10) || 1970; // this should always be present
- var month = (parseInt(res[2],10) || 1) - 1;
- var date = parseInt(res[3],10) || 0;
- var hour = parseInt(res[5],10) || 0;
- var min = parseInt(res[7],10) || 0;
- var sec = parseFloat(res[9]) || 0;
- var ms = Math.round((sec%1) * 1000)
- sec -= ms/1000
-
- var time = Date.UTC(year, month, date, hour, min, sec, ms);
-
- if (res[11] && res[11] != 'Z'){
- var ofs = 0;
- ofs += (parseInt(res[13],10) || 0) * 60*60*1000; // hours
- ofs += (parseInt(res[14],10) || 0) * 60*1000; // mins
- if (res[12] == '+') // if ahead subtract
- ofs *= -1;
-
- time += ofs
- }
-
- return new Date(time);
-}
-
-RegExp.prototype.tojson = RegExp.prototype.toString;
-
-Array.contains = function( a , x ){
- for ( var i=0; i<a.length; i++ ){
- if ( a[i] == x )
- return true;
- }
- return false;
-}
-
-Array.unique = function( a ){
- var u = [];
- for ( var i=0; i<a.length; i++){
- var o = a[i];
- if ( ! Array.contains( u , o ) ){
- u.push( o );
- }
- }
- return u;
-}
-
-Array.shuffle = function( arr ){
- for ( var i=0; i<arr.length-1; i++ ){
- var pos = i+Random.randInt(arr.length-i);
- var save = arr[i];
- arr[i] = arr[pos];
- arr[pos] = save;
- }
- return arr;
-}
-
-
-Array.tojson = function( a , indent , nolint ){
- var lineEnding = nolint ? " " : "\n";
-
- if (!indent)
- indent = "";
-
- if ( nolint )
- indent = "";
-
- if (a.length == 0) {
- return "[ ]";
- }
-
- var s = "[" + lineEnding;
- indent += "\t";
- for ( var i=0; i<a.length; i++){
- s += indent + tojson( a[i], indent , nolint );
- if ( i < a.length - 1 ){
- s += "," + lineEnding;
- }
- }
- if ( a.length == 0 ) {
- s += indent;
- }
-
- indent = indent.substring(1);
- s += lineEnding+indent+"]";
- return s;
-}
-
-Array.fetchRefs = function( arr , coll ){
- var n = [];
- for ( var i=0; i<arr.length; i ++){
- var z = arr[i];
- if ( coll && coll != z.getCollection() )
- continue;
- n.push( z.fetch() );
- }
-
- return n;
-}
-
-Array.sum = function( arr ){
- if ( arr.length == 0 )
- return null;
- var s = arr[0];
- for ( var i=1; i<arr.length; i++ )
- s += arr[i];
- return s;
-}
-
-Array.avg = function( arr ){
- if ( arr.length == 0 )
- return null;
- return Array.sum( arr ) / arr.length;
-}
-
-Array.stdDev = function( arr ){
- var avg = Array.avg( arr );
- var sum = 0;
-
- for ( var i=0; i<arr.length; i++ ){
- sum += Math.pow( arr[i] - avg , 2 );
- }
-
- return Math.sqrt( sum / arr.length );
-}
-
-//these two are helpers for Array.sort(func)
-compare = function(l, r){ return (l == r ? 0 : (l < r ? -1 : 1)); }
-
-// arr.sort(compareOn('name'))
-compareOn = function(field){
- return function(l, r) { return compare(l[field], r[field]); }
-}
-
-Object.keySet = function( o ) {
- var ret = new Array();
- for( i in o ) {
- if ( !( i in o.__proto__ && o[ i ] === o.__proto__[ i ] ) ) {
- ret.push( i );
- }
- }
- return ret;
-}
-
-if ( ! NumberLong.prototype ) {
- NumberLong.prototype = {}
-}
-
-NumberLong.prototype.tojson = function() {
- return this.toString();
-}
-
-if ( ! NumberInt.prototype ) {
- NumberInt.prototype = {}
-}
-
-NumberInt.prototype.tojson = function() {
- return this.toString();
-}
-
-if ( ! ObjectId.prototype )
- ObjectId.prototype = {}
-
-ObjectId.prototype.toString = function(){
- return this.str;
-}
-
-ObjectId.prototype.tojson = function(){
- return "ObjectId(\"" + this.str + "\")";
-}
-
-ObjectId.prototype.isObjectId = true;
-
-ObjectId.prototype.getTimestamp = function(){
- return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
-}
-
-ObjectId.prototype.equals = function( other){
- return this.str == other.str;
-}
-
-if ( typeof( DBPointer ) != "undefined" ){
- DBPointer.prototype.fetch = function(){
- assert( this.ns , "need a ns" );
- assert( this.id , "need an id" );
-
- return db[ this.ns ].findOne( { _id : this.id } );
- }
-
- DBPointer.prototype.tojson = function(indent){
- return tojson({"ns" : this.ns, "id" : this.id}, indent);
- }
-
- DBPointer.prototype.getCollection = function(){
- return this.ns;
- }
-
- DBPointer.prototype.toString = function(){
- return "DBPointer " + this.ns + ":" + this.id;
- }
-}
-else {
- print( "warning: no DBPointer" );
-}
-
-if ( typeof( DBRef ) != "undefined" ){
- DBRef.prototype.fetch = function(){
- assert( this.$ref , "need a ns" );
- assert( this.$id , "need an id" );
-
- return db[ this.$ref ].findOne( { _id : this.$id } );
- }
-
- DBRef.prototype.tojson = function(indent){
- return tojson({"$ref" : this.$ref, "$id" : this.$id}, indent);
- }
-
- DBRef.prototype.getCollection = function(){
- return this.$ref;
- }
-
- DBRef.prototype.toString = function(){
- return this.tojson();
- }
-}
-else {
- print( "warning: no DBRef" );
-}
-
-if ( typeof( BinData ) != "undefined" ){
- BinData.prototype.tojson = function () {
- //return "BinData type: " + this.type + " len: " + this.len;
- return this.toString();
- }
-
- BinData.prototype.subtype = function () {
- return this.type;
- }
-
- BinData.prototype.length = function () {
- return this.len;
- }
-}
-else {
- print( "warning: no BinData class" );
-}
-
-/*if ( typeof( UUID ) != "undefined" ){
- UUID.prototype.tojson = function () {
- return this.toString();
- }
-}*/
-
-if ( typeof _threadInject != "undefined" ){
- print( "fork() available!" );
-
- Thread = function(){
- this.init.apply( this, arguments );
- }
- _threadInject( Thread.prototype );
-
- ScopedThread = function() {
- this.init.apply( this, arguments );
- }
- ScopedThread.prototype = new Thread( function() {} );
- _scopedThreadInject( ScopedThread.prototype );
-
- fork = function() {
- var t = new Thread( function() {} );
- Thread.apply( t, arguments );
- return t;
- }
-
- // Helper class to generate a list of events which may be executed by a ParallelTester
- EventGenerator = function( me, collectionName, mean ) {
- this.mean = mean;
- this.events = new Array( me, collectionName );
- }
-
- EventGenerator.prototype._add = function( action ) {
- this.events.push( [ Random.genExp( this.mean ), action ] );
- }
-
- EventGenerator.prototype.addInsert = function( obj ) {
- this._add( "t.insert( " + tojson( obj ) + " )" );
- }
-
- EventGenerator.prototype.addRemove = function( obj ) {
- this._add( "t.remove( " + tojson( obj ) + " )" );
- }
-
- EventGenerator.prototype.addUpdate = function( objOld, objNew ) {
- this._add( "t.update( " + tojson( objOld ) + ", " + tojson( objNew ) + " )" );
- }
-
- EventGenerator.prototype.addCheckCount = function( count, query, shouldPrint, checkQuery ) {
- query = query || {};
- shouldPrint = shouldPrint || false;
- checkQuery = checkQuery || false;
- var action = "assert.eq( " + count + ", t.count( " + tojson( query ) + " ) );"
- if ( checkQuery ) {
- action += " assert.eq( " + count + ", t.find( " + tojson( query ) + " ).toArray().length );"
- }
- if ( shouldPrint ) {
- action += " print( me + ' ' + " + count + " );";
- }
- this._add( action );
- }
-
- EventGenerator.prototype.getEvents = function() {
- return this.events;
- }
-
- EventGenerator.dispatch = function() {
- var args = argumentsToArray( arguments );
- var me = args.shift();
- var collectionName = args.shift();
- var m = new Mongo( db.getMongo().host );
- var t = m.getDB( "test" )[ collectionName ];
- for( var i in args ) {
- sleep( args[ i ][ 0 ] );
- eval( args[ i ][ 1 ] );
- }
- }
-
- // Helper class for running tests in parallel. It assembles a set of tests
- // and then calls assert.parallelests to run them.
- ParallelTester = function() {
- this.params = new Array();
- }
-
- ParallelTester.prototype.add = function( fun, args ) {
- args = args || [];
- args.unshift( fun );
- this.params.push( args );
- }
-
- ParallelTester.prototype.run = function( msg, newScopes ) {
- newScopes = newScopes || false;
- assert.parallelTests( this.params, msg, newScopes );
- }
-
- // creates lists of tests from jstests dir in a format suitable for use by
- // ParallelTester.fileTester. The lists will be in random order.
- // n: number of lists to split these tests into
- ParallelTester.createJstestsLists = function( n ) {
- var params = new Array();
- for( var i = 0; i < n; ++i ) {
- params.push( [] );
- }
-
- var makeKeys = function( a ) {
- var ret = {};
- for( var i in a ) {
- ret[ a[ i ] ] = 1;
- }
- return ret;
- }
-
- // some tests can't run in parallel with most others
- var skipTests = makeKeys( [ "jstests/dbadmin.js",
- "jstests/repair.js",
- "jstests/cursor8.js",
- "jstests/recstore.js",
- "jstests/extent.js",
- "jstests/indexb.js",
- "jstests/profile1.js",
- "jstests/mr3.js",
- "jstests/indexh.js",
- "jstests/apitest_db.js",
- "jstests/evalb.js",
- "jstests/evald.js",
- "jstests/evalf.js",
- "jstests/killop.js",
- "jstests/run_program1.js",
- "jstests/notablescan.js",
- "jstests/drop2.js",
- "jstests/dropdb_race.js",
- "jstests/bench_test1.js",
- "jstests/queryoptimizera.js"] );
-
- // some tests can't be run in parallel with each other
- var serialTestsArr = [ "jstests/fsync.js",
- "jstests/fsync2.js" ];
- var serialTests = makeKeys( serialTestsArr );
-
- params[ 0 ] = serialTestsArr;
-
- var files = listFiles("jstests");
- files = Array.shuffle( files );
-
- var i = 0;
- files.forEach(
- function(x) {
-
- if ( ( /[\/\\]_/.test(x.name) ) ||
- ( ! /\.js$/.test(x.name ) ) ||
- ( x.name in skipTests ) ||
- ( x.name in serialTests ) ||
- ! /\.js$/.test(x.name ) ){
- print(" >>>>>>>>>>>>>>> skipping " + x.name);
- return;
- }
-
- params[ i % n ].push( x.name );
- ++i;
- }
- );
-
- // randomize ordering of the serialTests
- params[ 0 ] = Array.shuffle( params[ 0 ] );
-
- for( var i in params ) {
- params[ i ].unshift( i );
- }
-
- return params;
- }
-
- // runs a set of test files
- // first argument is an identifier for this tester, remaining arguments are file names
- ParallelTester.fileTester = function() {
- var args = argumentsToArray( arguments );
- var suite = args.shift();
- args.forEach(
- function( x ) {
- print(" S" + suite + " Test : " + x + " ...");
- var time = Date.timeFunc( function() { load(x); }, 1);
- print(" S" + suite + " Test : " + x + " " + time + "ms" );
- }
- );
- }
-
- // params: array of arrays, each element of which consists of a function followed
- // by zero or more arguments to that function. Each function and its arguments will
- // be called in a separate thread.
- // msg: failure message
- // newScopes: if true, each thread starts in a fresh scope
- assert.parallelTests = function( params, msg, newScopes ) {
- newScopes = newScopes || false;
- var wrapper = function( fun, argv ) {
- eval (
- "var z = function() {" +
- "var __parallelTests__fun = " + fun.toString() + ";" +
- "var __parallelTests__argv = " + tojson( argv ) + ";" +
- "var __parallelTests__passed = false;" +
- "try {" +
- "__parallelTests__fun.apply( 0, __parallelTests__argv );" +
- "__parallelTests__passed = true;" +
- "} catch ( e ) {" +
- "print( '********** Parallel Test FAILED: ' + tojson(e) );" +
- "}" +
- "return __parallelTests__passed;" +
- "}"
- );
- return z;
- }
- var runners = new Array();
- for( var i in params ) {
- var param = params[ i ];
- var test = param.shift();
- var t;
- if ( newScopes )
- t = new ScopedThread( wrapper( test, param ) );
- else
- t = new Thread( wrapper( test, param ) );
- runners.push( t );
- }
-
- runners.forEach( function( x ) { x.start(); } );
- var nFailed = 0;
- // v8 doesn't like it if we exit before all threads are joined (SERVER-529)
- runners.forEach( function( x ) { if( !x.returnData() ) { ++nFailed; } } );
- assert.eq( 0, nFailed, msg );
- }
-}
-
-tojsononeline = function( x ){
- return tojson( x , " " , true );
-}
-
-tojson = function( x, indent , nolint ){
- if ( x === null )
- return "null";
-
- if ( x === undefined )
- return "undefined";
-
- if (!indent)
- indent = "";
-
- switch ( typeof x ) {
- case "string": {
- var s = "\"";
- for ( var i=0; i<x.length; i++ ){
- switch (x[i]){
- case '"': s += '\\"'; break;
- case '\\': s += '\\\\'; break;
- case '\b': s += '\\b'; break;
- case '\f': s += '\\f'; break;
- case '\n': s += '\\n'; break;
- case '\r': s += '\\r'; break;
- case '\t': s += '\\t'; break;
-
- default: {
- var code = x.charCodeAt(i);
- if (code < 0x20){
- s += (code < 0x10 ? '\\u000' : '\\u00') + code.toString(16);
- } else {
- s += x[i];
- }
- }
- }
- }
- return s + "\"";
- }
- case "number":
- case "boolean":
- return "" + x;
- case "object":{
- var s = tojsonObject( x, indent , nolint );
- if ( ( nolint == null || nolint == true ) && s.length < 80 && ( indent == null || indent.length == 0 ) ){
- s = s.replace( /[\s\r\n ]+/gm , " " );
- }
- return s;
- }
- case "function":
- return x.toString();
- default:
- throw "tojson can't handle type " + ( typeof x );
- }
-
-}
-
-tojsonObject = function( x, indent , nolint ){
- var lineEnding = nolint ? " " : "\n";
- var tabSpace = nolint ? "" : "\t";
-
- assert.eq( ( typeof x ) , "object" , "tojsonObject needs object, not [" + ( typeof x ) + "]" );
-
- if (!indent)
- indent = "";
-
- if ( typeof( x.tojson ) == "function" && x.tojson != tojson ) {
- return x.tojson(indent,nolint);
- }
-
- if ( x.constructor && typeof( x.constructor.tojson ) == "function" && x.constructor.tojson != tojson ) {
- return x.constructor.tojson( x, indent , nolint );
- }
-
- if ( x.toString() == "[object MaxKey]" )
- return "{ $maxKey : 1 }";
- if ( x.toString() == "[object MinKey]" )
- return "{ $minKey : 1 }";
-
- var s = "{" + lineEnding;
-
- // push one level of indent
- indent += tabSpace;
-
- var total = 0;
- for ( var k in x ) total++;
- if ( total == 0 ) {
- s += indent + lineEnding;
- }
-
- var keys = x;
- if ( typeof( x._simpleKeys ) == "function" )
- keys = x._simpleKeys();
- var num = 1;
- for ( var k in keys ){
-
- var val = x[k];
- if ( val == DB.prototype || val == DBCollection.prototype )
- continue;
-
- s += indent + "\"" + k + "\" : " + tojson( val, indent , nolint );
- if (num != total) {
- s += ",";
- num++;
- }
- s += lineEnding;
- }
-
- // pop one level of indent
- indent = indent.substring(1);
- return s + indent + "}";
-}
-
-shellPrint = function( x ){
- it = x;
- if ( x != undefined )
- shellPrintHelper( x );
-
- if ( db ){
- var e = db.getPrevError();
- if ( e.err ) {
- if( e.nPrev <= 1 )
- print( "error on last call: " + tojson( e.err ) );
- else
- print( "an error " + tojson(e.err) + " occurred " + e.nPrev + " operations back in the command invocation" );
- }
- db.resetError();
- }
-}
-
-printjson = function(x){
- print( tojson( x ) );
-}
-
-printjsononeline = function(x){
- print( tojsononeline( x ) );
-}
-
-if ( typeof TestData == "undefined" ){
- TestData = undefined
-}
-
-jsTestName = function(){
- if( TestData ) return TestData.testName
- return "__unknown_name__"
-}
-
-jsTestFile = function(){
- if( TestData ) return TestData.testFile
- return "__unknown_file__"
-}
-
-jsTestPath = function(){
- if( TestData ) return TestData.testPath
- return "__unknown_path__"
-}
-
-jsTestOptions = function(){
- if( TestData ) return { noJournal : TestData.noJournal,
- noJournalPrealloc : TestData.noJournalPrealloc }
- return {}
-}
-
-jsTestLog = function(msg){
- print( "\n\n----\n" + msg + "\n----\n\n" )
-}
-
-shellPrintHelper = function (x) {
-
- if (typeof (x) == "undefined") {
-
- if (typeof (db) != "undefined" && db.getLastError) {
- // explicit w:1 so that replset getLastErrorDefaults aren't used here which would be bad.
- var e = db.getLastError(1);
- if (e != null)
- print(e);
- }
-
- return;
- }
-
- if (x == __magicNoPrint)
- return;
-
- if (x == null) {
- print("null");
- return;
- }
-
- if (typeof x != "object")
- return print(x);
-
- var p = x.shellPrint;
- if (typeof p == "function")
- return x.shellPrint();
-
- var p = x.tojson;
- if (typeof p == "function")
- print(x.tojson());
- else
- print(tojson(x));
-}
-
-shellAutocomplete = function (/*prefix*/){ // outer scope function called on init. Actual function at end
-
- var universalMethods = "constructor prototype toString valueOf toLocaleString hasOwnProperty propertyIsEnumerable".split(' ');
-
- var builtinMethods = {}; // uses constructor objects as keys
- builtinMethods[Array] = "length concat join pop push reverse shift slice sort splice unshift indexOf lastIndexOf every filter forEach map some".split(' ');
- builtinMethods[Boolean] = "".split(' '); // nothing more than universal methods
- builtinMethods[Date] = "getDate getDay getFullYear getHours getMilliseconds getMinutes getMonth getSeconds getTime getTimezoneOffset getUTCDate getUTCDay getUTCFullYear getUTCHours getUTCMilliseconds getUTCMinutes getUTCMonth getUTCSeconds getYear parse setDate setFullYear setHours setMilliseconds setMinutes setMonth setSeconds setTime setUTCDate setUTCFullYear setUTCHours setUTCMilliseconds setUTCMinutes setUTCMonth setUTCSeconds setYear toDateString toGMTString toLocaleDateString toLocaleTimeString toTimeString toUTCString UTC".split(' ');
- builtinMethods[Math] = "E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan".split(' ');
- builtinMethods[Number] = "MAX_VALUE MIN_VALUE NEGATIVE_INFINITY POSITIVE_INFINITY toExponential toFixed toPrecision".split(' ');
- builtinMethods[RegExp] = "global ignoreCase lastIndex multiline source compile exec test".split(' ');
- builtinMethods[String] = "length charAt charCodeAt concat fromCharCode indexOf lastIndexOf match replace search slice split substr substring toLowerCase toUpperCase".split(' ');
- builtinMethods[Function] = "call apply".split(' ');
- builtinMethods[Object] = "bsonsize".split(' ');
-
- builtinMethods[Mongo] = "find update insert remove".split(' ');
- builtinMethods[BinData] = "hex base64 length subtype".split(' ');
-
- var extraGlobals = "Infinity NaN undefined null true false decodeURI decodeURIComponent encodeURI encodeURIComponent escape eval isFinite isNaN parseFloat parseInt unescape Array Boolean Date Math Number RegExp String print load gc MinKey MaxKey Mongo NumberLong ObjectId DBPointer UUID BinData Map".split(' ');
-
- var isPrivate = function(name){
- if (shellAutocomplete.showPrivate) return false;
- if (name == '_id') return false;
- if (name[0] == '_') return true;
- if (name[name.length-1] == '_') return true; // some native functions have an extra name_ method
- return false;
- }
-
- var customComplete = function(obj){
- try {
- if(obj.__proto__.constructor.autocomplete){
- var ret = obj.constructor.autocomplete(obj);
- if (ret.constructor != Array){
- print("\nautocompleters must return real Arrays");
- return [];
- }
- return ret;
- } else {
- return [];
- }
- } catch (e) {
- // print(e); // uncomment if debugging custom completers
- return [];
- }
- }
-
- var worker = function( prefix ){
- var global = (function(){return this;}).call(); // trick to get global object
-
- var curObj = global;
- var parts = prefix.split('.');
- for (var p=0; p < parts.length - 1; p++){ // doesn't include last part
- curObj = curObj[parts[p]];
- if (curObj == null)
- return [];
- }
-
- var lastPrefix = parts[parts.length-1] || '';
- var begining = parts.slice(0, parts.length-1).join('.');
- if (begining.length)
- begining += '.';
-
- var possibilities = new Array().concat(
- universalMethods,
- Object.keySet(curObj),
- Object.keySet(curObj.__proto__),
- builtinMethods[curObj] || [], // curObj is a builtin constructor
- builtinMethods[curObj.__proto__.constructor] || [], // curObj is made from a builtin constructor
- curObj == global ? extraGlobals : [],
- customComplete(curObj)
- );
-
- var ret = [];
- for (var i=0; i < possibilities.length; i++){
- var p = possibilities[i];
- if (typeof(curObj[p]) == "undefined" && curObj != global) continue; // extraGlobals aren't in the global object
- if (p.length == 0 || p.length < lastPrefix.length) continue;
- if (lastPrefix[0] != '_' && isPrivate(p)) continue;
- if (p.match(/^[0-9]+$/)) continue; // don't array number indexes
- if (p.substr(0, lastPrefix.length) != lastPrefix) continue;
-
- var completion = begining + p;
- if(curObj[p] && curObj[p].constructor == Function && p != 'constructor')
- completion += '(';
-
- ret.push(completion);
- }
-
- return ret;
- }
-
- // this is the actual function that gets assigned to shellAutocomplete
- return function( prefix ){
- try {
- __autocomplete__ = worker(prefix).sort();
- }catch (e){
- print("exception durring autocomplete: " + tojson(e.message));
- __autocomplete__ = [];
- }
- }
-}();
-
-shellAutocomplete.showPrivate = false; // toggle to show (useful when working on internals)
-
-shellHelper = function( command , rest , shouldPrint ){
- command = command.trim();
- var args = rest.trim().replace(/\s*;$/,"").split( "\s+" );
-
- if ( ! shellHelper[command] )
- throw "no command [" + command + "]";
-
- var res = shellHelper[command].apply( null , args );
- if ( shouldPrint ){
- shellPrintHelper( res );
- }
- return res;
-}
-
-shellHelper.use = function (dbname) {
- var s = "" + dbname;
- if (s == "") {
- print("bad use parameter");
- return;
- }
- db = db.getMongo().getDB(dbname);
- print("switched to db " + db.getName());
-}
-
-shellHelper.it = function(){
- if ( typeof( ___it___ ) == "undefined" || ___it___ == null ){
- print( "no cursor" );
- return;
- }
- shellPrintHelper( ___it___ );
-}
-
-shellHelper.show = function (what) {
- assert(typeof what == "string");
-
- var args = what.split( /\s+/ );
- what = args[0]
- args = args.splice(1)
-
- if (what == "profile") {
- if (db.system.profile.count() == 0) {
- print("db.system.profile is empty");
- print("Use db.setProfilingLevel(2) will enable profiling");
- print("Use db.system.profile.find() to show raw profile entries");
- }
- else {
- print();
- db.system.profile.find({ millis: { $gt: 0} }).sort({ $natural: -1 }).limit(5).forEach(
- function (x) {
- print("" + x.op + "\t" + x.ns + " " + x.millis + "ms " + String(x.ts).substring(0, 24));
- var l = "";
- for ( var z in x ){
- if ( z == "op" || z == "ns" || z == "millis" || z == "ts" )
- continue;
-
- var val = x[z];
- var mytype = typeof(val);
-
- if ( mytype == "string" ||
- mytype == "number" )
- l += z + ":" + val + " ";
- else if ( mytype == "object" )
- l += z + ":" + tojson(val ) + " ";
- else if ( mytype == "boolean" )
- l += z + " ";
- else
- l += z + ":" + val + " ";
-
- }
- print( l );
- print("\n");
- }
- )
- }
- return "";
- }
-
- if (what == "users") {
- db.system.users.find().forEach(printjson);
- return "";
- }
-
- if (what == "collections" || what == "tables") {
- db.getCollectionNames().forEach(function (x) { print(x) });
- return "";
- }
-
- if (what == "dbs") {
- var dbs = db.getMongo().getDBs();
- var size = {};
- dbs.databases.forEach(function (x) { size[x.name] = x.sizeOnDisk; });
- var names = dbs.databases.map(function (z) { return z.name; }).sort();
- names.forEach(function (n) {
- if (size[n] > 1) {
- print(n + "\t" + size[n] / 1024 / 1024 / 1024 + "GB");
- } else {
- print(n + "\t(empty)");
- }
- });
- //db.getMongo().getDBNames().sort().forEach(function (x) { print(x) });
- return "";
- }
-
- if (what == "log" ) {
- var n = "global";
- if ( args.length > 0 )
- n = args[0]
-
- var res = db.adminCommand( { getLog : n } )
- for ( var i=0; i<res.log.length; i++){
- print( res.log[i] )
- }
- return ""
- }
-
- if (what == "logs" ) {
- var res = db.adminCommand( { getLog : "*" } )
- for ( var i=0; i<res.names.length; i++){
- print( res.names[i] )
- }
- return ""
- }
-
-
- throw "don't know how to show [" + what + "]";
-
-}
-
-if ( typeof( Map ) == "undefined" ){
- Map = function(){
- this._data = {};
- }
-}
-
-Map.hash = function( val ){
- if ( ! val )
- return val;
-
- switch ( typeof( val ) ){
- case 'string':
- case 'number':
- case 'date':
- return val.toString();
- case 'object':
- case 'array':
- var s = "";
- for ( var k in val ){
- s += k + val[k];
- }
- return s;
- }
-
- throw "can't hash : " + typeof( val );
-}
-
-Map.prototype.put = function( key , value ){
- var o = this._get( key );
- var old = o.value;
- o.value = value;
- return old;
-}
-
-Map.prototype.get = function( key ){
- return this._get( key ).value;
-}
-
-Map.prototype._get = function( key ){
- var h = Map.hash( key );
- var a = this._data[h];
- if ( ! a ){
- a = [];
- this._data[h] = a;
- }
-
- for ( var i=0; i<a.length; i++ ){
- if ( friendlyEqual( key , a[i].key ) ){
- return a[i];
- }
- }
- var o = { key : key , value : null };
- a.push( o );
- return o;
-}
-
-Map.prototype.values = function(){
- var all = [];
- for ( var k in this._data ){
- this._data[k].forEach( function(z){ all.push( z.value ); } );
- }
- return all;
-}
-
-if ( typeof( gc ) == "undefined" ){
- gc = function(){
- print( "warning: using noop gc()" );
- }
-}
-
-
-Math.sigFig = function( x , N ){
- if ( ! N ){
- N = 3;
- }
- var p = Math.pow( 10, N - Math.ceil( Math.log( Math.abs(x) ) / Math.log( 10 )) );
- return Math.round(x*p)/p;
-}
-
-Random = function() {}
-
-// set random seed
-Random.srand = function( s ) { _srand( s ); }
-
-// random number 0 <= r < 1
-Random.rand = function() { return _rand(); }
-
-// random integer 0 <= r < n
-Random.randInt = function( n ) { return Math.floor( Random.rand() * n ); }
-
-Random.setRandomSeed = function( s ) {
- s = s || new Date().getTime();
- print( "setting random seed: " + s );
- Random.srand( s );
-}
-
-// generate a random value from the exponential distribution with the specified mean
-Random.genExp = function( mean ) {
- return -Math.log( Random.rand() ) * mean;
-}
-
-Geo = {};
-Geo.distance = function( a , b ){
- var ax = null;
- var ay = null;
- var bx = null;
- var by = null;
-
- for ( var key in a ){
- if ( ax == null )
- ax = a[key];
- else if ( ay == null )
- ay = a[key];
- }
-
- for ( var key in b ){
- if ( bx == null )
- bx = b[key];
- else if ( by == null )
- by = b[key];
- }
-
- return Math.sqrt( Math.pow( by - ay , 2 ) +
- Math.pow( bx - ax , 2 ) );
-}
-
-Geo.sphereDistance = function( a , b ){
- var ax = null;
- var ay = null;
- var bx = null;
- var by = null;
-
- // TODO swap order of x and y when done on server
- for ( var key in a ){
- if ( ax == null )
- ax = a[key] * (Math.PI/180);
- else if ( ay == null )
- ay = a[key] * (Math.PI/180);
- }
-
- for ( var key in b ){
- if ( bx == null )
- bx = b[key] * (Math.PI/180);
- else if ( by == null )
- by = b[key] * (Math.PI/180);
- }
-
- var sin_x1=Math.sin(ax), cos_x1=Math.cos(ax);
- var sin_y1=Math.sin(ay), cos_y1=Math.cos(ay);
- var sin_x2=Math.sin(bx), cos_x2=Math.cos(bx);
- var sin_y2=Math.sin(by), cos_y2=Math.cos(by);
-
- var cross_prod =
- (cos_y1*cos_x1 * cos_y2*cos_x2) +
- (cos_y1*sin_x1 * cos_y2*sin_x2) +
- (sin_y1 * sin_y2);
-
- if (cross_prod >= 1 || cross_prod <= -1){
- // fun with floats
- assert( Math.abs(cross_prod)-1 < 1e-6 );
- return cross_prod > 0 ? 0 : Math.PI;
- }
-
- return Math.acos(cross_prod);
-}
-
-rs = function () { return "try rs.help()"; }
-
-rs.help = function () {
- print("\trs.status() { replSetGetStatus : 1 } checks repl set status");
- print("\trs.initiate() { replSetInitiate : null } initiates set with default settings");
- print("\trs.initiate(cfg) { replSetInitiate : cfg } initiates set with configuration cfg");
- print("\trs.conf() get the current configuration object from local.system.replset");
- print("\trs.reconfig(cfg) updates the configuration of a running replica set with cfg (disconnects)");
- print("\trs.add(hostportstr) add a new member to the set with default attributes (disconnects)");
- print("\trs.add(membercfgobj) add a new member to the set with extra attributes (disconnects)");
- print("\trs.addArb(hostportstr) add a new member which is arbiterOnly:true (disconnects)");
- print("\trs.stepDown([secs]) step down as primary (momentarily) (disconnects)");
- print("\trs.freeze(secs) make a node ineligible to become primary for the time specified");
- print("\trs.remove(hostportstr) remove a host from the replica set (disconnects)");
- print("\trs.slaveOk() shorthand for db.getMongo().setSlaveOk()");
- print();
- print("\tdb.isMaster() check who is primary");
- print();
- print("\treconfiguration helpers disconnect from the database so the shell will display");
- print("\tan error, even if the command succeeds.");
- print("\tsee also http://<mongod_host>:28017/_replSet for additional diagnostic info");
-}
-rs.slaveOk = function () { return db.getMongo().setSlaveOk(); }
-rs.status = function () { return db._adminCommand("replSetGetStatus"); }
-rs.isMaster = function () { return db.isMaster(); }
-rs.initiate = function (c) { return db._adminCommand({ replSetInitiate: c }); }
-rs._runCmd = function (c) {
- // after the command, catch the disconnect and reconnect if necessary
- var res = null;
- try {
- res = db.adminCommand(c);
- }
- catch (e) {
- if (("" + e).indexOf("error doing query") >= 0) {
- // closed connection. reconnect.
- db.getLastErrorObj();
- var o = db.getLastErrorObj();
- if (o.ok) {
- print("reconnected to server after rs command (which is normal)");
- }
- else {
- printjson(o);
- }
- }
- else {
- print("shell got exception during repl set operation: " + e);
- print("in some circumstances, the primary steps down and closes connections on a reconfig");
- }
- return "";
- }
- return res;
-}
-rs.reconfig = function (cfg, options) {
- cfg.version = rs.conf().version + 1;
- cmd = { replSetReconfig: cfg };
- for (var i in options) {
- cmd[i] = options[i];
- }
- return this._runCmd(cmd);
-}
-rs.add = function (hostport, arb) {
- var cfg = hostport;
-
- var local = db.getSisterDB("local");
- assert(local.system.replset.count() <= 1, "error: local.system.replset has unexpected contents");
- var c = local.system.replset.findOne();
- assert(c, "no config object retrievable from local.system.replset");
-
- c.version++;
-
- var max = 0;
- for (var i in c.members)
- if (c.members[i]._id > max) max = c.members[i]._id;
- if (isString(hostport)) {
- cfg = { _id: max + 1, host: hostport };
- if (arb)
- cfg.arbiterOnly = true;
- }
- c.members.push(cfg);
- return this._runCmd({ replSetReconfig: c });
-}
-rs.stepDown = function (secs) { return db._adminCommand({ replSetStepDown:(secs === undefined) ? 60:secs}); }
-rs.freeze = function (secs) { return db._adminCommand({replSetFreeze:secs}); }
-rs.addArb = function (hn) { return this.add(hn, true); }
-rs.conf = function () { return db.getSisterDB("local").system.replset.findOne(); }
-rs.config = function () { return rs.conf(); }
-
-rs.remove = function (hn) {
- var local = db.getSisterDB("local");
- assert(local.system.replset.count() <= 1, "error: local.system.replset has unexpected contents");
- var c = local.system.replset.findOne();
- assert(c, "no config object retrievable from local.system.replset");
- c.version++;
-
- for (var i in c.members) {
- if (c.members[i].host == hn) {
- c.members.splice(i, 1);
- return db._adminCommand({ replSetReconfig : c});
- }
- }
-
- return "error: couldn't find "+hn+" in "+tojson(c.members);
-};
-
-rs.debug = {};
-
-rs.debug.nullLastOpWritten = function(primary, secondary) {
- var p = connect(primary+"/local");
- var s = connect(secondary+"/local");
- s.getMongo().setSlaveOk();
-
- var secondToLast = s.oplog.rs.find().sort({$natural : -1}).limit(1).next();
- var last = p.runCommand({findAndModify : "oplog.rs",
- query : {ts : {$gt : secondToLast.ts}},
- sort : {$natural : 1},
- update : {$set : {op : "n"}}});
-
- if (!last.value.o || !last.value.o._id) {
- print("couldn't find an _id?");
- }
- else {
- last.value.o = {_id : last.value.o._id};
- }
-
- print("nulling out this op:");
- printjson(last);
-};
-
-rs.debug.getLastOpWritten = function(server) {
- var s = db.getSisterDB("local");
- if (server) {
- s = connect(server+"/local");
- }
- s.getMongo().setSlaveOk();
-
- return s.oplog.rs.find().sort({$natural : -1}).limit(1).next();
-};
-
-
-help = shellHelper.help = function (x) {
- if (x == "mr") {
- print("\nSee also http://www.mongodb.org/display/DOCS/MapReduce");
- print("\nfunction mapf() {");
- print(" // 'this' holds current document to inspect");
- print(" emit(key, value);");
- print("}");
- print("\nfunction reducef(key,value_array) {");
- print(" return reduced_value;");
- print("}");
- print("\ndb.mycollection.mapReduce(mapf, reducef[, options])");
- print("\noptions");
- print("{[query : <query filter object>]");
- print(" [, sort : <sort the query. useful for optimization>]");
- print(" [, limit : <number of objects to return from collection>]");
- print(" [, out : <output-collection name>]");
- print(" [, keeptemp: <true|false>]");
- print(" [, finalize : <finalizefunction>]");
- print(" [, scope : <object where fields go into javascript global scope >]");
- print(" [, verbose : true]}\n");
- return;
- } else if (x == "connect") {
- print("\nNormally one specifies the server on the mongo shell command line. Run mongo --help to see those options.");
- print("Additional connections may be opened:\n");
- print(" var x = new Mongo('host[:port]');");
- print(" var mydb = x.getDB('mydb');");
- print(" or");
- print(" var mydb = connect('host[:port]/mydb');");
- print("\nNote: the REPL prompt only auto-reports getLastError() for the shell command line connection.\n");
- return;
- }
- else if (x == "keys") {
- print("Tab completion and command history is available at the command prompt.\n");
- print("Some emacs keystrokes are available too:");
- print(" Ctrl-A start of line");
- print(" Ctrl-E end of line");
- print(" Ctrl-K del to end of line");
- print("\nMulti-line commands");
- print("You can enter a multi line javascript expression. If parens, braces, etc. are not closed, you will see a new line ");
- print("beginning with '...' characters. Type the rest of your expression. Press Ctrl-C to abort the data entry if you");
- print("get stuck.\n");
- }
- else if (x == "misc") {
- print("\tb = new BinData(subtype,base64str) create a BSON BinData value");
- print("\tb.subtype() the BinData subtype (0..255)");
- print("\tb.length() length of the BinData data in bytes");
- print("\tb.hex() the data as a hex encoded string");
- print("\tb.base64() the data as a base 64 encoded string");
- print("\tb.toString()");
- print();
- print("\tb = HexData(subtype,hexstr) create a BSON BinData value from a hex string");
- print("\tb = UUID(hexstr) create a BSON BinData value of UUID subtype");
- print("\tb = MD5(hexstr) create a BSON BinData value of MD5 subtype");
- print();
- print("\to = new ObjectId() create a new ObjectId");
- print("\to.getTimestamp() return timestamp derived from first 32 bits of the OID");
- print("\to.isObjectId()");
- print("\to.toString()");
- print("\to.equals(otherid)");
- return;
- }
- else if (x == "admin") {
- print("\tls([path]) list files");
- print("\tpwd() returns current directory");
- print("\tlistFiles([path]) returns file list");
- print("\thostname() returns name of this host");
- print("\tcat(fname) returns contents of text file as a string");
- print("\tremoveFile(f) delete a file or directory");
- print("\tload(jsfilename) load and execute a .js file");
- print("\trun(program[, args...]) spawn a program and wait for its completion");
- print("\trunProgram(program[, args...]) same as run(), above");
- print("\tsleep(m) sleep m milliseconds");
- print("\tgetMemInfo() diagnostic");
- return;
- }
- else if (x == "test") {
- print("\tstartMongodEmpty(args) DELETES DATA DIR and then starts mongod");
- print("\t returns a connection to the new server");
- print("\tstartMongodTest(port,dir,options)");
- print("\t DELETES DATA DIR");
- print("\t automatically picks port #s starting at 27000 and increasing");
- print("\t or you can specify the port as the first arg");
- print("\t dir is /data/db/<port>/ if not specified as the 2nd arg");
- print("\t returns a connection to the new server");
- print("\tresetDbpath(dirpathstr) deletes everything under the dir specified including subdirs");
- print("\tstopMongoProgram(port[, signal])");
- return;
- }
- else if (x == "") {
- print("\t" + "db.help() help on db methods");
- print("\t" + "db.mycoll.help() help on collection methods");
- print("\t" + "rs.help() help on replica set methods");
- print("\t" + "help admin administrative help");
- print("\t" + "help connect connecting to a db help");
- print("\t" + "help keys key shortcuts");
- print("\t" + "help misc misc things to know");
- print("\t" + "help mr mapreduce");
- print();
- print("\t" + "show dbs show database names");
- print("\t" + "show collections show collections in current database");
- print("\t" + "show users show users in current database");
- print("\t" + "show profile show most recent system.profile entries with time >= 1ms");
- print("\t" + "show logs show the accessible logger names");
- print("\t" + "show log [name] prints out the last segment of log in memory, 'global' is default");
- print("\t" + "use <db_name> set current database");
- print("\t" + "db.foo.find() list objects in collection foo");
- print("\t" + "db.foo.find( { a : 1 } ) list objects in foo where a == 1");
- print("\t" + "it result of the last line evaluated; use to further iterate");
- print("\t" + "DBQuery.shellBatchSize = x set default number of items to display on shell");
- print("\t" + "exit quit the mongo shell");
- }
- else
- print("unknown help option");
-}
diff --git a/shell/utils_sh.js b/shell/utils_sh.js
deleted file mode 100644
index 297643fd270..00000000000
--- a/shell/utils_sh.js
+++ /dev/null
@@ -1,114 +0,0 @@
-sh = function() { return "try sh.help();" }
-
-
-sh._checkMongos = function() {
- var x = db.runCommand( "ismaster" );
- if ( x.msg != "isdbgrid" )
- throw "not connected to a mongos"
-}
-
-sh._checkFullName = function( fullName ) {
- assert( fullName , "neeed a full name" )
- assert( fullName.indexOf( "." ) > 0 , "name needs to be fully qualified <db>.<collection>'" )
-}
-
-sh._adminCommand = function( cmd , skipCheck ) {
- if ( ! skipCheck ) sh._checkMongos();
- var res = db.getSisterDB( "admin" ).runCommand( cmd );
-
- if ( res == null || ! res.ok ) {
- print( "command failed: " + tojson( res ) )
- }
-
- return res;
-}
-
-
-sh._dataFormat = function( bytes ){
- if( bytes < 1024 ) return Math.floor( bytes ) + "b"
- if( bytes < 1024 * 1024 ) return Math.floor( bytes / 1024 ) + "kb"
- if( bytes < 1024 * 1024 * 1024 ) return Math.floor( ( Math.floor( bytes / 1024 ) / 1024 ) * 100 ) / 100 + "Mb"
- return Math.floor( ( Math.floor( bytes / ( 1024 * 1024 ) ) / 1024 ) * 100 ) / 100 + "Gb"
-}
-
-sh._collRE = function( coll ){
- return RegExp( "^" + (coll + "").replace(/\./g, "\\.") + "-.*" )
-}
-
-sh._pchunk = function( chunk ){
- return "[" + tojson( chunk.min ) + " -> " + tojson( chunk.max ) + "]"
-}
-
-sh.help = function() {
- print( "\tsh.addShard( host ) server:port OR setname/server:port" )
- print( "\tsh.enableSharding(dbname) enables sharding on the database dbname" )
- print( "\tsh.shardCollection(fullName,key,unique) shards the collection" );
-
- print( "\tsh.splitFind(fullName,find) splits the chunk that find is in at the median" );
- print( "\tsh.splitAt(fullName,middle) splits the chunk that middle is in at middle" );
- print( "\tsh.moveChunk(fullName,find,to) move the chunk where 'find' is to 'to' (name of shard)");
-
- print( "\tsh.setBalancerState( <bool on or not> ) turns the balancer on or off true=on, false=off" );
- print( "\tsh.getBalancerState() return true if on, off if not" );
- print( "\tsh.isBalancerRunning() return true if the balancer is running on any mongos" );
-
- print( "\tsh.status() prints a general overview of the cluster" )
-}
-
-sh.status = function( verbose , configDB ) {
- // TODO: move the actual commadn here
- printShardingStatus( configDB , verbose );
-}
-
-sh.addShard = function( url ){
- sh._adminCommand( { addShard : url } , true )
-}
-
-sh.enableSharding = function( dbname ) {
- assert( dbname , "need a valid dbname" )
- sh._adminCommand( { enableSharding : dbname } )
-}
-
-sh.shardCollection = function( fullName , key , unique ) {
- sh._checkFullName( fullName )
- assert( key , "need a key" )
- assert( typeof( key ) == "object" , "key needs to be an object" )
-
- var cmd = { shardCollection : fullName , key : key }
- if ( unique )
- cmd.unique = true;
-
- sh._adminCommand( cmd )
-}
-
-
-sh.splitFind = function( fullName , find ) {
- sh._checkFullName( fullName )
- sh._adminCommand( { split : fullName , find : find } )
-}
-
-sh.splitAt = function( fullName , middle ) {
- sh._checkFullName( fullName )
- sh._adminCommand( { split : fullName , middle : middle } )
-}
-
-sh.moveChunk = function( fullName , find , to ) {
- sh._checkFullName( fullName );
- sh._adminCommand( { moveChunk : fullName , find : find , to : to } )
-}
-
-sh.setBalancerState = function( onOrNot ) {
- db.getSisterDB( "config" ).settings.update({ _id: "balancer" }, { $set : { stopped: onOrNot ? false : true } }, true );
-}
-
-sh.getBalancerState = function() {
- var x = db.getSisterDB( "config" ).settings.findOne({ _id: "balancer" } )
- if ( x == null )
- return true;
- return ! x.stopped;
-}
-
-sh.isBalancerRunning = function() {
- var x = db.getSisterDB( "config" ).locks.findOne( { _id : "balancer" } );
- return x.state > 0;
-}