diff options
author | Mark Benvenuto <mark.benvenuto@mongodb.com> | 2015-06-20 00:22:50 -0400 |
---|---|---|
committer | Mark Benvenuto <mark.benvenuto@mongodb.com> | 2015-06-20 10:56:02 -0400 |
commit | 9c2ed42daa8fbbef4a919c21ec564e2db55e8d60 (patch) | |
tree | 3814f79c10d7b490948d8cb7b112ac1dd41ceff1 /src/mongo/dbtests/mock | |
parent | 01965cf52bce6976637ecb8f4a622aeb05ab256a (diff) | |
download | mongo-9c2ed42daa8fbbef4a919c21ec564e2db55e8d60.tar.gz |
SERVER-18579: Clang-Format - reformat code, no comment reflow
Diffstat (limited to 'src/mongo/dbtests/mock')
-rw-r--r-- | src/mongo/dbtests/mock/mock_conn_registry.cpp | 106 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_conn_registry.h | 136 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_dbclient_connection.cpp | 299 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_dbclient_connection.h | 199 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_dbclient_cursor.cpp | 24 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_dbclient_cursor.h | 37 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_remote_db_server.cpp | 354 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_remote_db_server.h | 355 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_replica_set.cpp | 417 | ||||
-rw-r--r-- | src/mongo/dbtests/mock/mock_replica_set.h | 195 |
10 files changed, 1054 insertions, 1068 deletions
diff --git a/src/mongo/dbtests/mock/mock_conn_registry.cpp b/src/mongo/dbtests/mock/mock_conn_registry.cpp index ad6cacb760c..2a34309a044 100644 --- a/src/mongo/dbtests/mock/mock_conn_registry.cpp +++ b/src/mongo/dbtests/mock/mock_conn_registry.cpp @@ -33,77 +33,73 @@ namespace mongo { - using std::string; +using std::string; - std::unique_ptr<MockConnRegistry> MockConnRegistry::_instance; +std::unique_ptr<MockConnRegistry> MockConnRegistry::_instance; - MONGO_INITIALIZER(MockConnRegistry)(InitializerContext* context) { - return MockConnRegistry::init(); - } - - Status MockConnRegistry::init() { - MockConnRegistry::_instance.reset(new MockConnRegistry()); - return Status::OK(); - } +MONGO_INITIALIZER(MockConnRegistry)(InitializerContext* context) { + return MockConnRegistry::init(); +} - MockConnRegistry::MockConnRegistry() : _mockConnStrHook(this) {} +Status MockConnRegistry::init() { + MockConnRegistry::_instance.reset(new MockConnRegistry()); + return Status::OK(); +} - MockConnRegistry* MockConnRegistry::get() { - return _instance.get(); - } +MockConnRegistry::MockConnRegistry() : _mockConnStrHook(this) {} - ConnectionString::ConnectionHook* MockConnRegistry::getConnStrHook() { - return &_mockConnStrHook; - } +MockConnRegistry* MockConnRegistry::get() { + return _instance.get(); +} - void MockConnRegistry::addServer(MockRemoteDBServer* server) { - stdx::lock_guard<stdx::mutex> sl(_registryMutex); +ConnectionString::ConnectionHook* MockConnRegistry::getConnStrHook() { + return &_mockConnStrHook; +} - const std::string hostName(server->getServerAddress()); - fassert(16533, _registry.count(hostName) == 0); +void MockConnRegistry::addServer(MockRemoteDBServer* server) { + stdx::lock_guard<stdx::mutex> sl(_registryMutex); - _registry[hostName] = server; - } + const std::string hostName(server->getServerAddress()); + fassert(16533, _registry.count(hostName) == 0); - bool MockConnRegistry::removeServer(const std::string& hostName) { - stdx::lock_guard<stdx::mutex> sl(_registryMutex); - return _registry.erase(hostName) == 1; - } + _registry[hostName] = server; +} - void MockConnRegistry::clear() { - stdx::lock_guard<stdx::mutex> sl(_registryMutex); - _registry.clear(); - } +bool MockConnRegistry::removeServer(const std::string& hostName) { + stdx::lock_guard<stdx::mutex> sl(_registryMutex); + return _registry.erase(hostName) == 1; +} - MockDBClientConnection* MockConnRegistry::connect(const std::string& connStr) { - stdx::lock_guard<stdx::mutex> sl(_registryMutex); - fassert(16534, _registry.count(connStr) == 1); - return new MockDBClientConnection(_registry[connStr], true); - } +void MockConnRegistry::clear() { + stdx::lock_guard<stdx::mutex> sl(_registryMutex); + _registry.clear(); +} - MockConnRegistry::MockConnHook::MockConnHook(MockConnRegistry* registry): - _registry(registry) { - } +MockDBClientConnection* MockConnRegistry::connect(const std::string& connStr) { + stdx::lock_guard<stdx::mutex> sl(_registryMutex); + fassert(16534, _registry.count(connStr) == 1); + return new MockDBClientConnection(_registry[connStr], true); +} - MockConnRegistry::MockConnHook::~MockConnHook() { - } +MockConnRegistry::MockConnHook::MockConnHook(MockConnRegistry* registry) : _registry(registry) {} - mongo::DBClientBase* MockConnRegistry::MockConnHook::connect( - const ConnectionString& connString, - std::string& errmsg, - double socketTimeout) { - const string hostName(connString.toString()); - MockDBClientConnection* conn = _registry->connect(hostName); +MockConnRegistry::MockConnHook::~MockConnHook() {} - if (!conn->connect(hostName.c_str(), errmsg)) { - // Assumption: connect never throws, so no leak. - delete conn; +mongo::DBClientBase* MockConnRegistry::MockConnHook::connect(const ConnectionString& connString, + std::string& errmsg, + double socketTimeout) { + const string hostName(connString.toString()); + MockDBClientConnection* conn = _registry->connect(hostName); - // mimic ConnectionString::connect for MASTER type connection to return NULL - // if the destination is unreachable. - return NULL; - } + if (!conn->connect(hostName.c_str(), errmsg)) { + // Assumption: connect never throws, so no leak. + delete conn; - return conn; + // mimic ConnectionString::connect for MASTER type connection to return NULL + // if the destination is unreachable. + return NULL; } + + return conn; +} } diff --git a/src/mongo/dbtests/mock/mock_conn_registry.h b/src/mongo/dbtests/mock/mock_conn_registry.h index 6822df4b57e..33764885a69 100644 --- a/src/mongo/dbtests/mock/mock_conn_registry.h +++ b/src/mongo/dbtests/mock/mock_conn_registry.h @@ -37,85 +37,85 @@ #include "mongo/util/concurrency/mutex.h" namespace mongo { +/** + * Registry for storing mock servers and can create mock connections to these + * servers. + */ +class MockConnRegistry { +public: /** - * Registry for storing mock servers and can create mock connections to these - * servers. + * Initializes the static instance. */ - class MockConnRegistry { - public: - /** - * Initializes the static instance. - */ - static Status init(); + static Status init(); - /** - * @return the singleton registry. If this needs to be called before main(), - * then the initializer method should depend on "MockConnRegistry". - */ - static MockConnRegistry* get(); + /** + * @return the singleton registry. If this needs to be called before main(), + * then the initializer method should depend on "MockConnRegistry". + */ + static MockConnRegistry* get(); - /** - * Adds a server to this registry. - * - * @param server the server to add. Caller is responsible for disposing - * the server. - */ - void addServer(MockRemoteDBServer* server); + /** + * Adds a server to this registry. + * + * @param server the server to add. Caller is responsible for disposing + * the server. + */ + void addServer(MockRemoteDBServer* server); - /** - * Removes the server from this registry. - * - * @param hostName the host name of the server to remove. - * - * @return true if the server is in the registry and was removed. - */ - bool removeServer(const std::string& hostName); + /** + * Removes the server from this registry. + * + * @param hostName the host name of the server to remove. + * + * @return true if the server is in the registry and was removed. + */ + bool removeServer(const std::string& hostName); - /** - * Clears the registry. - */ - void clear(); + /** + * Clears the registry. + */ + void clear(); - /** - * @return a new mocked connection to a server with the given hostName. - */ - MockDBClientConnection* connect(const std::string& hostName); + /** + * @return a new mocked connection to a server with the given hostName. + */ + MockDBClientConnection* connect(const std::string& hostName); + + /** + * @return the hook that can be used with ConnectionString. + */ + ConnectionString::ConnectionHook* getConnStrHook(); +private: + class MockConnHook : public ConnectionString::ConnectionHook { + public: /** - * @return the hook that can be used with ConnectionString. + * Creates a new connection hook for the ConnectionString class that + * can create mock connections to mock replica set members using their + * pseudo host names. + * + * @param replSet the mock replica set. Caller is responsible for managing + * replSet and making sure that it lives longer than this object. */ - ConnectionString::ConnectionHook* getConnStrHook(); + MockConnHook(MockConnRegistry* registry); + ~MockConnHook(); + + mongo::DBClientBase* connect(const mongo::ConnectionString& connString, + std::string& errmsg, + double socketTimeout); private: - class MockConnHook: public ConnectionString::ConnectionHook { - public: - /** - * Creates a new connection hook for the ConnectionString class that - * can create mock connections to mock replica set members using their - * pseudo host names. - * - * @param replSet the mock replica set. Caller is responsible for managing - * replSet and making sure that it lives longer than this object. - */ - MockConnHook(MockConnRegistry* registry); - ~MockConnHook(); - - mongo::DBClientBase* connect( - const mongo::ConnectionString& connString, - std::string& errmsg, double socketTimeout); - - private: - MockConnRegistry* _registry; - }; - - MockConnRegistry(); - - static std::unique_ptr<MockConnRegistry> _instance; - - MockConnHook _mockConnStrHook; - - // protects _registry - stdx::mutex _registryMutex; - unordered_map<std::string, MockRemoteDBServer*> _registry; + MockConnRegistry* _registry; }; + + MockConnRegistry(); + + static std::unique_ptr<MockConnRegistry> _instance; + + MockConnHook _mockConnStrHook; + + // protects _registry + stdx::mutex _registryMutex; + unordered_map<std::string, MockRemoteDBServer*> _registry; +}; } diff --git a/src/mongo/dbtests/mock/mock_dbclient_connection.cpp b/src/mongo/dbtests/mock/mock_dbclient_connection.cpp index 612765b7d9e..b357b6bf74c 100644 --- a/src/mongo/dbtests/mock/mock_dbclient_connection.cpp +++ b/src/mongo/dbtests/mock/mock_dbclient_connection.cpp @@ -37,188 +37,183 @@ using std::string; using std::vector; namespace mongo { - MockDBClientConnection::MockDBClientConnection(MockRemoteDBServer* remoteServer, - bool autoReconnect): - _remoteServerInstanceID(remoteServer->getInstanceID()), - _remoteServer(remoteServer), - _isFailed(false), - _sockCreationTime(mongo::curTimeMicros64()), - _autoReconnect(autoReconnect) { - } +MockDBClientConnection::MockDBClientConnection(MockRemoteDBServer* remoteServer, bool autoReconnect) + : _remoteServerInstanceID(remoteServer->getInstanceID()), + _remoteServer(remoteServer), + _isFailed(false), + _sockCreationTime(mongo::curTimeMicros64()), + _autoReconnect(autoReconnect) {} + +MockDBClientConnection::~MockDBClientConnection() {} - MockDBClientConnection::~MockDBClientConnection() { +bool MockDBClientConnection::connect(const char* hostName, std::string& errmsg) { + if (_remoteServer->isRunning()) { + _remoteServerInstanceID = _remoteServer->getInstanceID(); + return true; } - bool MockDBClientConnection::connect(const char* hostName, std::string& errmsg) { - if (_remoteServer->isRunning()) { - _remoteServerInstanceID = _remoteServer->getInstanceID(); - return true; - } + errmsg.assign("cannot connect to " + _remoteServer->getServerAddress()); + return false; +} + +bool MockDBClientConnection::runCommand(const string& dbname, + const BSONObj& cmdObj, + BSONObj& info, + int options) { + checkConnection(); - errmsg.assign("cannot connect to " + _remoteServer->getServerAddress()); - return false; + try { + return _remoteServer->runCommand(_remoteServerInstanceID, dbname, cmdObj, info, options); + } catch (const mongo::SocketException&) { + _isFailed = true; + throw; } - bool MockDBClientConnection::runCommand(const string& dbname, const BSONObj& cmdObj, - BSONObj &info, int options) { - checkConnection(); + return false; +} - try { - return _remoteServer->runCommand(_remoteServerInstanceID, dbname, cmdObj, - info, options); - } - catch (const mongo::SocketException&) { - _isFailed = true; - throw; - } +rpc::UniqueReply MockDBClientConnection::runCommandWithMetadata(StringData database, + StringData command, + const BSONObj& metadata, + const BSONObj& commandArgs) { + checkConnection(); - return false; + try { + return _remoteServer->runCommandWithMetadata( + _remoteServerInstanceID, database, command, metadata, commandArgs); + } catch (const mongo::SocketException&) { + _isFailed = true; + throw; } - rpc::UniqueReply MockDBClientConnection::runCommandWithMetadata(StringData database, - StringData command, - const BSONObj &metadata, - const BSONObj &commandArgs) { - checkConnection(); - - try { - return _remoteServer->runCommandWithMetadata(_remoteServerInstanceID, - database, - command, - metadata, - commandArgs); - } - catch (const mongo::SocketException&) { - _isFailed = true; - throw; - } - - MONGO_UNREACHABLE; - } + MONGO_UNREACHABLE; +} - std::unique_ptr<mongo::DBClientCursor> MockDBClientConnection::query(const string& ns, - mongo::Query query, - int nToReturn, - int nToSkip, - const BSONObj* fieldsToReturn, - int queryOptions, - int batchSize) { - checkConnection(); - - try { - mongo::BSONArray result(_remoteServer->query(_remoteServerInstanceID, ns, query, - nToReturn, nToSkip, fieldsToReturn, queryOptions, batchSize)); - - std::unique_ptr<mongo::DBClientCursor> cursor; - cursor.reset(new MockDBClientCursor(this, result)); - return cursor; - } - catch (const mongo::SocketException&) { - _isFailed = true; - throw; - } - - std::unique_ptr<mongo::DBClientCursor> nullPtr; - return nullPtr; - } +std::unique_ptr<mongo::DBClientCursor> MockDBClientConnection::query(const string& ns, + mongo::Query query, + int nToReturn, + int nToSkip, + const BSONObj* fieldsToReturn, + int queryOptions, + int batchSize) { + checkConnection(); + + try { + mongo::BSONArray result(_remoteServer->query(_remoteServerInstanceID, + ns, + query, + nToReturn, + nToSkip, + fieldsToReturn, + queryOptions, + batchSize)); + + std::unique_ptr<mongo::DBClientCursor> cursor; + cursor.reset(new MockDBClientCursor(this, result)); + return cursor; + } catch (const mongo::SocketException&) { + _isFailed = true; + throw; + } + + std::unique_ptr<mongo::DBClientCursor> nullPtr; + return nullPtr; +} - mongo::ConnectionString::ConnectionType MockDBClientConnection::type() const { - return mongo::ConnectionString::CUSTOM; - } +mongo::ConnectionString::ConnectionType MockDBClientConnection::type() const { + return mongo::ConnectionString::CUSTOM; +} - bool MockDBClientConnection::isFailed() const { - return _isFailed; - } +bool MockDBClientConnection::isFailed() const { + return _isFailed; +} - string MockDBClientConnection::getServerAddress() const { - return _remoteServer->getServerAddress(); - } +string MockDBClientConnection::getServerAddress() const { + return _remoteServer->getServerAddress(); +} - string MockDBClientConnection::toString() const { - return _remoteServer->toString(); - } +string MockDBClientConnection::toString() const { + return _remoteServer->toString(); +} - unsigned long long MockDBClientConnection::query(stdx::function<void(const BSONObj&)> f, - const string& ns, - mongo::Query query, - const BSONObj* fieldsToReturn, - int queryOptions) { - verify(false); - return 0; - } +unsigned long long MockDBClientConnection::query(stdx::function<void(const BSONObj&)> f, + const string& ns, + mongo::Query query, + const BSONObj* fieldsToReturn, + int queryOptions) { + verify(false); + return 0; +} - unsigned long long MockDBClientConnection::query(stdx::function<void( - mongo::DBClientCursorBatchIterator&)> f, - const std::string& ns, - mongo::Query query, - const mongo::BSONObj* fieldsToReturn, - int queryOptions) { - verify(false); - return 0; - } +unsigned long long MockDBClientConnection::query( + stdx::function<void(mongo::DBClientCursorBatchIterator&)> f, + const std::string& ns, + mongo::Query query, + const mongo::BSONObj* fieldsToReturn, + int queryOptions) { + verify(false); + return 0; +} - uint64_t MockDBClientConnection::getSockCreationMicroSec() const { - return _sockCreationTime; - } +uint64_t MockDBClientConnection::getSockCreationMicroSec() const { + return _sockCreationTime; +} - void MockDBClientConnection::insert(const string &ns, BSONObj obj, int flags) { - _remoteServer->insert(ns, obj, flags); - } +void MockDBClientConnection::insert(const string& ns, BSONObj obj, int flags) { + _remoteServer->insert(ns, obj, flags); +} - void MockDBClientConnection::insert(const string &ns, - const vector<BSONObj>& objList, - int flags) { - for (vector<BSONObj>::const_iterator iter = objList.begin(); - iter != objList.end(); ++iter) { - insert(ns, *iter, flags); - } +void MockDBClientConnection::insert(const string& ns, const vector<BSONObj>& objList, int flags) { + for (vector<BSONObj>::const_iterator iter = objList.begin(); iter != objList.end(); ++iter) { + insert(ns, *iter, flags); } +} - void MockDBClientConnection::remove(const string& ns, Query query, bool justOne) { - remove(ns, query, (justOne ? RemoveOption_JustOne : 0)); - } +void MockDBClientConnection::remove(const string& ns, Query query, bool justOne) { + remove(ns, query, (justOne ? RemoveOption_JustOne : 0)); +} - void MockDBClientConnection::remove(const string& ns, Query query, int flags) { - _remoteServer->remove(ns, query, flags); - } +void MockDBClientConnection::remove(const string& ns, Query query, int flags) { + _remoteServer->remove(ns, query, flags); +} - void MockDBClientConnection::killCursor(long long cursorID) { - verify(false); // unimplemented - } +void MockDBClientConnection::killCursor(long long cursorID) { + verify(false); // unimplemented +} - bool MockDBClientConnection::callRead(mongo::Message& toSend , mongo::Message& response) { - verify(false); // unimplemented - return false; - } +bool MockDBClientConnection::callRead(mongo::Message& toSend, mongo::Message& response) { + verify(false); // unimplemented + return false; +} - bool MockDBClientConnection::call(mongo::Message& toSend, - mongo::Message& response, - bool assertOk, - string* actualServer) { - verify(false); // unimplemented - return false; - } +bool MockDBClientConnection::call(mongo::Message& toSend, + mongo::Message& response, + bool assertOk, + string* actualServer) { + verify(false); // unimplemented + return false; +} - void MockDBClientConnection::say(mongo::Message& toSend, bool isRetry, string* actualServer) { - verify(false); // unimplemented - } +void MockDBClientConnection::say(mongo::Message& toSend, bool isRetry, string* actualServer) { + verify(false); // unimplemented +} - void MockDBClientConnection::sayPiggyBack(mongo::Message& toSend) { - verify(false); // unimplemented - } +void MockDBClientConnection::sayPiggyBack(mongo::Message& toSend) { + verify(false); // unimplemented +} - bool MockDBClientConnection::lazySupported() const { - verify(false); // unimplemented - return false; - } +bool MockDBClientConnection::lazySupported() const { + verify(false); // unimplemented + return false; +} - double MockDBClientConnection::getSoTimeout() const { - return 0; - } +double MockDBClientConnection::getSoTimeout() const { + return 0; +} - void MockDBClientConnection::checkConnection() { - if (_isFailed && _autoReconnect) { - _remoteServerInstanceID = _remoteServer->getInstanceID(); - } +void MockDBClientConnection::checkConnection() { + if (_isFailed && _autoReconnect) { + _remoteServerInstanceID = _remoteServer->getInstanceID(); } } +} diff --git a/src/mongo/dbtests/mock/mock_dbclient_connection.h b/src/mongo/dbtests/mock/mock_dbclient_connection.h index 7cb02f9636e..3572e33b11b 100644 --- a/src/mongo/dbtests/mock/mock_dbclient_connection.h +++ b/src/mongo/dbtests/mock/mock_dbclient_connection.h @@ -34,103 +34,110 @@ #include "mongo/dbtests/mock/mock_remote_db_server.h" namespace mongo { +/** + * A simple class for mocking mongo::DBClientConnection. + * + * Also check out sample usage in dbtests/mock_dbclient_conn_test.cpp + */ +class MockDBClientConnection : public mongo::DBClientConnection { +public: /** - * A simple class for mocking mongo::DBClientConnection. + * Create a mock connection to a mock server. * - * Also check out sample usage in dbtests/mock_dbclient_conn_test.cpp + * @param remoteServer the remote server to connect to. The caller is + * responsible for making sure that the life of remoteServer is + * longer than this connection. + * @param autoReconnect will automatically re-establish connection the + * next time an operation is requested when the last operation caused + * this connection to fall into a failed state. */ - class MockDBClientConnection : public mongo::DBClientConnection { - public: - /** - * Create a mock connection to a mock server. - * - * @param remoteServer the remote server to connect to. The caller is - * responsible for making sure that the life of remoteServer is - * longer than this connection. - * @param autoReconnect will automatically re-establish connection the - * next time an operation is requested when the last operation caused - * this connection to fall into a failed state. - */ - MockDBClientConnection(MockRemoteDBServer* remoteServer, bool autoReconnect = false); - virtual ~MockDBClientConnection(); - - // - // DBClientBase methods - // - - bool connect(const char* hostName, std::string& errmsg); - - inline bool connect(const HostAndPort& host, std::string& errmsg) { - return connect(host.toString().c_str(), errmsg); - } - - bool runCommand(const std::string& dbname, const mongo::BSONObj& cmdObj, - mongo::BSONObj &info, int options = 0); - - rpc::UniqueReply runCommandWithMetadata(StringData database, - StringData command, - const BSONObj& metadata, - const BSONObj& commandArgs) final; - - std::unique_ptr<mongo::DBClientCursor> query(const std::string &ns, - mongo::Query query = mongo::Query(), - int nToReturn = 0, - int nToSkip = 0, - const mongo::BSONObj* fieldsToReturn = 0, - int queryOptions = 0, - int batchSize = 0); - - uint64_t getSockCreationMicroSec() const; - - virtual void insert(const std::string& ns, BSONObj obj, int flags = 0); - - virtual void insert(const std::string& ns, const std::vector<BSONObj>& objList, int flags = 0); - - virtual void remove(const std::string& ns, Query query, bool justOne = false); - - virtual void remove(const std::string& ns, Query query, int flags = 0); - - // - // Getters - // - - mongo::ConnectionString::ConnectionType type() const; - bool isFailed() const; - double getSoTimeout() const; - std::string getServerAddress() const; - std::string toString() const; - - // - // Unsupported methods (defined to get rid of virtual function was hidden error) - // - unsigned long long query(stdx::function<void(const mongo::BSONObj&)> f, - const std::string& ns, mongo::Query query, - const mongo::BSONObj* fieldsToReturn = 0, int queryOptions = 0); - - unsigned long long query(stdx::function<void(mongo::DBClientCursorBatchIterator&)> f, - const std::string& ns, mongo::Query query, - const mongo::BSONObj* fieldsToReturn = 0, - int queryOptions = 0); - - // - // Unsupported methods (these are pure virtuals in the base class) - // - - void killCursor(long long cursorID); - bool callRead(mongo::Message& toSend , mongo::Message& response); - bool call(mongo::Message& toSend, mongo::Message& response, bool assertOk = true, - std::string* actualServer = 0); - void say(mongo::Message& toSend, bool isRetry = false, std::string* actualServer = 0); - void sayPiggyBack(mongo::Message& toSend); - bool lazySupported() const; - - private: - void checkConnection(); - - MockRemoteDBServer::InstanceID _remoteServerInstanceID; - MockRemoteDBServer* _remoteServer; - bool _isFailed; - uint64_t _sockCreationTime; - bool _autoReconnect; - }; + MockDBClientConnection(MockRemoteDBServer* remoteServer, bool autoReconnect = false); + virtual ~MockDBClientConnection(); + + // + // DBClientBase methods + // + + bool connect(const char* hostName, std::string& errmsg); + + inline bool connect(const HostAndPort& host, std::string& errmsg) { + return connect(host.toString().c_str(), errmsg); + } + + bool runCommand(const std::string& dbname, + const mongo::BSONObj& cmdObj, + mongo::BSONObj& info, + int options = 0); + + rpc::UniqueReply runCommandWithMetadata(StringData database, + StringData command, + const BSONObj& metadata, + const BSONObj& commandArgs) final; + + std::unique_ptr<mongo::DBClientCursor> query(const std::string& ns, + mongo::Query query = mongo::Query(), + int nToReturn = 0, + int nToSkip = 0, + const mongo::BSONObj* fieldsToReturn = 0, + int queryOptions = 0, + int batchSize = 0); + + uint64_t getSockCreationMicroSec() const; + + virtual void insert(const std::string& ns, BSONObj obj, int flags = 0); + + virtual void insert(const std::string& ns, const std::vector<BSONObj>& objList, int flags = 0); + + virtual void remove(const std::string& ns, Query query, bool justOne = false); + + virtual void remove(const std::string& ns, Query query, int flags = 0); + + // + // Getters + // + + mongo::ConnectionString::ConnectionType type() const; + bool isFailed() const; + double getSoTimeout() const; + std::string getServerAddress() const; + std::string toString() const; + + // + // Unsupported methods (defined to get rid of virtual function was hidden error) + // + unsigned long long query(stdx::function<void(const mongo::BSONObj&)> f, + const std::string& ns, + mongo::Query query, + const mongo::BSONObj* fieldsToReturn = 0, + int queryOptions = 0); + + unsigned long long query(stdx::function<void(mongo::DBClientCursorBatchIterator&)> f, + const std::string& ns, + mongo::Query query, + const mongo::BSONObj* fieldsToReturn = 0, + int queryOptions = 0); + + // + // Unsupported methods (these are pure virtuals in the base class) + // + + void killCursor(long long cursorID); + bool callRead(mongo::Message& toSend, mongo::Message& response); + bool call(mongo::Message& toSend, + mongo::Message& response, + bool assertOk = true, + std::string* actualServer = 0); + void say(mongo::Message& toSend, bool isRetry = false, std::string* actualServer = 0); + void sayPiggyBack(mongo::Message& toSend); + bool lazySupported() const; + +private: + void checkConnection(); + + MockRemoteDBServer::InstanceID _remoteServerInstanceID; + MockRemoteDBServer* _remoteServer; + bool _isFailed; + uint64_t _sockCreationTime; + bool _autoReconnect; +}; } diff --git a/src/mongo/dbtests/mock/mock_dbclient_cursor.cpp b/src/mongo/dbtests/mock/mock_dbclient_cursor.cpp index feab994cc7d..4105b866b02 100644 --- a/src/mongo/dbtests/mock/mock_dbclient_cursor.cpp +++ b/src/mongo/dbtests/mock/mock_dbclient_cursor.cpp @@ -30,18 +30,18 @@ #include "mongo/dbtests/mock/mock_dbclient_cursor.h" namespace mongo { - MockDBClientCursor::MockDBClientCursor(mongo::DBClientBase* client, - const mongo::BSONArray& resultSet): - mongo::DBClientCursor(client, "", 0, 0, 0) { - _resultSet = resultSet.copy(); - _cursor.reset(new mongo::DBClientMockCursor(BSONArray(_resultSet))); - } +MockDBClientCursor::MockDBClientCursor(mongo::DBClientBase* client, + const mongo::BSONArray& resultSet) + : mongo::DBClientCursor(client, "", 0, 0, 0) { + _resultSet = resultSet.copy(); + _cursor.reset(new mongo::DBClientMockCursor(BSONArray(_resultSet))); +} - bool MockDBClientCursor::more() { - return _cursor->more(); - } +bool MockDBClientCursor::more() { + return _cursor->more(); +} - mongo::BSONObj MockDBClientCursor::next() { - return _cursor->next(); - } +mongo::BSONObj MockDBClientCursor::next() { + return _cursor->next(); +} } diff --git a/src/mongo/dbtests/mock/mock_dbclient_cursor.h b/src/mongo/dbtests/mock/mock_dbclient_cursor.h index 22fec61898b..19ba5515c76 100644 --- a/src/mongo/dbtests/mock/mock_dbclient_cursor.h +++ b/src/mongo/dbtests/mock/mock_dbclient_cursor.h @@ -35,25 +35,24 @@ namespace mongo { +/** + * Simple adapter class for mongo::DBClientMockCursor to mongo::DBClientCursor. + * Only supports more and next, the behavior of other operations are undefined. + */ +class MockDBClientCursor : public mongo::DBClientCursor { +public: + MockDBClientCursor(mongo::DBClientBase* client, const mongo::BSONArray& mockCollection); + + bool more(); + /** - * Simple adapter class for mongo::DBClientMockCursor to mongo::DBClientCursor. - * Only supports more and next, the behavior of other operations are undefined. + * Note: has the same contract as DBClientCursor - returned BSONObj will + * become invalid when this cursor is destroyed. */ - class MockDBClientCursor: public mongo::DBClientCursor { - public: - MockDBClientCursor(mongo::DBClientBase* client, - const mongo::BSONArray& mockCollection); - - bool more(); - - /** - * Note: has the same contract as DBClientCursor - returned BSONObj will - * become invalid when this cursor is destroyed. - */ - mongo::BSONObj next(); - - private: - std::unique_ptr<mongo::DBClientMockCursor> _cursor; - mongo::BSONObj _resultSet; - }; + mongo::BSONObj next(); + +private: + std::unique_ptr<mongo::DBClientMockCursor> _cursor; + mongo::BSONObj _resultSet; +}; } diff --git a/src/mongo/dbtests/mock/mock_remote_db_server.cpp b/src/mongo/dbtests/mock/mock_remote_db_server.cpp index 7a28d2f7429..963677012f6 100644 --- a/src/mongo/dbtests/mock/mock_remote_db_server.cpp +++ b/src/mongo/dbtests/mock/mock_remote_db_server.cpp @@ -46,222 +46,216 @@ using std::vector; namespace mongo { - MockRemoteDBServer::CircularBSONIterator::CircularBSONIterator( - const vector<BSONObj>& replyVector) { - for (std::vector<mongo::BSONObj>::const_iterator iter = replyVector.begin(); - iter != replyVector.end(); ++iter) { - _replyObjs.push_back(iter->copy()); - } +MockRemoteDBServer::CircularBSONIterator::CircularBSONIterator(const vector<BSONObj>& replyVector) { + for (std::vector<mongo::BSONObj>::const_iterator iter = replyVector.begin(); + iter != replyVector.end(); + ++iter) { + _replyObjs.push_back(iter->copy()); + } + + _iter = _replyObjs.begin(); +} + +BSONObj MockRemoteDBServer::CircularBSONIterator::next() { + verify(_iter != _replyObjs.end()); + BSONObj reply = _iter->copy(); + ++_iter; + + if (_iter == _replyObjs.end()) { _iter = _replyObjs.begin(); } - BSONObj MockRemoteDBServer::CircularBSONIterator::next() { - verify(_iter != _replyObjs.end()); + return reply; +} - BSONObj reply = _iter->copy(); - ++_iter; +MockRemoteDBServer::MockRemoteDBServer(const string& hostAndPort) + : _isRunning(true), + _hostAndPort(hostAndPort), + _delayMilliSec(0), + _cmdCount(0), + _queryCount(0), + _instanceID(0) { + insert(IdentityNS, BSON(HostField(hostAndPort)), 0); + setCommandReply("dbStats", BSON(HostField(hostAndPort))); +} - if (_iter == _replyObjs.end()) { - _iter = _replyObjs.begin(); - } +MockRemoteDBServer::~MockRemoteDBServer() {} - return reply; - } +void MockRemoteDBServer::setDelay(long long milliSec) { + scoped_spinlock sLock(_lock); + _delayMilliSec = milliSec; +} - MockRemoteDBServer::MockRemoteDBServer(const string& hostAndPort): - _isRunning(true), - _hostAndPort(hostAndPort), - _delayMilliSec(0), - _cmdCount(0), - _queryCount(0), - _instanceID(0) { - insert(IdentityNS, BSON(HostField(hostAndPort)), 0); - setCommandReply("dbStats", BSON(HostField(hostAndPort))); - } +void MockRemoteDBServer::shutdown() { + scoped_spinlock sLock(_lock); + _isRunning = false; +} - MockRemoteDBServer::~MockRemoteDBServer() { - } +void MockRemoteDBServer::reboot() { + scoped_spinlock sLock(_lock); + _isRunning = true; + _instanceID++; +} - void MockRemoteDBServer::setDelay(long long milliSec) { - scoped_spinlock sLock(_lock); - _delayMilliSec = milliSec; - } +MockRemoteDBServer::InstanceID MockRemoteDBServer::getInstanceID() const { + scoped_spinlock sLock(_lock); + return _instanceID; +} - void MockRemoteDBServer::shutdown() { - scoped_spinlock sLock(_lock); - _isRunning = false; - } +bool MockRemoteDBServer::isRunning() const { + scoped_spinlock sLock(_lock); + return _isRunning; +} - void MockRemoteDBServer::reboot() { - scoped_spinlock sLock(_lock); - _isRunning = true; - _instanceID++; - } +void MockRemoteDBServer::setCommandReply(const string& cmdName, const mongo::BSONObj& replyObj) { + vector<BSONObj> replySequence; + replySequence.push_back(replyObj); + setCommandReply(cmdName, replySequence); +} - MockRemoteDBServer::InstanceID MockRemoteDBServer::getInstanceID() const { - scoped_spinlock sLock(_lock); - return _instanceID; - } +void MockRemoteDBServer::setCommandReply(const string& cmdName, + const vector<BSONObj>& replySequence) { + scoped_spinlock sLock(_lock); + _cmdMap[cmdName].reset(new CircularBSONIterator(replySequence)); +} - bool MockRemoteDBServer::isRunning() const { - scoped_spinlock sLock(_lock); - return _isRunning; - } +void MockRemoteDBServer::insert(const string& ns, BSONObj obj, int flags) { + scoped_spinlock sLock(_lock); - void MockRemoteDBServer::setCommandReply(const string& cmdName, - const mongo::BSONObj& replyObj) { - vector<BSONObj> replySequence; - replySequence.push_back(replyObj); - setCommandReply(cmdName, replySequence); - } + vector<BSONObj>& mockCollection = _dataMgr[ns]; + mockCollection.push_back(obj.copy()); +} - void MockRemoteDBServer::setCommandReply(const string& cmdName, - const vector<BSONObj>& replySequence) { - scoped_spinlock sLock(_lock); - _cmdMap[cmdName].reset(new CircularBSONIterator(replySequence)); +void MockRemoteDBServer::remove(const string& ns, Query query, int flags) { + scoped_spinlock sLock(_lock); + if (_dataMgr.count(ns) == 0) { + return; } - void MockRemoteDBServer::insert(const string &ns, BSONObj obj, int flags) { - scoped_spinlock sLock(_lock); + _dataMgr.erase(ns); +} - vector<BSONObj>& mockCollection = _dataMgr[ns]; - mockCollection.push_back(obj.copy()); - } +rpc::UniqueReply MockRemoteDBServer::runCommandWithMetadata(MockRemoteDBServer::InstanceID id, + StringData database, + StringData commandName, + const BSONObj& metadata, + const BSONObj& commandArgs) { + checkIfUp(id); + std::string cmdName = commandName.toString(); - void MockRemoteDBServer::remove(const string& ns, Query query, int flags) { - scoped_spinlock sLock(_lock); - if (_dataMgr.count(ns) == 0) { - return; - } + BSONObj reply; + { + scoped_spinlock lk(_lock); - _dataMgr.erase(ns); - } + uassert(ErrorCodes::IllegalOperation, + str::stream() << "no reply for command: " << commandName, + _cmdMap.count(cmdName)); - rpc::UniqueReply MockRemoteDBServer::runCommandWithMetadata(MockRemoteDBServer::InstanceID id, - StringData database, - StringData commandName, - const BSONObj& metadata, - const BSONObj& commandArgs) { - checkIfUp(id); - std::string cmdName = commandName.toString(); - - BSONObj reply; - { - scoped_spinlock lk(_lock); - - uassert(ErrorCodes::IllegalOperation, - str::stream() << "no reply for command: " << commandName, - _cmdMap.count(cmdName)); - - reply = _cmdMap[cmdName]->next(); - } - - if (_delayMilliSec > 0) { - mongo::sleepmillis(_delayMilliSec); - } - - checkIfUp(id); - - { - scoped_spinlock lk(_lock); - _cmdCount++; - } - - // We need to construct a reply message - it will always be read through a view so it - // doesn't matter whether we use CommandReplBuilder or LegacyReplyBuilder - auto message = rpc::CommandReplyBuilder{}.setMetadata(rpc::makeEmptyMetadata()) - .setCommandReply(reply) - .done(); - auto replyView = stdx::make_unique<rpc::CommandReply>(message.get()); - return rpc::UniqueReply(std::move(message), std::move(replyView)); + reply = _cmdMap[cmdName]->next(); } - bool MockRemoteDBServer::runCommand(MockRemoteDBServer::InstanceID id, - const string& dbname, - const BSONObj& cmdObj, - BSONObj &info, - int options) { - BSONObj upconvertedRequest; - BSONObj upconvertedMetadata; - std::tie(upconvertedRequest, upconvertedMetadata) = uassertStatusOK( - rpc::upconvertRequestMetadata(cmdObj, options) - ); - - StringData commandName = upconvertedRequest.firstElementFieldName(); - - auto res = runCommandWithMetadata(id, - dbname, - commandName, - upconvertedMetadata, - upconvertedRequest); - - info = res->getCommandReply().getOwned(); - return info["ok"].trueValue(); + if (_delayMilliSec > 0) { + mongo::sleepmillis(_delayMilliSec); } - mongo::BSONArray MockRemoteDBServer::query( - MockRemoteDBServer::InstanceID id, - const string& ns, - mongo::Query query, - int nToReturn, - int nToSkip, - const BSONObj* fieldsToReturn, - int queryOptions, - int batchSize) { - checkIfUp(id); - - if (_delayMilliSec > 0) { - mongo::sleepmillis(_delayMilliSec); - } - - checkIfUp(id); - - scoped_spinlock sLock(_lock); - _queryCount++; - - const vector<BSONObj>& coll = _dataMgr[ns]; - BSONArrayBuilder result; - for (vector<BSONObj>::const_iterator iter = coll.begin(); iter != coll.end(); ++ iter) { - result.append(iter->copy()); - } - - return BSONArray(result.obj()); - } + checkIfUp(id); - mongo::ConnectionString::ConnectionType MockRemoteDBServer::type() const { - return mongo::ConnectionString::CUSTOM; + { + scoped_spinlock lk(_lock); + _cmdCount++; } - size_t MockRemoteDBServer::getCmdCount() const { - scoped_spinlock sLock(_lock); - return _cmdCount; - } + // We need to construct a reply message - it will always be read through a view so it + // doesn't matter whether we use CommandReplBuilder or LegacyReplyBuilder + auto message = rpc::CommandReplyBuilder{} + .setMetadata(rpc::makeEmptyMetadata()) + .setCommandReply(reply) + .done(); + auto replyView = stdx::make_unique<rpc::CommandReply>(message.get()); + return rpc::UniqueReply(std::move(message), std::move(replyView)); +} - size_t MockRemoteDBServer::getQueryCount() const { - scoped_spinlock sLock(_lock); - return _queryCount; - } +bool MockRemoteDBServer::runCommand(MockRemoteDBServer::InstanceID id, + const string& dbname, + const BSONObj& cmdObj, + BSONObj& info, + int options) { + BSONObj upconvertedRequest; + BSONObj upconvertedMetadata; + std::tie(upconvertedRequest, upconvertedMetadata) = + uassertStatusOK(rpc::upconvertRequestMetadata(cmdObj, options)); - void MockRemoteDBServer::clearCounters() { - scoped_spinlock sLock(_lock); - _cmdCount = 0; - _queryCount = 0; - } + StringData commandName = upconvertedRequest.firstElementFieldName(); + + auto res = + runCommandWithMetadata(id, dbname, commandName, upconvertedMetadata, upconvertedRequest); - string MockRemoteDBServer::getServerAddress() const { - return _hostAndPort; + info = res->getCommandReply().getOwned(); + return info["ok"].trueValue(); +} + +mongo::BSONArray MockRemoteDBServer::query(MockRemoteDBServer::InstanceID id, + const string& ns, + mongo::Query query, + int nToReturn, + int nToSkip, + const BSONObj* fieldsToReturn, + int queryOptions, + int batchSize) { + checkIfUp(id); + + if (_delayMilliSec > 0) { + mongo::sleepmillis(_delayMilliSec); } - string MockRemoteDBServer::toString() { - return _hostAndPort; + checkIfUp(id); + + scoped_spinlock sLock(_lock); + _queryCount++; + + const vector<BSONObj>& coll = _dataMgr[ns]; + BSONArrayBuilder result; + for (vector<BSONObj>::const_iterator iter = coll.begin(); iter != coll.end(); ++iter) { + result.append(iter->copy()); } - void MockRemoteDBServer::checkIfUp(InstanceID id) const { - scoped_spinlock sLock(_lock); + return BSONArray(result.obj()); +} + +mongo::ConnectionString::ConnectionType MockRemoteDBServer::type() const { + return mongo::ConnectionString::CUSTOM; +} + +size_t MockRemoteDBServer::getCmdCount() const { + scoped_spinlock sLock(_lock); + return _cmdCount; +} + +size_t MockRemoteDBServer::getQueryCount() const { + scoped_spinlock sLock(_lock); + return _queryCount; +} + +void MockRemoteDBServer::clearCounters() { + scoped_spinlock sLock(_lock); + _cmdCount = 0; + _queryCount = 0; +} - if (!_isRunning || id < _instanceID) { - throw mongo::SocketException(mongo::SocketException::CLOSED, _hostAndPort); - } +string MockRemoteDBServer::getServerAddress() const { + return _hostAndPort; +} + +string MockRemoteDBServer::toString() { + return _hostAndPort; +} + +void MockRemoteDBServer::checkIfUp(InstanceID id) const { + scoped_spinlock sLock(_lock); + + if (!_isRunning || id < _instanceID) { + throw mongo::SocketException(mongo::SocketException::CLOSED, _hostAndPort); } } +} diff --git a/src/mongo/dbtests/mock/mock_remote_db_server.h b/src/mongo/dbtests/mock/mock_remote_db_server.h index 6461873636b..791009ec459 100644 --- a/src/mongo/dbtests/mock/mock_remote_db_server.h +++ b/src/mongo/dbtests/mock/mock_remote_db_server.h @@ -38,209 +38,210 @@ namespace mongo { - const std::string IdentityNS("local.me"); - const BSONField<std::string> HostField("host"); +const std::string IdentityNS("local.me"); +const BSONField<std::string> HostField("host"); + +/** + * A very simple mock that acts like a database server. Every object keeps track of its own + * InstanceID, which initially starts at zero and increments every time it is restarted. + * This is primarily used for simulating the state of which old connections won't be able + * to talk to the sockets that has already been closed on this server. + * + * Note: All operations on this server are protected by a lock. + */ +class MockRemoteDBServer { +public: + typedef size_t InstanceID; /** - * A very simple mock that acts like a database server. Every object keeps track of its own - * InstanceID, which initially starts at zero and increments every time it is restarted. - * This is primarily used for simulating the state of which old connections won't be able - * to talk to the sockets that has already been closed on this server. + * Creates a new mock server. This can also be setup to work with the + * ConnectionString class by using mongo::MockConnRegistry as follows: + * + * ConnectionString::setConnectionHook(MockConnRegistry::get()->getConnStrHook()); + * MockRemoteDBServer server("$a:27017"); + * MockConnRegistry::get()->addServer(&server); + * + * This allows clients using the ConnectionString::connect interface to create + * connections to this server. The requirements to make this hook fully functional are: * - * Note: All operations on this server are protected by a lock. + * 1. hostAndPort of this server should start with $. + * 2. No other instance has the same hostAndPort as this. + * + * This server will also contain the hostAndPort inside the IdentityNS + * collection. This is convenient for testing query routing. + * + * @param hostAndPort the host name with port for this server. + * + * @see MockConnRegistry */ - class MockRemoteDBServer { - public: - typedef size_t InstanceID; + MockRemoteDBServer(const std::string& hostAndPort); + virtual ~MockRemoteDBServer(); - /** - * Creates a new mock server. This can also be setup to work with the - * ConnectionString class by using mongo::MockConnRegistry as follows: - * - * ConnectionString::setConnectionHook(MockConnRegistry::get()->getConnStrHook()); - * MockRemoteDBServer server("$a:27017"); - * MockConnRegistry::get()->addServer(&server); - * - * This allows clients using the ConnectionString::connect interface to create - * connections to this server. The requirements to make this hook fully functional are: - * - * 1. hostAndPort of this server should start with $. - * 2. No other instance has the same hostAndPort as this. - * - * This server will also contain the hostAndPort inside the IdentityNS - * collection. This is convenient for testing query routing. - * - * @param hostAndPort the host name with port for this server. - * - * @see MockConnRegistry - */ - MockRemoteDBServer(const std::string& hostAndPort); - virtual ~MockRemoteDBServer(); + // + // Connectivity methods + // - // - // Connectivity methods - // - - /** - * Set a delay for calls to query and runCommand - */ - void setDelay(long long milliSec); + /** + * Set a delay for calls to query and runCommand + */ + void setDelay(long long milliSec); - /** - * Shuts down this server. Any operations on this server with an InstanceID - * less than or equal to the current one will throw a mongo::SocketException. - * To bring the server up again, use the reboot method. - */ - void shutdown(); + /** + * Shuts down this server. Any operations on this server with an InstanceID + * less than or equal to the current one will throw a mongo::SocketException. + * To bring the server up again, use the reboot method. + */ + void shutdown(); - /** - * Increments the instanceID of this server. - */ - void reboot(); + /** + * Increments the instanceID of this server. + */ + void reboot(); - /** - * @return true if this server is running - */ - bool isRunning() const; + /** + * @return true if this server is running + */ + bool isRunning() const; - // - // Mocking methods - // + // + // Mocking methods + // - /** - * Sets the reply for a command. - * - * @param cmdName the name of the command - * @param replyObj the exact reply for the command - */ - void setCommandReply(const std::string& cmdName, - const mongo::BSONObj& replyObj); + /** + * Sets the reply for a command. + * + * @param cmdName the name of the command + * @param replyObj the exact reply for the command + */ + void setCommandReply(const std::string& cmdName, const mongo::BSONObj& replyObj); - /** - * Sets the reply for a command. - * - * @param cmdName the name of the command. - * @param replySequence the sequence of replies to cycle through every time - * the given command is requested. This is useful for setting up a - * sequence of response when the command can be called more than once - * that requires different results when calling a method. - */ - void setCommandReply(const std::string& cmdName, - const std::vector<mongo::BSONObj>& replySequence); + /** + * Sets the reply for a command. + * + * @param cmdName the name of the command. + * @param replySequence the sequence of replies to cycle through every time + * the given command is requested. This is useful for setting up a + * sequence of response when the command can be called more than once + * that requires different results when calling a method. + */ + void setCommandReply(const std::string& cmdName, + const std::vector<mongo::BSONObj>& replySequence); - /** - * Inserts a single document to this server. - * - * @param ns the namespace to insert the document to. - * @param obj the document to insert. - * @param flags ignored. - */ - void insert(const std::string& ns, BSONObj obj, int flags = 0); + /** + * Inserts a single document to this server. + * + * @param ns the namespace to insert the document to. + * @param obj the document to insert. + * @param flags ignored. + */ + void insert(const std::string& ns, BSONObj obj, int flags = 0); - /** - * Removes documents from this server. - * - * @param ns the namespace to remove documents from. - * @param query ignored. - * @param flags ignored. - */ - void remove(const std::string& ns, Query query, int flags = 0); - - // - // DBClientBase methods - // - bool runCommand(InstanceID id, const std::string& dbname, - const mongo::BSONObj& cmdObj, - mongo::BSONObj &info, int options = 0); - - rpc::UniqueReply runCommandWithMetadata(InstanceID id, - StringData database, - StringData commandName, - const BSONObj& metadata, - const BSONObj& commandArgs); - - mongo::BSONArray query(InstanceID id, - const std::string &ns, - mongo::Query query = mongo::Query(), - int nToReturn = 0, - int nToSkip = 0, - const mongo::BSONObj* fieldsToReturn = 0, - int queryOptions = 0, - int batchSize = 0); - - // - // Getters - // - - InstanceID getInstanceID() const; - mongo::ConnectionString::ConnectionType type() const; - double getSoTimeout() const; + /** + * Removes documents from this server. + * + * @param ns the namespace to remove documents from. + * @param query ignored. + * @param flags ignored. + */ + void remove(const std::string& ns, Query query, int flags = 0); + + // + // DBClientBase methods + // + bool runCommand(InstanceID id, + const std::string& dbname, + const mongo::BSONObj& cmdObj, + mongo::BSONObj& info, + int options = 0); + + rpc::UniqueReply runCommandWithMetadata(InstanceID id, + StringData database, + StringData commandName, + const BSONObj& metadata, + const BSONObj& commandArgs); + + mongo::BSONArray query(InstanceID id, + const std::string& ns, + mongo::Query query = mongo::Query(), + int nToReturn = 0, + int nToSkip = 0, + const mongo::BSONObj* fieldsToReturn = 0, + int queryOptions = 0, + int batchSize = 0); + + // + // Getters + // + + InstanceID getInstanceID() const; + mongo::ConnectionString::ConnectionType type() const; + double getSoTimeout() const; - /** - * @return the exact std::string address passed to hostAndPort parameter of the - * constructor. In other words, doesn't automatically append a - * 'default' port if none is specified. - */ - std::string getServerAddress() const; - std::string toString(); + /** + * @return the exact std::string address passed to hostAndPort parameter of the + * constructor. In other words, doesn't automatically append a + * 'default' port if none is specified. + */ + std::string getServerAddress() const; + std::string toString(); - // - // Call counters - // + // + // Call counters + // - size_t getCmdCount() const; - size_t getQueryCount() const; - void clearCounters(); + size_t getCmdCount() const; + size_t getQueryCount() const; + void clearCounters(); - private: +private: + /** + * A very simple class for cycling through a set of BSONObj + */ + class CircularBSONIterator { + public: /** - * A very simple class for cycling through a set of BSONObj + * Creates a new iterator with a deep copy of the vector. */ - class CircularBSONIterator { - public: - /** - * Creates a new iterator with a deep copy of the vector. - */ - CircularBSONIterator(const std::vector<mongo::BSONObj>& replyVector); - mongo::BSONObj next(); - - private: - std::vector<mongo::BSONObj>::iterator _iter; - std::vector<mongo::BSONObj> _replyObjs; - }; + CircularBSONIterator(const std::vector<mongo::BSONObj>& replyVector); + mongo::BSONObj next(); - /** - * Checks whether the instance of the server is still up. - * - * @throws mongo::SocketException if this server is down - */ - void checkIfUp(InstanceID id) const; + private: + std::vector<mongo::BSONObj>::iterator _iter; + std::vector<mongo::BSONObj> _replyObjs; + }; + + /** + * Checks whether the instance of the server is still up. + * + * @throws mongo::SocketException if this server is down + */ + void checkIfUp(InstanceID id) const; - typedef unordered_map<std::string, std::shared_ptr<CircularBSONIterator> > CmdToReplyObj; - typedef unordered_map<std::string, std::vector<BSONObj> > MockDataMgr; + typedef unordered_map<std::string, std::shared_ptr<CircularBSONIterator>> CmdToReplyObj; + typedef unordered_map<std::string, std::vector<BSONObj>> MockDataMgr; - bool _isRunning; + bool _isRunning; - const std::string _hostAndPort; - long long _delayMilliSec; + const std::string _hostAndPort; + long long _delayMilliSec; - // - // Mock replies - // - CmdToReplyObj _cmdMap; - MockDataMgr _dataMgr; + // + // Mock replies + // + CmdToReplyObj _cmdMap; + MockDataMgr _dataMgr; - // - // Op Counters - // - size_t _cmdCount; - size_t _queryCount; + // + // Op Counters + // + size_t _cmdCount; + size_t _queryCount; - // Unique id for every restart of this server used for rejecting requests from - // connections that are still "connected" to the old instance - InstanceID _instanceID; + // Unique id for every restart of this server used for rejecting requests from + // connections that are still "connected" to the old instance + InstanceID _instanceID; - // protects this entire instance - mutable mongo::SpinLock _lock; - }; + // protects this entire instance + mutable mongo::SpinLock _lock; +}; } diff --git a/src/mongo/dbtests/mock/mock_replica_set.cpp b/src/mongo/dbtests/mock/mock_replica_set.cpp index 16d6adbf2d1..3c969be31f0 100644 --- a/src/mongo/dbtests/mock/mock_replica_set.cpp +++ b/src/mongo/dbtests/mock/mock_replica_set.cpp @@ -38,287 +38,282 @@ using namespace mongo::repl; namespace mongo { - using std::string; - using std::vector; - - MockReplicaSet::MockReplicaSet(const string& setName, size_t nodes): - _setName(setName) { - BSONObjBuilder configBuilder; - configBuilder.append("_id", setName); - configBuilder.append("version", 1); - - BSONArrayBuilder membersBuilder(configBuilder.subarrayStart("members")); - for (size_t n = 0; n < nodes; n++) { - std::stringstream str; - str << "$" << setName << n << ":27017"; - const string hostName(str.str()); - - if (n == 0) { - _primaryHost = hostName; - } +using std::string; +using std::vector; - MockRemoteDBServer* mockServer = new MockRemoteDBServer(hostName); - _nodeMap[hostName] = mockServer; +MockReplicaSet::MockReplicaSet(const string& setName, size_t nodes) : _setName(setName) { + BSONObjBuilder configBuilder; + configBuilder.append("_id", setName); + configBuilder.append("version", 1); - MockConnRegistry::get()->addServer(mockServer); + BSONArrayBuilder membersBuilder(configBuilder.subarrayStart("members")); + for (size_t n = 0; n < nodes; n++) { + std::stringstream str; + str << "$" << setName << n << ":27017"; + const string hostName(str.str()); - membersBuilder.append(BSON("_id" << static_cast<int>(n) << "host" << hostName)); + if (n == 0) { + _primaryHost = hostName; } - membersBuilder.done(); - ReplicaSetConfig replConfig; - fassert(28566, replConfig.initialize(configBuilder.obj())); - fassert(28573, replConfig.validate()); - setConfig(replConfig); - } + MockRemoteDBServer* mockServer = new MockRemoteDBServer(hostName); + _nodeMap[hostName] = mockServer; - MockReplicaSet::~MockReplicaSet() { - for (ReplNodeMap::iterator iter = _nodeMap.begin(); - iter != _nodeMap.end(); ++iter) { - MockConnRegistry::get()->removeServer(iter->second->getServerAddress()); - delete iter->second; - } + MockConnRegistry::get()->addServer(mockServer); + + membersBuilder.append(BSON("_id" << static_cast<int>(n) << "host" << hostName)); } + membersBuilder.done(); - string MockReplicaSet::getSetName() const { - return _setName; + ReplicaSetConfig replConfig; + fassert(28566, replConfig.initialize(configBuilder.obj())); + fassert(28573, replConfig.validate()); + setConfig(replConfig); +} + +MockReplicaSet::~MockReplicaSet() { + for (ReplNodeMap::iterator iter = _nodeMap.begin(); iter != _nodeMap.end(); ++iter) { + MockConnRegistry::get()->removeServer(iter->second->getServerAddress()); + delete iter->second; } +} - string MockReplicaSet::getConnectionString() const { - std::stringstream str; - str << _setName; - str << "/"; +string MockReplicaSet::getSetName() const { + return _setName; +} - ReplNodeMap::const_iterator iter = _nodeMap.begin(); - while (iter != _nodeMap.end()) { - str << iter->second->getServerAddress(); - ++iter; +string MockReplicaSet::getConnectionString() const { + std::stringstream str; + str << _setName; + str << "/"; - if (iter != _nodeMap.end()) { - str << ","; - } - } + ReplNodeMap::const_iterator iter = _nodeMap.begin(); + while (iter != _nodeMap.end()) { + str << iter->second->getServerAddress(); + ++iter; - return str.str(); + if (iter != _nodeMap.end()) { + str << ","; + } } - vector<HostAndPort> MockReplicaSet::getHosts() const { - vector<HostAndPort> list; + return str.str(); +} - for (ReplNodeMap::const_iterator iter = _nodeMap.begin(); - iter != _nodeMap.end(); ++iter) { - list.push_back(HostAndPort(iter->second->getServerAddress())); - } +vector<HostAndPort> MockReplicaSet::getHosts() const { + vector<HostAndPort> list; - return list; + for (ReplNodeMap::const_iterator iter = _nodeMap.begin(); iter != _nodeMap.end(); ++iter) { + list.push_back(HostAndPort(iter->second->getServerAddress())); } - string MockReplicaSet::getPrimary() const { - return _primaryHost; - } + return list; +} - void MockReplicaSet::setPrimary(const string& hostAndPort) { - const MemberConfig* config = _replConfig.findMemberByHostAndPort(HostAndPort(hostAndPort)); - fassert(16578, config); +string MockReplicaSet::getPrimary() const { + return _primaryHost; +} - fassert(16579, !config->isHidden() && config->getPriority() > 0 && !config->isArbiter()); +void MockReplicaSet::setPrimary(const string& hostAndPort) { + const MemberConfig* config = _replConfig.findMemberByHostAndPort(HostAndPort(hostAndPort)); + fassert(16578, config); - _primaryHost = hostAndPort; + fassert(16579, !config->isHidden() && config->getPriority() > 0 && !config->isArbiter()); - mockIsMasterCmd(); - mockReplSetGetStatusCmd(); - } + _primaryHost = hostAndPort; - vector<string> MockReplicaSet::getSecondaries() const { - vector<string> secondaries; + mockIsMasterCmd(); + mockReplSetGetStatusCmd(); +} - for (ReplicaSetConfig::MemberIterator member = _replConfig.membersBegin(); - member != _replConfig.membersEnd(); ++member) { - if (member->getHostAndPort() != HostAndPort(_primaryHost)) { - secondaries.push_back(member->getHostAndPort().toString()); - } - } +vector<string> MockReplicaSet::getSecondaries() const { + vector<string> secondaries; - return secondaries; + for (ReplicaSetConfig::MemberIterator member = _replConfig.membersBegin(); + member != _replConfig.membersEnd(); + ++member) { + if (member->getHostAndPort() != HostAndPort(_primaryHost)) { + secondaries.push_back(member->getHostAndPort().toString()); + } } - MockRemoteDBServer* MockReplicaSet::getNode(const string& hostAndPort) { - return mapFindWithDefault(_nodeMap, hostAndPort, static_cast<MockRemoteDBServer*>(NULL)); - } + return secondaries; +} - repl::ReplicaSetConfig MockReplicaSet::getReplConfig() const { - return _replConfig; - } +MockRemoteDBServer* MockReplicaSet::getNode(const string& hostAndPort) { + return mapFindWithDefault(_nodeMap, hostAndPort, static_cast<MockRemoteDBServer*>(NULL)); +} - void MockReplicaSet::setConfig(const repl::ReplicaSetConfig& newConfig) { - _replConfig = newConfig; - mockIsMasterCmd(); - mockReplSetGetStatusCmd(); - } +repl::ReplicaSetConfig MockReplicaSet::getReplConfig() const { + return _replConfig; +} - void MockReplicaSet::kill(const string& hostAndPort) { - verify(_nodeMap.count(hostAndPort) == 1); - _nodeMap[hostAndPort]->shutdown(); - } +void MockReplicaSet::setConfig(const repl::ReplicaSetConfig& newConfig) { + _replConfig = newConfig; + mockIsMasterCmd(); + mockReplSetGetStatusCmd(); +} - void MockReplicaSet::kill(const vector<string>& hostList) { - for (vector<string>::const_iterator iter = hostList.begin(); - iter != hostList.end(); ++iter) { - kill(*iter); - } - } +void MockReplicaSet::kill(const string& hostAndPort) { + verify(_nodeMap.count(hostAndPort) == 1); + _nodeMap[hostAndPort]->shutdown(); +} - void MockReplicaSet::restore(const string& hostAndPort) { - verify(_nodeMap.count(hostAndPort) == 1); - _nodeMap[hostAndPort]->reboot(); +void MockReplicaSet::kill(const vector<string>& hostList) { + for (vector<string>::const_iterator iter = hostList.begin(); iter != hostList.end(); ++iter) { + kill(*iter); } +} - void MockReplicaSet::mockIsMasterCmd() { - for (ReplNodeMap::iterator nodeIter = _nodeMap.begin(); - nodeIter != _nodeMap.end(); ++nodeIter) { - const string& hostAndPort = nodeIter->first; +void MockReplicaSet::restore(const string& hostAndPort) { + verify(_nodeMap.count(hostAndPort) == 1); + _nodeMap[hostAndPort]->reboot(); +} - BSONObjBuilder builder; - builder.append("setName", _setName); +void MockReplicaSet::mockIsMasterCmd() { + for (ReplNodeMap::iterator nodeIter = _nodeMap.begin(); nodeIter != _nodeMap.end(); + ++nodeIter) { + const string& hostAndPort = nodeIter->first; - const MemberConfig* member = _replConfig.findMemberByHostAndPort( - HostAndPort(hostAndPort)); - if (!member) { - builder.append("ismaster", false); - builder.append("secondary", false); + BSONObjBuilder builder; + builder.append("setName", _setName); + const MemberConfig* member = _replConfig.findMemberByHostAndPort(HostAndPort(hostAndPort)); + if (!member) { + builder.append("ismaster", false); + builder.append("secondary", false); + + vector<string> hostList; + builder.append("hosts", hostList); + } else { + const bool isPrimary = hostAndPort == getPrimary(); + builder.append("ismaster", isPrimary); + builder.append("secondary", !isPrimary); + + { + // TODO: add passives & arbiters vector<string> hostList; - builder.append("hosts", hostList); - } - else { - const bool isPrimary = hostAndPort == getPrimary(); - builder.append("ismaster", isPrimary); - builder.append("secondary", !isPrimary); - - { - // TODO: add passives & arbiters - vector<string> hostList; - hostList.push_back(getPrimary()); - - const vector<string> secondaries = getSecondaries(); - for (vector<string>::const_iterator secIter = secondaries.begin(); - secIter != secondaries.end(); ++secIter) { - hostList.push_back(*secIter); - } + hostList.push_back(getPrimary()); - builder.append("hosts", hostList); + const vector<string> secondaries = getSecondaries(); + for (vector<string>::const_iterator secIter = secondaries.begin(); + secIter != secondaries.end(); + ++secIter) { + hostList.push_back(*secIter); } - builder.append("primary", getPrimary()); + builder.append("hosts", hostList); + } - if (member->isArbiter()) { - builder.append("arbiterOnly", true); - } + builder.append("primary", getPrimary()); - if (member->getPriority() == 0 && !member->isArbiter()) { - builder.append("passive", true); - } + if (member->isArbiter()) { + builder.append("arbiterOnly", true); + } - if (member->getSlaveDelay().count()) { - builder.appendIntOrLL("slaveDelay", member->getSlaveDelay().count()); - } + if (member->getPriority() == 0 && !member->isArbiter()) { + builder.append("passive", true); + } - if (member->isHidden()) { - builder.append("hidden", true); - } + if (member->getSlaveDelay().count()) { + builder.appendIntOrLL("slaveDelay", member->getSlaveDelay().count()); + } - if (!member->shouldBuildIndexes()) { - builder.append("buildIndexes", false); - } + if (member->isHidden()) { + builder.append("hidden", true); + } + + if (!member->shouldBuildIndexes()) { + builder.append("buildIndexes", false); + } - const ReplicaSetTagConfig tagConfig = _replConfig.getTagConfig(); - if (member->hasTags(tagConfig)) { - BSONObjBuilder tagBuilder; - for (MemberConfig::TagIterator tag = member->tagsBegin(); - tag != member->tagsEnd(); ++tag) { - std::string tagKey = tagConfig.getTagKey(*tag); - if (tagKey[0] == '$') { - // Filter out internal tags - continue; - } - tagBuilder.append(tagKey, tagConfig.getTagValue(*tag)); + const ReplicaSetTagConfig tagConfig = _replConfig.getTagConfig(); + if (member->hasTags(tagConfig)) { + BSONObjBuilder tagBuilder; + for (MemberConfig::TagIterator tag = member->tagsBegin(); tag != member->tagsEnd(); + ++tag) { + std::string tagKey = tagConfig.getTagKey(*tag); + if (tagKey[0] == '$') { + // Filter out internal tags + continue; } - builder.append("tags", tagBuilder.done()); + tagBuilder.append(tagKey, tagConfig.getTagValue(*tag)); } + builder.append("tags", tagBuilder.done()); } + } - builder.append("me", hostAndPort); - builder.append("ok", true); + builder.append("me", hostAndPort); + builder.append("ok", true); - nodeIter->second->setCommandReply("ismaster", builder.done()); - } + nodeIter->second->setCommandReply("ismaster", builder.done()); } +} - int MockReplicaSet::getState(const std::string& hostAndPort) const { - if (!_replConfig.findMemberByHostAndPort(HostAndPort(hostAndPort))) { - return static_cast<int>(MemberState::RS_REMOVED); - } - else if (hostAndPort == getPrimary()) { - return static_cast<int>(MemberState::RS_PRIMARY); - } - else { - return static_cast<int>(MemberState::RS_SECONDARY); - } +int MockReplicaSet::getState(const std::string& hostAndPort) const { + if (!_replConfig.findMemberByHostAndPort(HostAndPort(hostAndPort))) { + return static_cast<int>(MemberState::RS_REMOVED); + } else if (hostAndPort == getPrimary()) { + return static_cast<int>(MemberState::RS_PRIMARY); + } else { + return static_cast<int>(MemberState::RS_SECONDARY); } +} - void MockReplicaSet::mockReplSetGetStatusCmd() { - // Copied from ReplSetImpl::_summarizeStatus - for (ReplNodeMap::iterator nodeIter = _nodeMap.begin(); - nodeIter != _nodeMap.end(); ++nodeIter) { - MockRemoteDBServer* node = nodeIter->second; - vector<BSONObj> hostsField; +void MockReplicaSet::mockReplSetGetStatusCmd() { + // Copied from ReplSetImpl::_summarizeStatus + for (ReplNodeMap::iterator nodeIter = _nodeMap.begin(); nodeIter != _nodeMap.end(); + ++nodeIter) { + MockRemoteDBServer* node = nodeIter->second; + vector<BSONObj> hostsField; - BSONObjBuilder fullStatBuilder; + BSONObjBuilder fullStatBuilder; - { - BSONObjBuilder selfStatBuilder; - selfStatBuilder.append("name", node->getServerAddress()); - selfStatBuilder.append("health", 1.0); - selfStatBuilder.append("state", getState(node->getServerAddress())); + { + BSONObjBuilder selfStatBuilder; + selfStatBuilder.append("name", node->getServerAddress()); + selfStatBuilder.append("health", 1.0); + selfStatBuilder.append("state", getState(node->getServerAddress())); - selfStatBuilder.append("self", true); - // TODO: _id, stateStr, uptime, optime, optimeDate, maintenanceMode, errmsg + selfStatBuilder.append("self", true); + // TODO: _id, stateStr, uptime, optime, optimeDate, maintenanceMode, errmsg - hostsField.push_back(selfStatBuilder.obj()); - } + hostsField.push_back(selfStatBuilder.obj()); + } - for (ReplicaSetConfig::MemberIterator member = _replConfig.membersBegin(); - member != _replConfig.membersEnd(); ++member) { - MockRemoteDBServer* hostNode = getNode(member->getHostAndPort().toString()); + for (ReplicaSetConfig::MemberIterator member = _replConfig.membersBegin(); + member != _replConfig.membersEnd(); + ++member) { + MockRemoteDBServer* hostNode = getNode(member->getHostAndPort().toString()); - if (hostNode == node) { - continue; - } + if (hostNode == node) { + continue; + } - BSONObjBuilder hostMemberBuilder; + BSONObjBuilder hostMemberBuilder; - // TODO: _id, stateStr, uptime, optime, optimeDate, lastHeartbeat, pingMs - // errmsg, authenticated + // TODO: _id, stateStr, uptime, optime, optimeDate, lastHeartbeat, pingMs + // errmsg, authenticated - hostMemberBuilder.append("name", hostNode->getServerAddress()); - const double health = hostNode->isRunning() ? 1.0 : 0.0; - hostMemberBuilder.append("health", health); - hostMemberBuilder.append("state", getState(hostNode->getServerAddress())); + hostMemberBuilder.append("name", hostNode->getServerAddress()); + const double health = hostNode->isRunning() ? 1.0 : 0.0; + hostMemberBuilder.append("health", health); + hostMemberBuilder.append("state", getState(hostNode->getServerAddress())); - hostsField.push_back(hostMemberBuilder.obj()); - } + hostsField.push_back(hostMemberBuilder.obj()); + } - sort(hostsField.begin(), hostsField.end()); + sort(hostsField.begin(), hostsField.end()); - // TODO: syncingTo + // TODO: syncingTo - fullStatBuilder.append("set", _setName); - fullStatBuilder.appendTimeT("date", time(0)); - fullStatBuilder.append("myState", getState(node->getServerAddress())); - fullStatBuilder.append("members", hostsField); - fullStatBuilder.append("ok", true); + fullStatBuilder.append("set", _setName); + fullStatBuilder.appendTimeT("date", time(0)); + fullStatBuilder.append("myState", getState(node->getServerAddress())); + fullStatBuilder.append("members", hostsField); + fullStatBuilder.append("ok", true); - node->setCommandReply("replSetGetStatus", fullStatBuilder.done()); - } + node->setCommandReply("replSetGetStatus", fullStatBuilder.done()); } } +} diff --git a/src/mongo/dbtests/mock/mock_replica_set.h b/src/mongo/dbtests/mock/mock_replica_set.h index 9c394c97648..c3f22c3cb97 100644 --- a/src/mongo/dbtests/mock/mock_replica_set.h +++ b/src/mongo/dbtests/mock/mock_replica_set.h @@ -36,106 +36,105 @@ #include <vector> namespace mongo { +/** + * This is a helper class for managing a replica set consisting of + * MockRemoteDBServer instances. + * + * Note: Be sure to call ScopedDbConnection::clearPool() after every test + * when doing tests that involves the ReplicaSetMonitor. This is because + * it uses ScopedDbConnection which means you can have a residue connections + * that was created from previous tests and can cause a seg fault if the + * MockRemoteDBServer instances were already destroyed. + * + * Warning: Not thread-safe + */ +class MockReplicaSet { +public: + /** + * Creates a mock replica set and automatically mocks the isMaster + * and replSetGetStatus commands based on the default replica set + * configuration. + * + * @param setName The name for this replica set + * @param nodes The initial number of nodes for this replica set + */ + MockReplicaSet(const std::string& setName, size_t nodes); + ~MockReplicaSet(); + + // + // getters + // + + std::string getSetName() const; + std::string getConnectionString() const; + std::vector<HostAndPort> getHosts() const; + repl::ReplicaSetConfig getReplConfig() const; + std::string getPrimary() const; + std::vector<std::string> getSecondaries() const; + + /** + * Sets the configuration for this replica sets. This also has a side effect + * of mocking the ismaster and replSetGetStatus command responses based on + * the new config. + * + * Note: does not automatically select a new primary. Can be done manually by + * calling setPrimary. + */ + void setConfig(const repl::ReplicaSetConfig& newConfig); + + void setPrimary(const std::string& hostAndPort); + + /** + * @return pointer to the mocked remote server with the given hostName. + * NULL if host doesn't exists. + */ + MockRemoteDBServer* getNode(const std::string& hostAndPort); + + /** + * Kills a node belonging to this set. + * + * @param hostName the name of the replica node to kill. + */ + void kill(const std::string& hostAndPort); + /** - * This is a helper class for managing a replica set consisting of - * MockRemoteDBServer instances. + * Kills a set of host belonging to this set. * - * Note: Be sure to call ScopedDbConnection::clearPool() after every test - * when doing tests that involves the ReplicaSetMonitor. This is because - * it uses ScopedDbConnection which means you can have a residue connections - * that was created from previous tests and can cause a seg fault if the - * MockRemoteDBServer instances were already destroyed. + * @param hostList the list of host names of the servers to kill. + */ + void kill(const std::vector<std::string>& hostList); + + /** + * Reboots a node. * - * Warning: Not thread-safe + * @param hostName the name of the host to reboot. + */ + void restore(const std::string& hostName); + +private: + typedef std::map<std::string, MockRemoteDBServer*> ReplNodeMap; + + /** + * Mocks the ismaster command based on the information on the current + * replica set configuration. */ - class MockReplicaSet { - public: - - /** - * Creates a mock replica set and automatically mocks the isMaster - * and replSetGetStatus commands based on the default replica set - * configuration. - * - * @param setName The name for this replica set - * @param nodes The initial number of nodes for this replica set - */ - MockReplicaSet(const std::string& setName, size_t nodes); - ~MockReplicaSet(); - - // - // getters - // - - std::string getSetName() const; - std::string getConnectionString() const; - std::vector<HostAndPort> getHosts() const; - repl::ReplicaSetConfig getReplConfig() const; - std::string getPrimary() const; - std::vector<std::string> getSecondaries() const; - - /** - * Sets the configuration for this replica sets. This also has a side effect - * of mocking the ismaster and replSetGetStatus command responses based on - * the new config. - * - * Note: does not automatically select a new primary. Can be done manually by - * calling setPrimary. - */ - void setConfig(const repl::ReplicaSetConfig& newConfig); - - void setPrimary(const std::string& hostAndPort); - - /** - * @return pointer to the mocked remote server with the given hostName. - * NULL if host doesn't exists. - */ - MockRemoteDBServer* getNode(const std::string& hostAndPort); - - /** - * Kills a node belonging to this set. - * - * @param hostName the name of the replica node to kill. - */ - void kill(const std::string& hostAndPort); - - /** - * Kills a set of host belonging to this set. - * - * @param hostList the list of host names of the servers to kill. - */ - void kill(const std::vector<std::string>& hostList); - - /** - * Reboots a node. - * - * @param hostName the name of the host to reboot. - */ - void restore(const std::string& hostName); - - private: - typedef std::map<std::string, MockRemoteDBServer*> ReplNodeMap; - - /** - * Mocks the ismaster command based on the information on the current - * replica set configuration. - */ - void mockIsMasterCmd(); - - /** - * Mocks the replSetGetStatus command based on the current states of the - * mocked servers. - */ - void mockReplSetGetStatusCmd(); - - /** - * @return the replica set state of the given host - */ - int getState(const std::string& hostAndPort) const; - - const std::string _setName; - ReplNodeMap _nodeMap; - repl::ReplicaSetConfig _replConfig; - - std::string _primaryHost; - }; + void mockIsMasterCmd(); + + /** + * Mocks the replSetGetStatus command based on the current states of the + * mocked servers. + */ + void mockReplSetGetStatusCmd(); + + /** + * @return the replica set state of the given host + */ + int getState(const std::string& hostAndPort) const; + + const std::string _setName; + ReplNodeMap _nodeMap; + repl::ReplicaSetConfig _replConfig; + + std::string _primaryHost; +}; } |