MongoDB C++ Driver legacy-1.0.0
Loading...
Searching...
No Matches
dbclient_rs.h
Go to the documentation of this file.
1
3/* Copyright 2009 10gen Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#pragma once
19
20#include <boost/shared_ptr.hpp>
21#include <utility>
22
24#include "mongo/client/export_macros.h"
25#include "mongo/util/net/hostandport.h"
26
27namespace mongo {
28
29 class ReplicaSetMonitor;
30 class TagSet;
31 struct ReadPreferenceSetting;
32 typedef boost::shared_ptr<ReplicaSetMonitor> ReplicaSetMonitorPtr;
33
42 class MONGO_CLIENT_API DBClientReplicaSet : public DBClientBase {
43 public:
44 using DBClientBase::query;
45 using DBClientBase::update;
46 using DBClientBase::remove;
47
49 DBClientReplicaSet( const std::string& name , const std::vector<HostAndPort>& servers, double so_timeout=0 );
50 virtual ~DBClientReplicaSet();
51
57 bool connect();
58
66 virtual void logout(const std::string& dbname, BSONObj& info);
67
68 // ----------- simple functions --------------
69
71 virtual std::auto_ptr<DBClientCursor> query(const std::string &ns, Query query, int nToReturn = 0, int nToSkip = 0,
72 const BSONObj *fieldsToReturn = 0, int queryOptions = 0 , int batchSize = 0 );
73
75 virtual BSONObj findOne(const std::string &ns, const Query& query, const BSONObj *fieldsToReturn = 0, int queryOptions = 0);
76
77 virtual void insert( const std::string &ns , BSONObj obj , int flags=0, const WriteConcern* wc=NULL );
78
79 virtual void insert( const std::string &ns, const std::vector< BSONObj >& v , int flags=0, const WriteConcern* wc=NULL );
80
81 virtual void remove( const std::string &ns , Query obj , int flags, const WriteConcern* wc=NULL );
82
83 virtual void update( const std::string &ns , Query query , BSONObj obj , int flags, const WriteConcern* wc=NULL );
84
85 virtual void killCursor( long long cursorID );
86
87 // ---- access raw connections ----
88
96
105
106 // ---- callback pieces -------
107
108 virtual void say( Message &toSend, bool isRetry = false , std::string* actualServer = 0);
109 virtual bool recv( Message &toRecv );
110 virtual void checkResponse( const char* data, int nReturned, bool* retry = NULL, std::string* targetHost = NULL );
111
112 /* this is the callback from our underlying connections to notify us that we got a "not master" error.
113 */
114 void isntMaster();
115
116 /* this is used to indicate we got a "not master or secondary" error from a secondary.
117 */
118 void isntSecondary();
119
120 // ----- status ------
121
122 virtual bool isFailed() const { return ! _master || _master->isFailed(); }
124
125 // ----- informational ----
126
127 double getSoTimeout() const { return _so_timeout; }
128
129 std::string toString() const { return getServerAddress(); }
130
131 std::string getServerAddress() const;
132
133 virtual ConnectionString::ConnectionType type() const { return ConnectionString::SET; }
134 virtual bool lazySupported() const { return true; }
135
136 // ---- low level ------
137
138 virtual bool call( Message &toSend, Message &response, bool assertOk=true , std::string * actualServer = 0 );
139 virtual bool callRead( Message& toSend , Message& response ) { return checkMaster()->callRead( toSend , response ); }
140
151 static bool MONGO_CLIENT_FUNC isSecondaryQuery( const std::string& ns,
152 const BSONObj& queryObj,
153 int queryOptions );
154
155 virtual void setRunCommandHook(DBClientWithCommands::RunCommandHookFunc func);
156 virtual void setPostRunCommandHook(DBClientWithCommands::PostRunCommandHookFunc func);
157
162 virtual void reset();
163
168 static void setAuthPooledSecondaryConn(bool setting);
169
170 protected:
173 virtual void _auth(const BSONObj& params);
174
175 virtual void sayPiggyBack( Message &toSend ) { checkMaster()->say( toSend ); }
176
177 private:
185 std::auto_ptr<DBClientCursor> checkSlaveQueryResult( std::auto_ptr<DBClientCursor> result );
186
187 DBClientConnection * checkMaster();
188
201 DBClientConnection* selectNodeUsingTags(boost::shared_ptr<ReadPreferenceSetting> readPref);
202
207 bool checkLastHost(const ReadPreferenceSetting* readPref);
208
212 void invalidateLastSlaveOkCache();
213
214 void _auth( DBClientConnection * conn );
215
220 void logoutAll(DBClientConnection* conn);
221
225 void resetMaster();
226
230 void resetSlaveOkConn();
231
236 static const size_t MAX_RETRY;
237
238 // TODO: remove this when processes other than mongos uses the driver version.
239 static bool _authPooledSecondaryConn;
240
241 // Throws a DBException if the monitor doesn't exist and there isn't a cached seed to use.
242 ReplicaSetMonitorPtr _getMonitor() const;
243
244 std::string _setName;
245
246 HostAndPort _masterHost;
247 boost::scoped_ptr<DBClientConnection> _master;
248
249 // Last used host in a slaveOk query (can be a primary).
250 HostAndPort _lastSlaveOkHost;
251 // Last used connection in a slaveOk query (can be a primary).
252 // Connection can either be owned here or returned to the connection pool. Note that
253 // if connection is primary, it is owned by _master so it is incorrect to return
254 // it to the pool.
255 std::auto_ptr<DBClientConnection> _lastSlaveOkConn;
256 boost::shared_ptr<ReadPreferenceSetting> _lastReadPref;
257
258 double _so_timeout;
259
260 // we need to store so that when we connect to a new node on failure
261 // we can re-auth
262 // this could be a security issue, as the password is stored in memory
263 // not sure if/how we should handle
264 std::map<std::string, BSONObj> _auths; // dbName -> auth parameters
265
266 protected:
267
271 class LazyState {
272 public:
273 LazyState() :
274 _lastClient( NULL ), _lastOp( -1 ), _secondaryQueryOk( false ), _retries( 0 ) {}
275 DBClientConnection* _lastClient;
276 int _lastOp;
277 bool _secondaryQueryOk;
278 int _retries;
279
280 } _lazyState;
281
282 };
283
287 class MONGO_CLIENT_API TagSet {
288 public:
295
303 explicit TagSet(const BSONArray& tags) : _tags(tags) {}
304
308 const BSONArray& getTagBSON() const { return _tags; }
309
310 bool operator==(const TagSet& other) const { return _tags == other._tags; }
311
312 private:
313 BSONArray _tags;
314 };
315
316 struct MONGO_CLIENT_API ReadPreferenceSetting {
324 ReadPreferenceSetting(ReadPreference pref, const TagSet& tag):
325 pref(pref), tags(tag) {
326 }
327
328 inline bool equals(const ReadPreferenceSetting& other) const {
329 return pref == other.pref && tags == other.tags;
330 }
331
332 BSONObj toBSON() const;
333
334 const ReadPreference pref;
335 TagSet tags;
336 };
337}
C++ representation of a "BSON" object – that is, an extended JSON-style object in a binary representa...
Definition bsonobj.h:78
abstract class that implements the core db operations
Definition dbclientinterface.h:1329
A basic connection to the database.
Definition dbclientinterface.h:1550
for storing (non-threadsafe) information between lazy calls
Definition dbclient_rs.h:271
Use this class to connect to a replica set of servers.
Definition dbclient_rs.h:42
bool connect()
Returns false if no member of the set were reachable.
static bool MONGO_CLIENT_FUNC isSecondaryQuery(const std::string &ns, const BSONObj &queryObj, int queryOptions)
Returns whether a query or command can be sent to secondaries based on the query object and options.
DBClientConnection & slaveConn()
WARNING: this method is very dangerous - this object can decide to free the returned master connectio...
static void setAuthPooledSecondaryConn(bool setting)
@bool setting if true, DBClientReplicaSet connections will make sure that secondary connections are a...
DBClientReplicaSet(const std::string &name, const std::vector< HostAndPort > &servers, double so_timeout=0)
Call connect() after constructing.
virtual void logout(const std::string &dbname, BSONObj &info)
Logs out the connection for the given database.
DBClientConnection & masterConn()
WARNING: this method is very dangerous - this object can decide to free the returned master connectio...
virtual void insert(const std::string &ns, BSONObj obj, int flags=0, const WriteConcern *wc=NULL)
insert an object into the database
bool isStillConnected()
if not checked recently, checks whether the underlying socket/sockets are still valid
virtual void _auth(const BSONObj &params)
Authorize.
virtual bool call(Message &toSend, Message &response, bool assertOk=true, std::string *actualServer=0)
actualServer is set to the actual server where they call went if there was a choice (SlaveOk)
virtual void insert(const std::string &ns, const std::vector< BSONObj > &v, int flags=0, const WriteConcern *wc=NULL)
insert a vector of objects into the database
virtual std::auto_ptr< DBClientCursor > query(const std::string &ns, Query query, int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
throws userassertion "no master found"
virtual BSONObj findOne(const std::string &ns, const Query &query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
throws userassertion "no master found"
virtual void reset()
Performs a "soft reset" by clearing all states relating to secondary nodes and returning secondary co...
stdx::function< void(const BSONObj &, const std::string &)> PostRunCommandHookFunc
Similar to above, but for running a function on a command response after a command has been run.
Definition dbclientinterface.h:1230
stdx::function< void(BSONObjBuilder *)> RunCommandHookFunc
A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns ...
Definition dbclientinterface.h:1220
Definition message.h:298
Represents a Mongo query expression.
Definition dbclientinterface.h:387
A simple object for representing the list of tags requested by a $readPreference.
Definition dbclient_rs.h:287
const BSONArray & getTagBSON() const
Returns the BSONArray listing all tags that should be accepted.
Definition dbclient_rs.h:308
TagSet(const BSONArray &tags)
Creates a TagSet from a BSONArray of tags.
Definition dbclient_rs.h:303
TagSet()
Creates a TagSet that matches any nodes.
Class to encapsulate client side "Write Concern" concept.
Definition write_concern.h:35
Core MongoDB C++ driver interfaces are defined here.
the main MongoDB namespace
Definition bulk_operation_builder.h:24
Definition bsonobj.h:559
Name of a process on the network.
Definition hostandport.h:36
Definition dbclient_rs.h:316
ReadPreferenceSetting(ReadPreference pref, const TagSet &tag)
@parm pref the read preference mode.
Definition dbclient_rs.h:324