MongoDB  2.7.0
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 
27 namespace mongo {
28 
29  class ReplicaSetMonitor;
30  class TagSet;
31  struct ReadPreferenceSetting;
32  typedef shared_ptr<ReplicaSetMonitor> ReplicaSetMonitorPtr;
33 
42  class MONGO_CLIENT_API DBClientReplicaSet : public DBClientBase {
43  public:
44  using DBClientBase::query;
47 
49  DBClientReplicaSet( const string& name , const vector<HostAndPort>& servers, double so_timeout=0 );
50  virtual ~DBClientReplicaSet();
51 
57  bool connect();
58 
66  virtual void logout(const string& dbname, BSONObj& info);
67 
68  // ----------- simple functions --------------
69 
71  virtual auto_ptr<DBClientCursor> query(const 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 string &ns, const Query& query, const BSONObj *fieldsToReturn = 0, int queryOptions = 0);
76 
77  virtual void insert( const string &ns , BSONObj obj , int flags=0);
78 
81  virtual void insert( const string &ns, const vector< BSONObj >& v , int flags=0);
82 
83  virtual void remove( const string &ns , Query obj , int flags );
84 
85  virtual void update( const string &ns , Query query , BSONObj obj , int flags );
86 
87  virtual void killCursor( long long cursorID );
88 
89  // ---- access raw connections ----
90 
97  DBClientConnection& masterConn();
98 
106  DBClientConnection& slaveConn();
107 
108  // ---- callback pieces -------
109 
110  virtual void say( Message &toSend, bool isRetry = false , string* actualServer = 0);
111  virtual bool recv( Message &toRecv );
112  virtual void checkResponse( const char* data, int nReturned, bool* retry = NULL, string* targetHost = NULL );
113 
114  /* this is the callback from our underlying connections to notify us that we got a "not master" error.
115  */
116  void isntMaster();
117 
118  /* this is used to indicate we got a "not master or secondary" error from a secondary.
119  */
120  void isntSecondary();
121 
122  // ----- status ------
123 
124  virtual bool isFailed() const { return ! _master || _master->isFailed(); }
125  bool isStillConnected();
126 
127  // ----- informational ----
128 
129  double getSoTimeout() const { return _so_timeout; }
130 
131  string toString() const { return getServerAddress(); }
132 
133  string getServerAddress() const;
134 
135  virtual ConnectionString::ConnectionType type() const { return ConnectionString::SET; }
136  virtual bool lazySupported() const { return true; }
137 
138  // ---- low level ------
139 
140  virtual bool call( Message &toSend, Message &response, bool assertOk=true , string * actualServer = 0 );
141  virtual bool callRead( Message& toSend , Message& response ) { return checkMaster()->callRead( toSend , response ); }
142 
153  static bool isSecondaryQuery( const string& ns,
154  const BSONObj& queryObj,
155  int queryOptions );
156 
157  virtual void setRunCommandHook(DBClientWithCommands::RunCommandHookFunc func);
158  virtual void setPostRunCommandHook(DBClientWithCommands::PostRunCommandHookFunc func);
159 
160  protected:
163  virtual void _auth(const BSONObj& params);
164 
165  virtual void sayPiggyBack( Message &toSend ) { checkMaster()->say( toSend ); }
166 
167  private:
175  auto_ptr<DBClientCursor> checkSlaveQueryResult( auto_ptr<DBClientCursor> result );
176 
177  DBClientConnection * checkMaster();
178 
191  DBClientConnection* selectNodeUsingTags(shared_ptr<ReadPreferenceSetting> readPref);
192 
197  bool checkLastHost(const ReadPreferenceSetting* readPref);
198 
202  void invalidateLastSlaveOkCache();
203 
204  void _auth( DBClientConnection * conn );
205 
210  static const size_t MAX_RETRY;
211 
212  // Throws a DBException if the monitor doesn't exist and there isn't a cached seed to use.
213  ReplicaSetMonitorPtr _getMonitor() const;
214 
215  string _setName;
216 
217  HostAndPort _masterHost;
218  // Note: reason why this is a shared_ptr is because we want _lastSlaveOkConn to
219  // keep a reference of the _master connection when it selected a primary node.
220  // This is because the primary connection is special in mongos - it is the only
221  // connection that is versioned.
222  // WARNING: do not assign this variable (which will increment the internal ref
223  // counter) to any other variable other than _lastSlaveOkConn.
224  boost::shared_ptr<DBClientConnection> _master;
225 
226  // Last used host in a slaveOk query (can be a primary)
227  HostAndPort _lastSlaveOkHost;
228  // Last used connection in a slaveOk query (can be a primary)
229  boost::shared_ptr<DBClientConnection> _lastSlaveOkConn;
230  boost::shared_ptr<ReadPreferenceSetting> _lastReadPref;
231 
232  double _so_timeout;
233 
234  // we need to store so that when we connect to a new node on failure
235  // we can re-auth
236  // this could be a security issue, as the password is stored in memory
237  // not sure if/how we should handle
238  std::map<string, BSONObj> _auths; // dbName -> auth parameters
239 
240  protected:
241 
245  class LazyState {
246  public:
247  LazyState() :
248  _lastClient( NULL ), _lastOp( -1 ), _secondaryQueryOk( false ), _retries( 0 ) {}
249  DBClientConnection* _lastClient;
250  int _lastOp;
251  bool _secondaryQueryOk;
252  int _retries;
253 
254  } _lazyState;
255 
256  };
257 
261  class MONGO_CLIENT_API TagSet {
262  public:
268  TagSet();
269 
277  explicit TagSet(const BSONArray& tags) : _tags(tags) {}
278 
282  const BSONArray& getTagBSON() const { return _tags; }
283 
284  bool operator==(const TagSet& other) const { return _tags == other._tags; }
285 
286  private:
287  BSONArray _tags;
288  };
289 
290  struct MONGO_CLIENT_API ReadPreferenceSetting {
298  ReadPreferenceSetting(ReadPreference pref, const TagSet& tag):
299  pref(pref), tags(tag) {
300  }
301 
302  inline bool equals(const ReadPreferenceSetting& other) const {
303  return pref == other.pref && tags == other.tags;
304  }
305 
306  BSONObj toBSON() const;
307 
308  const ReadPreference pref;
309  TagSet tags;
310  };
311 }
virtual void update(const string &ns, Query query, BSONObj obj, bool upsert=false, bool multi=false)
updates objects matching query
Definition: dbclient.cpp:1200
ReadPreferenceSetting(ReadPreference pref, const TagSet &tag)
pref the read preference mode.
Definition: dbclient_rs.h:298
boost::function< void(BSONObjBuilder *)> RunCommandHookFunc
A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns ...
Definition: dbclientinterface.h:987
abstract class that implements the core db operations
Definition: dbclientinterface.h:1058
boost::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:997
Definition: dbclient_rs.h:290
Use this class to connect to a replica set of servers.
Definition: dbclient_rs.h:42
A basic connection to the database.
Definition: dbclientinterface.h:1194
Core MongoDB C++ driver interfaces are defined here.
TagSet(const BSONArray &tags)
Creates a TagSet from a BSONArray of tags.
Definition: dbclient_rs.h:277
for storing (non-threadsafe) information between lazy calls
Definition: dbclient_rs.h:245
A simple object for representing the list of tags requested by a $readPreference. ...
Definition: dbclient_rs.h:261
virtual auto_ptr< DBClientCursor > query(const string &ns, Query query, int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
send a query to the database.
Definition: dbclient.cpp:1021
helper for manipulating host:port connection endpoints.
Definition: hostandport.h:31
C++ representation of a "BSON" object – that is, an extended JSON-style object in a binary representa...
Definition: bsonobj.h:77
const BSONArray & getTagBSON() const
Returns the BSONArray listing all tags that should be accepted.
Definition: dbclient_rs.h:282
Represents a Mongo query expression.
Definition: dbclientinterface.h:350
Definition: bsonobj.h:585
Definition: message.h:153
virtual void remove(const string &ns, Query q, bool justOne=0)
remove matching objects from the database
Definition: dbclient.cpp:1173