summaryrefslogtreecommitdiff
path: root/src/mongo/scripting/bench.cpp
blob: 32f811ecd9acb4376fa7c7ee6330b7ad7265f4b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
/** @file bench.cpp */

/*
 *    Copyright (C) 2010 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "pch.h"
#include "engine.h"
#include "../util/md5.hpp"
#include "../util/version.h"
#include "../client/connpool.h"
#include "mongo/client/dbclientcursor.h"
#include <pcrecpp.h>

// ---------------------------------
// ---- benchmarking system --------
// ---------------------------------

// TODO:  Maybe extract as library to avoid code duplication?
namespace {
    inline pcrecpp::RE_Options flags2options(const char* flags) {
        pcrecpp::RE_Options options;
        options.set_utf8(true);
        while ( flags && *flags ) {
            if ( *flags == 'i' )
                options.set_caseless(true);
            else if ( *flags == 'm' )
                options.set_multiline(true);
            else if ( *flags == 'x' )
                options.set_extended(true);
            flags++;
        }
        return options;
    }
}

namespace mongo {

    struct BenchRunConfig {
        BenchRunConfig() : _mutex( "BenchRunConfig" ) {
            host = "localhost";
            db = "test";
            username = "";
            password = "";

            parallel = 1;
            seconds = 1;
            handleErrors = false;
            hideErrors = false;
            hideResults = true;

            active = true;
            threadsReady = 0;
            error = false;
            errCount = 0;
            throwGLE = false;
            breakOnTrap = true;
            loopCommands = true;
        }

        string host;
        string db;
        string username;
        string password;

        unsigned parallel;
        double seconds;

        bool hideResults;
        bool handleErrors;
        bool hideErrors;

        shared_ptr< pcrecpp::RE > trapPattern;
        shared_ptr< pcrecpp::RE > noTrapPattern;
        shared_ptr< pcrecpp::RE > watchPattern;
        shared_ptr< pcrecpp::RE > noWatchPattern;

        BSONObj ops;

        volatile bool active; // true at starts, gets set to false when should stop
        AtomicUInt threadsReady;

        bool error;
        bool throwGLE;
        bool breakOnTrap;
        bool loopCommands;

        AtomicUInt threadsActive;

        mongo::mutex _mutex;
        long long errCount;
        BSONArrayBuilder trapped;
    };

    static bool _hasSpecial( const BSONObj& obj ) {
        BSONObjIterator i( obj );
        while ( i.more() ) {
            BSONElement e = i.next();
            if ( e.fieldName()[0] == '#' )
                return true;
            
            if ( ! e.isABSONObj() )
                continue;
            
            if ( _hasSpecial( e.Obj() ) )
                return true;
        }
        return false;
    }
    
    static void _fixField( BSONObjBuilder& b , const BSONElement& e ) {
        verify( e.type() == Object );
        
        BSONObj sub = e.Obj();
        verify( sub.nFields() == 1 );
        
        BSONElement f = sub.firstElement();
        if ( str::equals( "#RAND_INT" , f.fieldName() ) ) {
            BSONObjIterator i( f.Obj() );
            int min = i.next().numberInt();
            int max = i.next().numberInt();
            
            int x = min + ( rand() % ( max - min ) );
            
            if ( i.more() )
                x *= i.next().numberInt();

            b.append( e.fieldName() , x );
        }
        else {
            uasserted( 14811 , str::stream() << "invalid bench dynamic piece: " << f.fieldName() );
        }
        
    } 
    
    static void fixQuery( BSONObjBuilder& b  , const BSONObj& obj ) {
        BSONObjIterator i( obj );
        while ( i.more() ) {
            BSONElement e = i.next();
            
            if ( ! e.isABSONObj() ) {
                b.append( e );
                continue;
            }

            BSONObj sub = e.Obj();
            if ( sub.firstElement().fieldName()[0] == '#' ) {
                _fixField( b , e );
            }
            else {
                BSONObjBuilder xx( e.type() == Object ? b.subobjStart( e.fieldName() ) : b.subarrayStart( e.fieldName() ) );
                fixQuery( xx , sub );
                xx.done();
            }

        }
    }

    static BSONObj fixQuery( const BSONObj& obj ) {

        if ( ! _hasSpecial( obj ) ) 
            return obj;

        BSONObjBuilder b( obj.objsize() + 128 );
        fixQuery( b , obj );
        return b.obj();
    }


    static void _benchThread( BenchRunConfig * config, DBClientBase* conn ){
        verify( conn );
        long long count = 0;
        while ( config->active || ! config->loopCommands ) {
            BSONObjIterator i( config->ops );
            while ( i.more() ) {

                // Break out if we should stop and we're not running all commands then stopping
                if( ! config->active && config->loopCommands ) break;

                BSONElement e = i.next();

                string ns = e["ns"].String();
                string op = e["op"].String();

                int delay = e["delay"].eoo() ? 0 : e["delay"].Int();

                BSONObj context = e["context"].eoo() ? BSONObj() : e["context"].Obj();

                auto_ptr<Scope> scope;
                ScriptingFunction scopeFunc = 0;
                BSONObj scopeObj;

                if (config->username != "") {
                    string errmsg;
                    if (!conn->auth(config->db, config->username, config->password, errmsg)) {
                        uasserted(15931, "Authenticating to connection for _benchThread failed: " + errmsg);
                    }
                }

                bool check = ! e["check"].eoo();
                if( check ){
                    if ( e["check"].type() == CodeWScope || e["check"].type() == Code || e["check"].type() == String ) {
                        scope = globalScriptEngine->getPooledScope( ns );
                        verify( scope.get() );

                        if ( e.type() == CodeWScope ) {
                            scopeFunc = scope->createFunction( e["check"].codeWScopeCode() );
                            scopeObj = BSONObj( e.codeWScopeScopeData() );
                        }
                        else {
                            scopeFunc = scope->createFunction( e["check"].valuestr() );
                        }

                        scope->init( &scopeObj );
                        verify( scopeFunc );
                    }
                    else {
                        warning() << "Invalid check type detected in benchRun op : " << e << endl;
                        check = false;
                    }
                }

                try {
                    if ( op == "findOne" ) {

                        BSONObj result = conn->findOne( ns , fixQuery( e["query"].Obj() ) );

                        if( check ){
                            int err = scope->invoke( scopeFunc , 0 , &result,  1000 * 60 , false );
                            if( err ){
                                log() << "Error checking in benchRun thread [findOne]" << causedBy( scope->getError() ) << endl;

                                scoped_lock lock( config->_mutex );
                                config->errCount++;

                                return;
                            }
                        }

                        if( ! config->hideResults || e["showResult"].trueValue() ) log() << "Result from benchRun thread [findOne] : " << result << endl;

                    }
                    else if ( op == "command" ) {

                        BSONObj result;
                        // TODO
                        /* bool ok = */ conn->runCommand( ns , fixQuery( e["command"].Obj() ), result, e["options"].numberInt() );

                        if( check ){
                            int err = scope->invoke( scopeFunc , 0 , &result,  1000 * 60 , false );
                            if( err ){
                                log() << "Error checking in benchRun thread [command]" << causedBy( scope->getError() ) << endl;

                                scoped_lock lock( config->_mutex );
                                config->errCount++;

                                return;
                            }
                        }

                        if( ! config->hideResults || e["showResult"].trueValue() ) log() << "Result from benchRun thread [command] : " << result << endl;

                    }
                    else if( op == "find" || op == "query" ) {

                        int limit = e["limit"].eoo() ? 0 : e["limit"].numberInt();
                        int skip = e["skip"].eoo() ? 0 : e["skip"].Int();
                        int options = e["options"].eoo() ? 0 : e["options"].Int();
                        int batchSize = e["batchSize"].eoo() ? 0 : e["batchSize"].Int();
                        BSONObj filter = e["filter"].eoo() ? BSONObj() : e["filter"].Obj();
                        int expected = e["expected"].eoo() ? -1 : e["expected"].Int();

                        auto_ptr<DBClientCursor> cursor = conn->query( ns, fixQuery( e["query"].Obj() ), limit, skip, &filter, options, batchSize );

                        int count = cursor->itcount();

                        if ( expected >= 0 &&  count != expected ) {
                            cout << "bench query on: " << ns << " expected: " << expected << " got: " << cout << endl;
                            verify(false);
                        }

                        if( check ){
                            BSONObj thisValue = BSON( "count" << count << "context" << context );
                            int err = scope->invoke( scopeFunc , 0 , &thisValue, 1000 * 60 , false );
                            if( err ){
                                log() << "Error checking in benchRun thread [find]" << causedBy( scope->getError() ) << endl;

                                scoped_lock lock( config->_mutex );
                                config->errCount++;

                                return;
                            }
                        }

                        if( ! config->hideResults || e["showResult"].trueValue() ) log() << "Result from benchRun thread [query] : " << count << endl;

                    }
                    else if( op == "update" ) {

                        bool multi = e["multi"].trueValue();
                        bool upsert = e["upsert"].trueValue();
                        BSONObj query = e["query"].eoo() ? BSONObj() : e["query"].Obj();
                        BSONObj update = e["update"].Obj();

                        conn->update( ns, fixQuery( query ), update, upsert , multi );

                        bool safe = e["safe"].trueValue();
                        if( safe ){
                            BSONObj result = conn->getLastErrorDetailed();

                            if( check ){
                                int err = scope->invoke( scopeFunc , 0 , &result, 1000 * 60 , false );
                                if( err ){
                                    log() << "Error checking in benchRun thread [update]" << causedBy( scope->getError() ) << endl;

                                    scoped_lock lock( config->_mutex );
                                    config->errCount++;

                                    return;
                                }
                            }

                            if( ! config->hideResults || e["showResult"].trueValue() ) log() << "Result from benchRun thread [safe update] : " << result << endl;

                            if( ! result["err"].eoo() && result["err"].type() == String && ( config->throwGLE || e["throwGLE"].trueValue() ) )
                                throw DBException( (string)"From benchRun GLE" + causedBy( result["err"].String() ),
                                                   result["code"].eoo() ? 0 : result["code"].Int() );
                        }
                    }
                    else if( op == "insert" ) {

                        conn->insert( ns, fixQuery( e["doc"].Obj() ) );

                        bool safe = e["safe"].trueValue();
                        if( safe ){
                            BSONObj result = conn->getLastErrorDetailed();

                            if( check ){
                                int err = scope->invoke( scopeFunc , 0 , &result, 1000 * 60 , false );
                                if( err ){
                                    log() << "Error checking in benchRun thread [insert]" << causedBy( scope->getError() ) << endl;

                                    scoped_lock lock( config->_mutex );
                                    config->errCount++;

                                    return;
                                }
                            }

                            if( ! config->hideResults || e["showResult"].trueValue() ) log() << "Result from benchRun thread [safe insert] : " << result << endl;

                            if( ! result["err"].eoo() && result["err"].type() == String && ( config->throwGLE || e["throwGLE"].trueValue() ) )
                                throw DBException( (string)"From benchRun GLE" + causedBy( result["err"].String() ),
                                                   result["code"].eoo() ? 0 : result["code"].Int() );
                        }
                    }
                    else if( op == "delete" || op == "remove" ) {

                        bool multi = e["multi"].eoo() ? true : e["multi"].trueValue();
                        BSONObj query = e["query"].eoo() ? BSONObj() : e["query"].Obj();

                        conn->remove( ns, fixQuery( query ), ! multi );

                        bool safe = e["safe"].trueValue();
                        if( safe ){
                            BSONObj result = conn->getLastErrorDetailed();

                            if( check ){
                                int err = scope->invoke( scopeFunc , 0 , &result, 1000 * 60 , false );
                                if( err ){
                                    log() << "Error checking in benchRun thread [delete]" << causedBy( scope->getError() ) << endl;

                                    scoped_lock lock( config->_mutex );
                                    config->errCount++;

                                    return;
                                }
                            }

                            if( ! config->hideResults || e["showResult"].trueValue() ) log() << "Result from benchRun thread [safe remove] : " << result << endl;

                            if( ! result["err"].eoo() && result["err"].type() == String && ( config->throwGLE || e["throwGLE"].trueValue() ) )
                                throw DBException( (string)"From benchRun GLE " + causedBy( result["err"].String() ),
                                                   result["code"].eoo() ? 0 : result["code"].Int() );
                        }
                    }
                    else if ( op == "createIndex" ) {
                        conn->ensureIndex( ns , e["key"].Obj() , false , "" , false );
                    }
                    else if ( op == "dropIndex" ) {
                        conn->dropIndex( ns , e["key"].Obj()  );
                    }
                    else {
                        log() << "don't understand op: " << op << endl;
                        config->error = true;
                        return;
                    }
                }
                catch( DBException& ex ){
                    if( ! config->hideErrors || e["showError"].trueValue() ){

                        bool yesWatch = ( config->watchPattern && config->watchPattern->FullMatch( ex.what() ) );
                        bool noWatch = ( config->noWatchPattern && config->noWatchPattern->FullMatch( ex.what() ) );

                        if( ( ! config->watchPattern && config->noWatchPattern && ! noWatch ) || // If we're just ignoring things
                            ( ! config->noWatchPattern && config->watchPattern && yesWatch ) || // If we're just watching things
                            ( config->watchPattern && config->noWatchPattern && yesWatch && ! noWatch ) )
                            log() << "Error in benchRun thread for op " << e << causedBy( ex ) << endl;
                    }

                    bool yesTrap = ( config->trapPattern && config->trapPattern->FullMatch( ex.what() ) );
                    bool noTrap = ( config->noTrapPattern && config->noTrapPattern->FullMatch( ex.what() ) );

                    if( ( ! config->trapPattern && config->noTrapPattern && ! noTrap ) ||
                        ( ! config->noTrapPattern && config->trapPattern && yesTrap ) ||
                        ( config->trapPattern && config->noTrapPattern && yesTrap && ! noTrap ) ){
                        {
                            scoped_lock lock( config->_mutex );
                            config->trapped.append( BSON( "error" << ex.what() << "op" << e << "count" << count ) );
                        }
                        if( config->breakOnTrap ) return;
                    }
                    if( ! config->handleErrors && ! e["handleError"].trueValue() ) return;

                    {
                        scoped_lock lock( config->_mutex );
                        config->errCount++;
                    }
                }
                catch( ... ){
                    if( ! config->hideErrors || e["showError"].trueValue() ) log() << "Error in benchRun thread caused by unknown error for op " << e << endl;
                    if( ! config->handleErrors && ! e["handleError"].trueValue() ) return;

                    {
                        scoped_lock lock( config->_mutex );
                        config->errCount++;
                    }
                }
                
                if ( ++count % 100 == 0 ) {
                    conn->getLastError();
                }

                sleepmillis( delay );
            }

            if( ! config->loopCommands ) break;
        }
    }

    static void benchThread( BenchRunConfig * config ) {

        ScopedDbConnection conn( config->host );
        config->threadsReady++;
        config->threadsActive++;

        try {
            if (config->username != "") {
                string errmsg;
                if (!conn.get()->auth(config->db, config->username, config->password, errmsg)) {
                    uasserted(15932, "Authenticating to connection for benchThread failed: " + errmsg);
                }
            }

            _benchThread( config, conn.get() );
        }
        catch( DBException& e ){
            error() << "DBException not handled in benchRun thread" << causedBy( e ) << endl;
        }
        catch( std::exception& e ){
            error() << "Exception not handled in benchRun thread" << causedBy( e ) << endl;
        }
        catch( ... ){
            error() << "Exception not handled in benchRun thread." << endl;
        }
        conn->getLastError();
        config->threadsActive--;
        conn.done();

    }


    class BenchRunner {
    public:

        BenchRunner( ) {
        }

        ~BenchRunner() {
        }

        void init( BSONObj& args ){

            oid.init();
            activeRuns[ oid ] = this;

            if ( args["host"].type() == String )
                config.host = args["host"].String();
            if ( args["db"].type() == String )
                config.db = args["db"].String();
            if ( args["username"].type() == String )
                config.username = args["username"].String();
            if ( args["password"].type() == String )
                config.db = args["password"].String();

            if ( args["parallel"].isNumber() )
                config.parallel = args["parallel"].numberInt();
            if ( args["seconds"].isNumber() )
                config.seconds = args["seconds"].numberInt();
            if ( ! args["hideResults"].eoo() )
                config.hideResults = args["hideResults"].trueValue();
            if ( ! args["handleErrors"].eoo() )
                config.handleErrors = args["handleErrors"].trueValue();
            if ( ! args["hideErrors"].eoo() )
                config.hideErrors = args["hideErrors"].trueValue();
            if ( ! args["throwGLE"].eoo() )
                config.throwGLE = args["throwGLE"].trueValue();
            if ( ! args["breakOnTrap"].eoo() )
                config.breakOnTrap = args["breakOnTrap"].trueValue();
            if ( ! args["loopCommands"].eoo() )
                config.loopCommands = args["loopCommands"].trueValue();


            if ( ! args["trapPattern"].eoo() ){
                 const char* regex = args["trapPattern"].regex();
                 const char* flags = args["trapPattern"].regexFlags();
                 config.trapPattern = shared_ptr< pcrecpp::RE >( new pcrecpp::RE( regex, flags2options( flags ) ) );
            }

            if ( ! args["noTrapPattern"].eoo() ){
                 const char* regex = args["noTrapPattern"].regex();
                 const char* flags = args["noTrapPattern"].regexFlags();
                 config.noTrapPattern = shared_ptr< pcrecpp::RE >( new pcrecpp::RE( regex, flags2options( flags ) ) );
            }

            if ( ! args["watchPattern"].eoo() ){
                 const char* regex = args["watchPattern"].regex();
                 const char* flags = args["watchPattern"].regexFlags();
                 config.watchPattern = shared_ptr< pcrecpp::RE >( new pcrecpp::RE( regex, flags2options( flags ) ) );
            }

            if ( ! args["noWatchPattern"].eoo() ){
                 const char* regex = args["noWatchPattern"].regex();
                 const char* flags = args["noWatchPattern"].regexFlags();
                 config.noWatchPattern = shared_ptr< pcrecpp::RE >( new pcrecpp::RE( regex, flags2options( flags ) ) );
            }

            config.ops = args["ops"].Obj().getOwned();
            conn = shared_ptr< ScopedDbConnection >( new ScopedDbConnection( config.host ) );

            // Get initial stats
            conn->get()->simpleCommand( "admin" , &before , "serverStatus" );

            // Start threads
            for ( unsigned i = 0; i < config.parallel; i++ )
                threads.push_back( shared_ptr< boost::thread >( new boost::thread( boost::bind( benchThread , &config ) ) ) );

            // Give them time to init
            while ( config.threadsReady < config.parallel ) sleepmillis( 1 );

        }

        void done(){

            log() << "Ending! (waiting for " << threads.size() << " threads)" << endl;

            {
                scoped_lock lock( config._mutex );
                config.active = false;
            }

            for ( unsigned i = 0; i < threads.size(); i++ ) threads[i]->join();

            // Get final stats
            conn->get()->simpleCommand( "admin" , &after , "serverStatus" );
            after.getOwned();

            conn.get()->done();

            activeRuns.erase( oid );

        }

        BSONObj status(){
            scoped_lock lock( config._mutex );
            return BSON( "errCount" << config.errCount <<
                         "trappedCount" << config.trapped.arrSize() <<
                         "threadsActive" << config.threadsActive.get() );
        }

        static BenchRunner* get( BSONObj args ){
            BenchRunner* runner = new BenchRunner();
            runner->init( args );
            return runner;
        }

        static BenchRunner* get( OID oid ){
            return activeRuns[ oid ];
        }

        static BSONObj finish( BenchRunner* runner ){

            runner->done();

            // vector<BSONOBj> errors = runner->config.errors;
            bool error = runner->config.error;

            if ( error )
                return BSON( "err" << 1 );

            // compute actual ops/sec
            BSONObj before = runner->before["opcounters"].Obj();
            BSONObj after = runner->after["opcounters"].Obj();

            BSONObjBuilder buf;
            buf.append( "note" , "values per second" );
            buf.append( "errCount", (long long) runner->config.errCount );
            buf.append( "trapped", runner->config.trapped.arr() );
            {
                BSONObjIterator i( after );
                while ( i.more() ) {
                    BSONElement e = i.next();
                    double x = e.number();
                    x = x - before[e.fieldName()].number();
                    buf.append( e.fieldName() , x / runner->config.seconds );
                }
            }

            BSONObj zoo = buf.obj();

            delete runner;
            return zoo;
        }

        static map< OID, BenchRunner* > activeRuns;

        OID oid;
        BenchRunConfig config;
        vector< shared_ptr< boost::thread > > threads;

        shared_ptr< ScopedDbConnection > conn;
        BSONObj before;
        BSONObj after;

    };

    map< OID, BenchRunner* > BenchRunner::activeRuns;


    /**
     * benchRun( { ops : [] , host : XXX , db : XXXX , parallel : 5 , seconds : 5 }
     */
    BSONObj benchRun( const BSONObj& argsFake, void* data ) {
        verify( argsFake.firstElement().isABSONObj() );
        BSONObj args = argsFake.firstElement().Obj();

        // setup

        BenchRunConfig config;

        if ( args["host"].type() == String )
            config.host = args["host"].String();
        if ( args["db"].type() == String )
            config.db = args["db"].String();
        if ( args["username"].type() == String )
            config.username = args["username"].String();
        if ( args["password"].type() == String )
            config.password = args["password"].String();

        if ( args["parallel"].isNumber() )
            config.parallel = args["parallel"].numberInt();
        if ( args["seconds"].isNumber() )
            config.seconds = args["seconds"].number();


        config.ops = args["ops"].Obj();

        // execute

        ScopedDbConnection conn( config.host );

        if (config.username != "") {
            string errmsg;
            if (!conn.get()->auth(config.db, config.username, config.password, errmsg)) {
                uasserted(15930, "Authenticating to connection for bench run failed: " + errmsg);
            }
        }


        //    start threads
        vector<boost::thread*> all;
        for ( unsigned i=0; i<config.parallel; i++ )
            all.push_back( new boost::thread( boost::bind( benchThread , &config ) ) );

        //    give them time to init
        while ( config.threadsReady < config.parallel )
            sleepmillis( 1 );

        BSONObj before;
        conn->simpleCommand( "admin" , &before , "serverStatus" );

        sleepmillis( (int)(1000.0 * config.seconds) );

        BSONObj after;
        conn->simpleCommand( "admin" , &after , "serverStatus" );

        conn.done();

        config.active = false;

        for ( unsigned i=0; i<all.size(); i++ )
            all[i]->join();

        if ( config.error )
            return BSON( "err" << 1 );

        // compute actual ops/sec

        before = before["opcounters"].Obj().copy();
        after = after["opcounters"].Obj().copy();
        
        bool totals = args["totals"].trueValue();

        BSONObjBuilder buf;
        if ( ! totals )
            buf.append( "note" , "values per second" );

        {
            BSONObjIterator i( after );
            while ( i.more() ) {
                BSONElement e = i.next();
                double x = e.number();
                x = x - before[e.fieldName()].number();
                if ( ! totals )
                    x = x / config.seconds;
                buf.append( e.fieldName() , x );
            }
        }
        BSONObj zoo = buf.obj();
        return BSON( "" << zoo );
    }

    /**
     * benchRun( { ops : [] , host : XXX , db : XXXX , parallel : 5 , seconds : 5 }
     */
    BSONObj benchRunSync( const BSONObj& argsFake, void* data ) {

        verify( argsFake.firstElement().isABSONObj() );
        BSONObj args = argsFake.firstElement().Obj();

        // Get new BenchRunner object
        BenchRunner* runner = BenchRunner::get( args );

        sleepsecs( static_cast<int>( runner->config.seconds ) );

        return BenchRunner::finish( runner );

    }

    /**
     * benchRun( { ops : [] , host : XXX , db : XXXX , parallel : 5 , seconds : 5 }
     */
    BSONObj benchStart( const BSONObj& argsFake, void* data ) {

        verify( argsFake.firstElement().isABSONObj() );
        BSONObj args = argsFake.firstElement().Obj();

        // Get new BenchRunner object
        BenchRunner* runner = BenchRunner::get( args );

        log() << "Starting benchRun test " << runner->oid << endl;

        return BSON( "" << runner->oid.toString() );
    }

    /**
     * benchRun( { ops : [] , host : XXX , db : XXXX , parallel : 5 , seconds : 5 }
     */
    BSONObj benchStatus( const BSONObj& argsFake, void* data ) {

        OID oid = OID( argsFake.firstElement().String() );

        log() << "Getting status for benchRun test " << oid << endl;

        // Get new BenchRunner object
        BenchRunner* runner = BenchRunner::get( oid );

        BSONObj statusObj = runner->status();

        return BSON( "" << statusObj );
    }

    /**
     * benchRun( { ops : [] , host : XXX , db : XXXX , parallel : 5 , seconds : 5 }
     */
    BSONObj benchFinish( const BSONObj& argsFake, void* data ) {

        OID oid = OID( argsFake.firstElement().String() );

        log() << "Finishing benchRun test " << oid << endl;

        // Get new BenchRunner object
        BenchRunner* runner = BenchRunner::get( oid );

        BSONObj finalObj = BenchRunner::finish( runner );

        return BSON( "" << finalObj );
    }

    void installBenchmarkSystem( Scope& scope ) {
        scope.injectNative( "benchRun" , benchRun );
        scope.injectNative( "benchRunSync" , benchRunSync );
        scope.injectNative( "benchStart" , benchStart );
        scope.injectNative( "benchStatus" , benchStatus );
        scope.injectNative( "benchFinish" , benchFinish );
    }

}