00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #pragma once
00020
00021 #include <map>
00022 #include "../../client/dbclient.h"
00023 #include "../security_key.h"
00024
00025 namespace mongo {
00026
00043 class ScopedConn {
00044 public:
00046 ScopedConn(string hostport);
00047 ~ScopedConn();
00048
00049
00050
00051
00052
00053
00054 bool runCommand(const string &dbname, const BSONObj& cmd, BSONObj &info, int options=0) {
00055 return conn()->runCommand(dbname, cmd, info, options);
00056 }
00057 unsigned long long count(const string &ns) {
00058 return conn()->count(ns);
00059 }
00060 BSONObj findOne(const string &ns, const Query& q, const BSONObj *fieldsToReturn = 0, int queryOptions = 0) {
00061 return conn()->findOne(ns, q, fieldsToReturn, queryOptions);
00062 }
00063 void setTimeout(double to) {
00064 conn()->setSoTimeout(to);
00065 }
00066
00067 private:
00068 auto_ptr<scoped_lock> connLock;
00069 static mongo::mutex mapMutex;
00070 struct X {
00071 mongo::mutex z;
00072 DBClientConnection cc;
00073 X() : z("X"), cc( true, 0, 10.0) {
00074 cc._logLevel = 2;
00075 }
00076 } *x;
00077 typedef map<string,ScopedConn::X*> M;
00078 static M& _map;
00079 DBClientConnection* conn() { return &x->cc; }
00080 };
00081
00082 inline ScopedConn::ScopedConn(string hostport) {
00083 bool first = false;
00084 {
00085 scoped_lock lk(mapMutex);
00086 x = _map[hostport];
00087 if( x == 0 ) {
00088 x = _map[hostport] = new X();
00089 first = true;
00090 connLock.reset( new scoped_lock(x->z) );
00091 }
00092 }
00093 if( !first ) {
00094 connLock.reset( new scoped_lock(x->z) );
00095 return;
00096 }
00097
00098
00099 string err;
00100 if (!x->cc.connect(hostport, err)) {
00101 log() << "couldn't connect to " << hostport << ": " << err << rsLog;
00102 return;
00103 }
00104
00105 if (!noauth && !x->cc.auth("local", internalSecurity.user, internalSecurity.pwd, err, false)) {
00106 log() << "could not authenticate against " << conn()->toString() << ", " << err << rsLog;
00107 return;
00108 }
00109 }
00110
00111 inline ScopedConn::~ScopedConn() {
00112
00113 }
00114
00115
00116
00117
00118
00119 }