replset.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. "use strict"
  2. var inherits = require('util').inherits,
  3. f = require('util').format,
  4. EventEmitter = require('events').EventEmitter,
  5. ReadPreference = require('./read_preference'),
  6. BasicCursor = require('../cursor'),
  7. retrieveBSON = require('../connection/utils').retrieveBSON,
  8. Logger = require('../connection/logger'),
  9. MongoError = require('../error'),
  10. Server = require('./server'),
  11. ReplSetState = require('./replset_state'),
  12. assign = require('./shared').assign,
  13. clone = require('./shared').clone,
  14. createClientInfo = require('./shared').createClientInfo;
  15. var MongoCR = require('../auth/mongocr')
  16. , X509 = require('../auth/x509')
  17. , Plain = require('../auth/plain')
  18. , GSSAPI = require('../auth/gssapi')
  19. , SSPI = require('../auth/sspi')
  20. , ScramSHA1 = require('../auth/scram');
  21. var BSON = retrieveBSON();
  22. //
  23. // States
  24. var DISCONNECTED = 'disconnected';
  25. var CONNECTING = 'connecting';
  26. var CONNECTED = 'connected';
  27. var DESTROYED = 'destroyed';
  28. function stateTransition(self, newState) {
  29. var legalTransitions = {
  30. 'disconnected': [CONNECTING, DESTROYED, DISCONNECTED],
  31. 'connecting': [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED],
  32. 'connected': [CONNECTED, DISCONNECTED, DESTROYED],
  33. 'destroyed': [DESTROYED]
  34. }
  35. // Get current state
  36. var legalStates = legalTransitions[self.state];
  37. if(legalStates && legalStates.indexOf(newState) != -1) {
  38. self.state = newState;
  39. } else {
  40. self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]'
  41. , self.id, self.state, newState, legalStates));
  42. }
  43. }
  44. //
  45. // ReplSet instance id
  46. var id = 1;
  47. var handlers = ['connect', 'close', 'error', 'timeout', 'parseError'];
  48. /**
  49. * Creates a new Replset instance
  50. * @class
  51. * @param {array} seedlist A list of seeds for the replicaset
  52. * @param {boolean} options.setName The Replicaset set name
  53. * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset
  54. * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
  55. * @param {boolean} [options.emitError=false] Server will emit errors events
  56. * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors
  57. * @param {number} [options.size=5] Server connection pool size
  58. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
  59. * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled
  60. * @param {boolean} [options.noDelay=true] TCP Connection no delay
  61. * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting
  62. * @param {number} [options.socketTimeout=0] TCP Socket timeout setting
  63. * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed
  64. * @param {boolean} [options.ssl=false] Use SSL for connection
  65. * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.
  66. * @param {Buffer} [options.ca] SSL Certificate store binary buffer
  67. * @param {Buffer} [options.cert] SSL Certificate binary buffer
  68. * @param {Buffer} [options.key] SSL Key file binary buffer
  69. * @param {string} [options.passphrase] SSL Certificate pass phrase
  70. * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.
  71. * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates
  72. * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits
  73. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  74. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  75. * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers
  76. * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection
  77. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
  78. * @return {ReplSet} A cursor instance
  79. * @fires ReplSet#connect
  80. * @fires ReplSet#ha
  81. * @fires ReplSet#joined
  82. * @fires ReplSet#left
  83. * @fires ReplSet#failed
  84. * @fires ReplSet#fullsetup
  85. * @fires ReplSet#all
  86. * @fires ReplSet#error
  87. * @fires ReplSet#serverHeartbeatStarted
  88. * @fires ReplSet#serverHeartbeatSucceeded
  89. * @fires ReplSet#serverHeartbeatFailed
  90. * @fires ReplSet#topologyOpening
  91. * @fires ReplSet#topologyClosed
  92. * @fires ReplSet#topologyDescriptionChanged
  93. * @property {string} type the topology type.
  94. * @property {string} parserType the parser type used (c++ or js).
  95. */
  96. var ReplSet = function(seedlist, options) {
  97. var self = this;
  98. options = options || {};
  99. // Validate seedlist
  100. if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array");
  101. // Validate list
  102. if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry");
  103. // Validate entries
  104. seedlist.forEach(function(e) {
  105. if(typeof e.host != 'string' || typeof e.port != 'number')
  106. throw new MongoError("seedlist entry must contain a host and port");
  107. });
  108. // Add event listener
  109. EventEmitter.call(this);
  110. // Get replSet Id
  111. this.id = id++;
  112. // Get the localThresholdMS
  113. var localThresholdMS = options.localThresholdMS || 15;
  114. // Backward compatibility
  115. if(options.acceptableLatency) localThresholdMS = options.acceptableLatency;
  116. // Create a logger
  117. var logger = Logger('ReplSet', options);
  118. // Internal state
  119. this.s = {
  120. options: assign({}, options),
  121. // BSON instance
  122. bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128,
  123. BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey,
  124. BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]),
  125. // Factory overrides
  126. Cursor: options.cursorFactory || BasicCursor,
  127. // Logger instance
  128. logger: logger,
  129. // Seedlist
  130. seedlist: seedlist,
  131. // Replicaset state
  132. replicaSetState: new ReplSetState({
  133. id: this.id, setName: options.setName,
  134. acceptableLatency: localThresholdMS,
  135. heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000,
  136. logger: logger
  137. }),
  138. // Current servers we are connecting to
  139. connectingServers: [],
  140. // Ha interval
  141. haInterval: options.haInterval ? options.haInterval : 10000,
  142. // Minimum heartbeat frequency used if we detect a server close
  143. minHeartbeatFrequencyMS: 500,
  144. // Disconnect handler
  145. disconnectHandler: options.disconnectHandler,
  146. // Server selection index
  147. index: 0,
  148. // Connect function options passed in
  149. connectOptions: {},
  150. // Are we running in debug mode
  151. debug: typeof options.debug == 'boolean' ? options.debug : false,
  152. // Client info
  153. clientInfo: createClientInfo(options)
  154. }
  155. // Add handler for topology change
  156. this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { self.emit('topologyDescriptionChanged', r); });
  157. // Log info warning if the socketTimeout < haInterval as it will cause
  158. // a lot of recycled connections to happen.
  159. if(this.s.logger.isWarn()
  160. && this.s.options.socketTimeout != 0
  161. && this.s.options.socketTimeout < this.s.haInterval) {
  162. this.s.logger.warn(f('warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts'
  163. , this.s.options.socketTimeout, this.s.haInterval));
  164. }
  165. // All the authProviders
  166. this.authProviders = options.authProviders || {
  167. 'mongocr': new MongoCR(this.s.bson), 'x509': new X509(this.s.bson)
  168. , 'plain': new Plain(this.s.bson), 'gssapi': new GSSAPI(this.s.bson)
  169. , 'sspi': new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson)
  170. }
  171. // Add forwarding of events from state handler
  172. var types = ['joined', 'left'];
  173. types.forEach(function(x) {
  174. self.s.replicaSetState.on(x, function(t, s) {
  175. if(self.state === CONNECTED && x === 'joined' && t == 'primary') {
  176. self.emit('reconnect', self);
  177. }
  178. self.emit(x, t, s);
  179. });
  180. });
  181. // Connect stat
  182. this.initialConnectState = {
  183. connect: false, fullsetup: false, all: false
  184. }
  185. // Disconnected state
  186. this.state = DISCONNECTED;
  187. this.haTimeoutId = null;
  188. // Are we authenticating
  189. this.authenticating = false;
  190. // Last ismaster
  191. this.ismaster = null;
  192. }
  193. inherits(ReplSet, EventEmitter);
  194. Object.defineProperty(ReplSet.prototype, 'type', {
  195. enumerable:true, get: function() { return 'replset'; }
  196. });
  197. Object.defineProperty(ReplSet.prototype, 'parserType', {
  198. enumerable:true, get: function() {
  199. return BSON.native ? "c++" : "js";
  200. }
  201. });
  202. function attemptReconnect(self) {
  203. if(self.runningAttempReconnect) return;
  204. // Set as running
  205. self.runningAttempReconnect = true;
  206. // Wait before execute
  207. self.haTimeoutId = setTimeout(function() {
  208. if(self.state == DESTROYED) return;
  209. // Debug log
  210. if(self.s.logger.isDebug()) {
  211. self.s.logger.debug(f('attemptReconnect for replset with id %s', self.id));
  212. }
  213. // Get all known hosts
  214. var keys = Object.keys(self.s.replicaSetState.set);
  215. var servers = keys.map(function(x) {
  216. return new Server(assign({}, self.s.options, {
  217. host: x.split(':')[0], port: parseInt(x.split(':')[1], 10)
  218. }, {
  219. authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true
  220. }, {
  221. clientInfo: clone(self.s.clientInfo)
  222. }));
  223. });
  224. // Create the list of servers
  225. self.s.connectingServers = servers.slice(0);
  226. // Handle all events coming from servers
  227. function _handleEvent(self, event) {
  228. return function() {
  229. // Destroy the instance
  230. if(self.state == DESTROYED) {
  231. return this.destroy();
  232. }
  233. // Debug log
  234. if(self.s.logger.isDebug()) {
  235. self.s.logger.debug(f('attemptReconnect for replset with id %s using server %s ended with event %s', self.id, this.name, event));
  236. }
  237. // Check if we are done
  238. function done() {
  239. // Done with the reconnection attempt
  240. if(self.s.connectingServers.length == 0) {
  241. if(self.state == DESTROYED) return;
  242. // If we have a primary and a disconnect handler, execute
  243. // buffered operations
  244. if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) {
  245. self.s.disconnectHandler.execute();
  246. } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) {
  247. self.s.disconnectHandler.execute({ executePrimary:true });
  248. } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) {
  249. self.s.disconnectHandler.execute({ executeSecondary:true });
  250. }
  251. // Do we have a primary
  252. if(self.s.replicaSetState.hasPrimary()) {
  253. // Emit reconnect as new primary was discovered
  254. self.emit('reconnect', self);
  255. // Connect any missing servers
  256. connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
  257. // Debug log
  258. if(self.s.logger.isDebug()) {
  259. self.s.logger.debug(f('attemptReconnect for replset with id successful resuming topologyMonitor', self.id));
  260. }
  261. // Reset the running
  262. self.runningAttempReconnect = false;
  263. // Go back to normal topology monitoring
  264. // Schedule a topology monitoring sweep
  265. setTimeout(function() {
  266. topologyMonitor(self);
  267. }, self.s.haInterval);
  268. });
  269. } else {
  270. if(self.listeners("close").length > 0) {
  271. self.emit('close', self);
  272. }
  273. // Reset the running
  274. self.runningAttempReconnect = false;
  275. // Attempt a new reconnect
  276. attemptReconnect(self);
  277. }
  278. }
  279. }
  280. // Remove the server from our list
  281. for(var i = 0; i < self.s.connectingServers.length; i++) {
  282. if(self.s.connectingServers[i].equals(this)) {
  283. self.s.connectingServers.splice(i, 1);
  284. }
  285. }
  286. // Keep reference to server
  287. var _self = this;
  288. // Debug log
  289. if(self.s.logger.isDebug()) {
  290. self.s.logger.debug(f('attemptReconnect in replset with id %s for', self.id));
  291. }
  292. // Connect and not authenticating
  293. if(event == 'connect' && !self.authenticating) {
  294. if(self.state == DESTROYED) {
  295. return _self.destroy();
  296. }
  297. // Update the replicaset state
  298. if(self.s.replicaSetState.update(_self)) {
  299. // Primary lastIsMaster store it
  300. if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) {
  301. self.ismaster = _self.lastIsMaster();
  302. }
  303. // Remove the handlers
  304. for(i = 0; i < handlers.length; i++) {
  305. _self.removeAllListeners(handlers[i]);
  306. }
  307. // Add stable state handlers
  308. _self.on('error', handleEvent(self, 'error'));
  309. _self.on('close', handleEvent(self, 'close'));
  310. _self.on('timeout', handleEvent(self, 'timeout'));
  311. _self.on('parseError', handleEvent(self, 'parseError'));
  312. } else {
  313. _self.destroy();
  314. }
  315. } else if(event == 'connect' && self.authenticating) {
  316. this.destroy();
  317. }
  318. done();
  319. }
  320. }
  321. // Index used to interleaf the server connects, avoiding
  322. // runtime issues on io constrained vm's
  323. var timeoutInterval = 0;
  324. function connect(server, timeoutInterval) {
  325. setTimeout(function() {
  326. server.once('connect', _handleEvent(self, 'connect'));
  327. server.once('close', _handleEvent(self, 'close'));
  328. server.once('timeout', _handleEvent(self, 'timeout'));
  329. server.once('error', _handleEvent(self, 'error'));
  330. server.once('parseError', _handleEvent(self, 'parseError'));
  331. // SDAM Monitoring events
  332. server.on('serverOpening', function(e) { self.emit('serverOpening', e); });
  333. server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); });
  334. server.on('serverClosed', function(e) { self.emit('serverClosed', e); });
  335. server.connect(self.s.connectOptions);
  336. }, timeoutInterval);
  337. }
  338. // Connect all servers
  339. while(servers.length > 0) {
  340. connect(servers.shift(), timeoutInterval++);
  341. }
  342. }, self.s.minHeartbeatFrequencyMS);
  343. }
  344. function connectNewServers(self, servers, callback) {
  345. // Count lefts
  346. var count = servers.length;
  347. // Handle events
  348. var _handleEvent = function(self, event) {
  349. return function() {
  350. var _self = this;
  351. count = count - 1;
  352. // Destroyed
  353. if(self.state == DESTROYED) {
  354. return this.destroy();
  355. }
  356. if(event == 'connect' && !self.authenticating) {
  357. // Destroyed
  358. if(self.state == DESTROYED) {
  359. return _self.destroy();
  360. }
  361. var result = self.s.replicaSetState.update(_self);
  362. // Update the state with the new server
  363. if(result) {
  364. // Primary lastIsMaster store it
  365. if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) {
  366. self.ismaster = _self.lastIsMaster();
  367. }
  368. // Remove the handlers
  369. for(var i = 0; i < handlers.length; i++) {
  370. _self.removeAllListeners(handlers[i]);
  371. }
  372. // Add stable state handlers
  373. _self.on('error', handleEvent(self, 'error'));
  374. _self.on('close', handleEvent(self, 'close'));
  375. _self.on('timeout', handleEvent(self, 'timeout'));
  376. _self.on('parseError', handleEvent(self, 'parseError'));
  377. } else {
  378. _self.destroy();
  379. }
  380. } else if(event == 'connect' && self.authenticating) {
  381. this.destroy();
  382. }
  383. // Are we done finish up callback
  384. if(count == 0) { callback(); }
  385. }
  386. }
  387. // No new servers
  388. if(count == 0) return callback();
  389. // Execute method
  390. function execute(_server, i) {
  391. setTimeout(function() {
  392. // Destroyed
  393. if(self.state == DESTROYED) {
  394. return;
  395. }
  396. // Create a new server instance
  397. var server = new Server(assign({}, self.s.options, {
  398. host: _server.split(':')[0],
  399. port: parseInt(_server.split(':')[1], 10)
  400. }, {
  401. authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true
  402. }, {
  403. clientInfo: clone(self.s.clientInfo)
  404. }));
  405. // Add temp handlers
  406. server.once('connect', _handleEvent(self, 'connect'));
  407. server.once('close', _handleEvent(self, 'close'));
  408. server.once('timeout', _handleEvent(self, 'timeout'));
  409. server.once('error', _handleEvent(self, 'error'));
  410. server.once('parseError', _handleEvent(self, 'parseError'));
  411. // SDAM Monitoring events
  412. server.on('serverOpening', function(e) { self.emit('serverOpening', e); });
  413. server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); });
  414. server.on('serverClosed', function(e) { self.emit('serverClosed', e); });
  415. server.connect(self.s.connectOptions);
  416. }, i);
  417. }
  418. // Create new instances
  419. for(var i = 0; i < servers.length; i++) {
  420. execute(servers[i], i);
  421. }
  422. }
  423. function topologyMonitor(self, options) {
  424. options = options || {};
  425. // Set momitoring timeout
  426. self.haTimeoutId = setTimeout(function() {
  427. if(self.state == DESTROYED) return;
  428. // Is this a on connect topology discovery
  429. // Schedule a proper topology monitoring to happen
  430. // To ensure any discovered servers do not timeout
  431. // while waiting for the initial discovery to happen.
  432. if(options.haInterval) {
  433. topologyMonitor(self);
  434. }
  435. // If we have a primary and a disconnect handler, execute
  436. // buffered operations
  437. if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) {
  438. self.s.disconnectHandler.execute();
  439. } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) {
  440. self.s.disconnectHandler.execute({ executePrimary:true });
  441. } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) {
  442. self.s.disconnectHandler.execute({ executeSecondary:true });
  443. }
  444. // Get the connectingServers
  445. var connectingServers = self.s.replicaSetState.allServers();
  446. // Debug log
  447. if(self.s.logger.isDebug()) {
  448. self.s.logger.debug(f('topologyMonitor in replset with id %s connected servers [%s]'
  449. , self.id
  450. , connectingServers.map(function(x) {
  451. return x.name;
  452. })));
  453. }
  454. // Get the count
  455. var count = connectingServers.length;
  456. // If we have no servers connected
  457. if(count == 0 && !options.haInterval) {
  458. if(self.listeners("close").length > 0) {
  459. self.emit('close', self);
  460. }
  461. return attemptReconnect(self);
  462. }
  463. // If the count is zero schedule a new fast
  464. function pingServer(_self, _server, cb) {
  465. // Measure running time
  466. var start = new Date().getTime();
  467. // Emit the server heartbeat start
  468. emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name });
  469. // Execute ismaster
  470. // Set the socketTimeout for a monitoring message to a low number
  471. // Ensuring ismaster calls are timed out quickly
  472. _server.command('admin.$cmd', {
  473. ismaster:true
  474. }, {
  475. monitoring: true,
  476. socketTimeout: self.s.options.connectionTimeout || 2000,
  477. }, function(err, r) {
  478. if(self.state == DESTROYED) {
  479. _server.destroy();
  480. return cb(err, r);
  481. }
  482. // Calculate latency
  483. var latencyMS = new Date().getTime() - start;
  484. // Set the last updatedTime
  485. var hrTime = process.hrtime();
  486. // Calculate the last update time
  487. _server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1]/1000);
  488. // We had an error, remove it from the state
  489. if(err) {
  490. // Emit the server heartbeat failure
  491. emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name });
  492. // Remove server from the state
  493. _self.s.replicaSetState.remove(_server);
  494. } else {
  495. // Update the server ismaster
  496. _server.ismaster = r.result;
  497. // Check if we have a lastWriteDate convert it to MS
  498. // and store on the server instance for later use
  499. if(_server.ismaster.lastWrite && _server.ismaster.lastWrite.lastWriteDate) {
  500. _server.lastWriteDate = _server.ismaster.lastWrite.lastWriteDate.getTime();
  501. }
  502. // Do we have a brand new server
  503. if(_server.lastIsMasterMS == -1) {
  504. _server.lastIsMasterMS = latencyMS;
  505. } else if(_server.lastIsMasterMS) {
  506. // After the first measurement, average RTT MUST be computed using an
  507. // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2.
  508. // If the prior average is denoted old_rtt, then the new average (new_rtt) is
  509. // computed from a new RTT measurement (x) using the following formula:
  510. // alpha = 0.2
  511. // new_rtt = alpha * x + (1 - alpha) * old_rtt
  512. _server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * _server.lastIsMasterMS;
  513. }
  514. if(_self.s.replicaSetState.update(_server)) {
  515. // Primary lastIsMaster store it
  516. if(_server.lastIsMaster() && _server.lastIsMaster().ismaster) {
  517. self.ismaster = _server.lastIsMaster();
  518. }
  519. }
  520. // Server heart beat event
  521. emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name });
  522. }
  523. // Calculate the stalness for this server
  524. self.s.replicaSetState.updateServerMaxStaleness(_server, self.s.haInterval);
  525. // Callback
  526. cb(err, r);
  527. });
  528. }
  529. // Connect any missing servers
  530. function connectMissingServers() {
  531. if(self.state == DESTROYED) return;
  532. // Attempt to connect to any unknown servers
  533. connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
  534. if(self.state == DESTROYED) return;
  535. // Check if we have an options.haInterval (meaning it was triggered from connect)
  536. if(options.haInterval) {
  537. // Do we have a primary and secondary
  538. if(self.state == CONNECTING
  539. && self.s.replicaSetState.hasPrimaryAndSecondary()) {
  540. // Transition to connected
  541. stateTransition(self, CONNECTED);
  542. // Update initial state
  543. self.initialConnectState.connect = true;
  544. self.initialConnectState.fullsetup = true;
  545. self.initialConnectState.all = true;
  546. // Emit fullsetup and all events
  547. process.nextTick(function() {
  548. self.emit('connect', self);
  549. self.emit('fullsetup', self);
  550. self.emit('all', self);
  551. });
  552. } else if(self.state == CONNECTING
  553. && self.s.replicaSetState.hasPrimary()) {
  554. // Transition to connected
  555. stateTransition(self, CONNECTED);
  556. // Update initial state
  557. self.initialConnectState.connect = true;
  558. // Emit connected sign
  559. process.nextTick(function() {
  560. self.emit('connect', self);
  561. });
  562. } else if(self.state == CONNECTING
  563. && self.s.replicaSetState.hasSecondary()
  564. && self.s.options.secondaryOnlyConnectionAllowed) {
  565. // Transition to connected
  566. stateTransition(self, CONNECTED);
  567. // Update initial state
  568. self.initialConnectState.connect = true;
  569. // Emit connected sign
  570. process.nextTick(function() {
  571. self.emit('connect', self);
  572. });
  573. } else if(self.state == CONNECTING) {
  574. self.emit('error', new MongoError('no primary found in replicaset'));
  575. // Destroy the topology
  576. return self.destroy();
  577. } else if(self.state == CONNECTED
  578. && self.s.replicaSetState.hasPrimaryAndSecondary()
  579. && !self.initialConnectState.fullsetup) {
  580. self.initialConnectState.fullsetup = true;
  581. // Emit fullsetup and all events
  582. process.nextTick(function() {
  583. self.emit('fullsetup', self);
  584. self.emit('all', self);
  585. });
  586. }
  587. }
  588. if(!options.haInterval) topologyMonitor(self);
  589. });
  590. }
  591. // No connectingServers but unknown servers
  592. if(connectingServers.length == 0
  593. && self.s.replicaSetState.unknownServers.length > 0 && options.haInterval) {
  594. return connectMissingServers();
  595. } else if(connectingServers.length == 0 && options.haInterval) {
  596. self.destroy();
  597. return self.emit('error', new MongoError('no valid replicaset members found'));
  598. }
  599. // Ping all servers
  600. for(var i = 0; i < connectingServers.length; i++) {
  601. pingServer(self, connectingServers[i], function() {
  602. count = count - 1;
  603. if(count == 0) {
  604. connectMissingServers();
  605. }
  606. });
  607. }
  608. }, options.haInterval || self.s.haInterval)
  609. }
  610. function handleEvent(self, event) {
  611. return function() {
  612. if(self.state == DESTROYED) return;
  613. // Debug log
  614. if(self.s.logger.isDebug()) {
  615. self.s.logger.debug(f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id));
  616. }
  617. self.s.replicaSetState.remove(this);
  618. }
  619. }
  620. function handleInitialConnectEvent(self, event) {
  621. return function() {
  622. // Debug log
  623. if(self.s.logger.isDebug()) {
  624. self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s', event, this.name, self.id));
  625. }
  626. // Destroy the instance
  627. if(self.state == DESTROYED) {
  628. return this.destroy();
  629. }
  630. // Check the type of server
  631. if(event == 'connect') {
  632. // Update the state
  633. var result = self.s.replicaSetState.update(this);
  634. if(result == true) {
  635. // Primary lastIsMaster store it
  636. if(this.lastIsMaster() && this.lastIsMaster().ismaster) {
  637. self.ismaster = this.lastIsMaster();
  638. }
  639. // Debug log
  640. if(self.s.logger.isDebug()) {
  641. self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', event, this.name, self.id, JSON.stringify(self.s.replicaSetState.set)));
  642. }
  643. // Remove the handlers
  644. for(var i = 0; i < handlers.length; i++) {
  645. this.removeAllListeners(handlers[i]);
  646. }
  647. // Add stable state handlers
  648. this.on('error', handleEvent(self, 'error'));
  649. this.on('close', handleEvent(self, 'close'));
  650. this.on('timeout', handleEvent(self, 'timeout'));
  651. this.on('parseError', handleEvent(self, 'parseError'));
  652. } else if(result instanceof MongoError) {
  653. this.destroy();
  654. self.destroy();
  655. return self.emit('error', result);
  656. } else {
  657. this.destroy();
  658. }
  659. } else {
  660. // Emit failure to connect
  661. self.emit('failed', this);
  662. // Remove from the state
  663. self.s.replicaSetState.remove(this);
  664. }
  665. // Remove from the list from connectingServers
  666. for(i = 0; i < self.s.connectingServers.length; i++) {
  667. if(self.s.connectingServers[i].equals(this)) {
  668. self.s.connectingServers.splice(i, 1);
  669. }
  670. }
  671. // Trigger topologyMonitor
  672. if(self.s.connectingServers.length == 0) {
  673. topologyMonitor(self, {haInterval: 1});
  674. }
  675. };
  676. }
  677. function connectServers(self, servers) {
  678. // Update connectingServers
  679. self.s.connectingServers = self.s.connectingServers.concat(servers);
  680. // Index used to interleaf the server connects, avoiding
  681. // runtime issues on io constrained vm's
  682. var timeoutInterval = 0;
  683. function connect(server, timeoutInterval) {
  684. setTimeout(function() {
  685. // Add the server to the state
  686. if(self.s.replicaSetState.update(server)) {
  687. // Primary lastIsMaster store it
  688. if(server.lastIsMaster() && server.lastIsMaster().ismaster) {
  689. self.ismaster = server.lastIsMaster();
  690. }
  691. }
  692. // Add event handlers
  693. server.once('close', handleInitialConnectEvent(self, 'close'));
  694. server.once('timeout', handleInitialConnectEvent(self, 'timeout'));
  695. server.once('parseError', handleInitialConnectEvent(self, 'parseError'));
  696. server.once('error', handleInitialConnectEvent(self, 'error'));
  697. server.once('connect', handleInitialConnectEvent(self, 'connect'));
  698. // SDAM Monitoring events
  699. server.on('serverOpening', function(e) { self.emit('serverOpening', e); });
  700. server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); });
  701. server.on('serverClosed', function(e) { self.emit('serverClosed', e); });
  702. // Start connection
  703. server.connect(self.s.connectOptions);
  704. }, timeoutInterval);
  705. }
  706. // Start all the servers
  707. while(servers.length > 0) {
  708. connect(servers.shift(), timeoutInterval++);
  709. }
  710. }
  711. /**
  712. * Emit event if it exists
  713. * @method
  714. */
  715. function emitSDAMEvent(self, event, description) {
  716. if(self.listeners(event).length > 0) {
  717. self.emit(event, description);
  718. }
  719. }
  720. /**
  721. * Initiate server connect
  722. * @method
  723. * @param {array} [options.auth=null] Array of auth options to apply on connect
  724. */
  725. ReplSet.prototype.connect = function(options) {
  726. var self = this;
  727. // Add any connect level options to the internal state
  728. this.s.connectOptions = options || {};
  729. // Set connecting state
  730. stateTransition(this, CONNECTING);
  731. // Create server instances
  732. var servers = this.s.seedlist.map(function(x) {
  733. return new Server(assign({}, self.s.options, x, {
  734. authProviders: self.authProviders, reconnect:false, monitoring:false, inTopology: true
  735. }, {
  736. clientInfo: clone(self.s.clientInfo)
  737. }));
  738. });
  739. // Error out as high availbility interval must be < than socketTimeout
  740. if(this.s.options.socketTimeout > 0 && this.s.options.socketTimeout <= this.s.options.haInterval) {
  741. return self.emit('error', new MongoError(f("haInterval [%s] MS must be set to less than socketTimeout [%s] MS"
  742. , this.s.options.haInterval, this.s.options.socketTimeout)));
  743. }
  744. // Emit the topology opening event
  745. emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id });
  746. // Start all server connections
  747. connectServers(self, servers);
  748. }
  749. /**
  750. * Destroy the server connection
  751. * @param {boolean} [options.force=false] Force destroy the pool
  752. * @method
  753. */
  754. ReplSet.prototype.destroy = function(options) {
  755. options = options || {};
  756. // Transition state
  757. stateTransition(this, DESTROYED);
  758. // Clear out any monitoring process
  759. if(this.haTimeoutId) clearTimeout(this.haTimeoutId);
  760. // Destroy the replicaset
  761. this.s.replicaSetState.destroy(options);
  762. // Destroy all connecting servers
  763. this.s.connectingServers.forEach(function(x) {
  764. x.destroy(options);
  765. });
  766. // Emit toplogy closing event
  767. emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id });
  768. }
  769. /**
  770. * Unref all connections belong to this server
  771. * @method
  772. */
  773. ReplSet.prototype.unref = function() {
  774. // Transition state
  775. stateTransition(this, DISCONNECTED);
  776. this.s.replicaSetState.allServers().forEach(function(x) {
  777. x.unref();
  778. });
  779. clearTimeout(this.haTimeoutId);
  780. }
  781. /**
  782. * Returns the last known ismaster document for this server
  783. * @method
  784. * @return {object}
  785. */
  786. ReplSet.prototype.lastIsMaster = function() {
  787. return this.s.replicaSetState.primary
  788. ? this.s.replicaSetState.primary.lastIsMaster() : this.ismaster;
  789. }
  790. /**
  791. * All raw connections
  792. * @method
  793. * @return {Connection[]}
  794. */
  795. ReplSet.prototype.connections = function() {
  796. var servers = this.s.replicaSetState.allServers();
  797. var connections = [];
  798. for(var i = 0; i < servers.length; i++) {
  799. connections = connections.concat(servers[i].connections());
  800. }
  801. return connections;
  802. }
  803. /**
  804. * Figure out if the server is connected
  805. * @method
  806. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  807. * @return {boolean}
  808. */
  809. ReplSet.prototype.isConnected = function(options) {
  810. options = options || {};
  811. // If we are authenticating signal not connected
  812. // To avoid interleaving of operations
  813. if(this.authenticating) return false;
  814. // If we specified a read preference check if we are connected to something
  815. // than can satisfy this
  816. if(options.readPreference
  817. && options.readPreference.equals(ReadPreference.secondary)) {
  818. return this.s.replicaSetState.hasSecondary();
  819. }
  820. if(options.readPreference
  821. && options.readPreference.equals(ReadPreference.primary)) {
  822. return this.s.replicaSetState.hasPrimary();
  823. }
  824. if(options.readPreference
  825. && options.readPreference.equals(ReadPreference.primaryPreferred)) {
  826. return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary();
  827. }
  828. if(options.readPreference
  829. && options.readPreference.equals(ReadPreference.secondaryPreferred)) {
  830. return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary();
  831. }
  832. if(this.s.secondaryOnlyConnectionAllowed
  833. && this.s.replicaSetState.hasSecondary()) {
  834. return true;
  835. }
  836. return this.s.replicaSetState.hasPrimary();
  837. }
  838. /**
  839. * Figure out if the replicaset instance was destroyed by calling destroy
  840. * @method
  841. * @return {boolean}
  842. */
  843. ReplSet.prototype.isDestroyed = function() {
  844. return this.state == DESTROYED;
  845. }
  846. /**
  847. * Get server
  848. * @method
  849. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  850. * @return {Server}
  851. */
  852. ReplSet.prototype.getServer = function(options) {
  853. // Ensure we have no options
  854. options = options || {};
  855. // Pick the right server baspickServerd on readPreference
  856. var server = this.s.replicaSetState.pickServer(options.readPreference);
  857. if(this.s.debug) this.emit('pickedServer', options.readPreference, server);
  858. return server;
  859. }
  860. /**
  861. * Get all connected servers
  862. * @method
  863. * @return {Server[]}
  864. */
  865. ReplSet.prototype.getServers = function() {
  866. return this.s.replicaSetState.allServers();
  867. }
  868. //
  869. // Execute write operation
  870. var executeWriteOperation = function(self, op, ns, ops, options, callback) {
  871. if(typeof options == 'function') callback = options, options = {}, options = options || {};
  872. // Ensure we have no options
  873. options = options || {};
  874. // No server returned we had an error
  875. if(self.s.replicaSetState.primary == null) {
  876. return callback(new MongoError("no primary server found"));
  877. }
  878. // Execute the command
  879. self.s.replicaSetState.primary[op](ns, ops, options, callback);
  880. }
  881. /**
  882. * Insert one or more documents
  883. * @method
  884. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  885. * @param {array} ops An array of documents to insert
  886. * @param {boolean} [options.ordered=true] Execute in order or out of order
  887. * @param {object} [options.writeConcern={}] Write concern for the operation
  888. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  889. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  890. * @param {opResultCallback} callback A callback function
  891. */
  892. ReplSet.prototype.insert = function(ns, ops, options, callback) {
  893. if(typeof options == 'function') callback = options, options = {}, options = options || {};
  894. if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
  895. // Not connected but we have a disconnecthandler
  896. if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
  897. return this.s.disconnectHandler.add('insert', ns, ops, options, callback);
  898. }
  899. // Execute write operation
  900. executeWriteOperation(this, 'insert', ns, ops, options, callback);
  901. }
  902. /**
  903. * Perform one or more update operations
  904. * @method
  905. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  906. * @param {array} ops An array of updates
  907. * @param {boolean} [options.ordered=true] Execute in order or out of order
  908. * @param {object} [options.writeConcern={}] Write concern for the operation
  909. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  910. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  911. * @param {opResultCallback} callback A callback function
  912. */
  913. ReplSet.prototype.update = function(ns, ops, options, callback) {
  914. if(typeof options == 'function') callback = options, options = {}, options = options || {};
  915. if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
  916. // Not connected but we have a disconnecthandler
  917. if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
  918. return this.s.disconnectHandler.add('update', ns, ops, options, callback);
  919. }
  920. // Execute write operation
  921. executeWriteOperation(this, 'update', ns, ops, options, callback);
  922. }
  923. /**
  924. * Perform one or more remove operations
  925. * @method
  926. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  927. * @param {array} ops An array of removes
  928. * @param {boolean} [options.ordered=true] Execute in order or out of order
  929. * @param {object} [options.writeConcern={}] Write concern for the operation
  930. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  931. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  932. * @param {opResultCallback} callback A callback function
  933. */
  934. ReplSet.prototype.remove = function(ns, ops, options, callback) {
  935. if(typeof options == 'function') callback = options, options = {}, options = options || {};
  936. if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
  937. // Not connected but we have a disconnecthandler
  938. if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
  939. return this.s.disconnectHandler.add('remove', ns, ops, options, callback);
  940. }
  941. // Execute write operation
  942. executeWriteOperation(this, 'remove', ns, ops, options, callback);
  943. }
  944. /**
  945. * Execute a command
  946. * @method
  947. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  948. * @param {object} cmd The command hash
  949. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  950. * @param {Connection} [options.connection] Specify connection object to execute command against
  951. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  952. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  953. * @param {opResultCallback} callback A callback function
  954. */
  955. ReplSet.prototype.command = function(ns, cmd, options, callback) {
  956. if(typeof options == 'function') callback = options, options = {}, options = options || {};
  957. if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
  958. var self = this;
  959. // Establish readPreference
  960. var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary;
  961. // If the readPreference is primary and we have no primary, store it
  962. if(readPreference.preference == 'primary' && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
  963. return this.s.disconnectHandler.add('command', ns, cmd, options, callback);
  964. } else if(readPreference.preference == 'secondary' && !this.s.replicaSetState.hasSecondary() && this.s.disconnectHandler != null) {
  965. return this.s.disconnectHandler.add('command', ns, cmd, options, callback);
  966. } else if(readPreference.preference != 'primary' && !this.s.replicaSetState.hasSecondary() && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
  967. return this.s.disconnectHandler.add('command', ns, cmd, options, callback);
  968. }
  969. // Pick a server
  970. var server = this.s.replicaSetState.pickServer(readPreference);
  971. // We received an error, return it
  972. if(!(server instanceof Server)) return callback(server);
  973. // Emit debug event
  974. if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server);
  975. // No server returned we had an error
  976. if(server == null) {
  977. return callback(new MongoError(f("no server found that matches the provided readPreference %s", readPreference)));
  978. }
  979. // Execute the command
  980. server.command(ns, cmd, options, callback);
  981. }
  982. /**
  983. * Authenticate using a specified mechanism
  984. * @method
  985. * @param {string} mechanism The Auth mechanism we are invoking
  986. * @param {string} db The db we are invoking the mechanism against
  987. * @param {...object} param Parameters for the specific mechanism
  988. * @param {authResultCallback} callback A callback function
  989. */
  990. ReplSet.prototype.auth = function(mechanism, db) {
  991. var allArgs = Array.prototype.slice.call(arguments, 0).slice(0);
  992. var self = this;
  993. var args = Array.prototype.slice.call(arguments, 2);
  994. var callback = args.pop();
  995. // If we don't have the mechanism fail
  996. if(this.authProviders[mechanism] == null && mechanism != 'default') {
  997. return callback(new MongoError(f("auth provider %s does not exist", mechanism)));
  998. }
  999. // Are we already authenticating, throw
  1000. if(this.authenticating) {
  1001. return callback(new MongoError('authentication or logout allready in process'));
  1002. }
  1003. // Topology is not connected, save the call in the provided store to be
  1004. // Executed at some point when the handler deems it's reconnected
  1005. if(!self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler != null) {
  1006. return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback);
  1007. }
  1008. // Set to authenticating
  1009. this.authenticating = true;
  1010. // All errors
  1011. var errors = [];
  1012. // Get all the servers
  1013. var servers = this.s.replicaSetState.allServers();
  1014. // No servers return
  1015. if(servers.length == 0) {
  1016. this.authenticating = false;
  1017. callback(null, true);
  1018. }
  1019. // Authenticate
  1020. function auth(server) {
  1021. // Arguments without a callback
  1022. var argsWithoutCallback = [mechanism, db].concat(args.slice(0));
  1023. // Create arguments
  1024. var finalArguments = argsWithoutCallback.concat([function(err) {
  1025. count = count - 1;
  1026. // Save all the errors
  1027. if(err) errors.push({name: server.name, err: err});
  1028. // We are done
  1029. if(count == 0) {
  1030. // Auth is done
  1031. self.authenticating = false;
  1032. // Return the auth error
  1033. if(errors.length) return callback(MongoError.create({
  1034. message: 'authentication fail', errors: errors
  1035. }), false);
  1036. // Successfully authenticated session
  1037. callback(null, self);
  1038. }
  1039. }]);
  1040. if(!server.lastIsMaster().arbiterOnly) {
  1041. // Execute the auth only against non arbiter servers
  1042. server.auth.apply(server, finalArguments);
  1043. } else {
  1044. // If we are authenticating against an arbiter just ignore it
  1045. finalArguments.pop()(null);
  1046. }
  1047. }
  1048. // Get total count
  1049. var count = servers.length;
  1050. // Authenticate against all servers
  1051. while(servers.length > 0) {
  1052. auth(servers.shift());
  1053. }
  1054. }
  1055. /**
  1056. * Logout from a database
  1057. * @method
  1058. * @param {string} db The db we are logging out from
  1059. * @param {authResultCallback} callback A callback function
  1060. */
  1061. ReplSet.prototype.logout = function(dbName, callback) {
  1062. var self = this;
  1063. // Are we authenticating or logging out, throw
  1064. if(this.authenticating) {
  1065. throw new MongoError('authentication or logout allready in process');
  1066. }
  1067. // Ensure no new members are processed while logging out
  1068. this.authenticating = true;
  1069. // Remove from all auth providers (avoid any reaplication of the auth details)
  1070. var providers = Object.keys(this.authProviders);
  1071. for(var i = 0; i < providers.length; i++) {
  1072. this.authProviders[providers[i]].logout(dbName);
  1073. }
  1074. // Now logout all the servers
  1075. var servers = this.s.replicaSetState.allServers();
  1076. var count = servers.length;
  1077. if(count == 0) return callback();
  1078. var errors = [];
  1079. function logoutServer(_server, cb) {
  1080. _server.logout(dbName, function(err) {
  1081. if(err) errors.push({name: _server.name, err: err});
  1082. cb();
  1083. });
  1084. }
  1085. // Execute logout on all server instances
  1086. for(i = 0; i < servers.length; i++) {
  1087. logoutServer(servers[i], function() {
  1088. count = count - 1;
  1089. if(count == 0) {
  1090. // Do not block new operations
  1091. self.authenticating = false;
  1092. // If we have one or more errors
  1093. if(errors.length) return callback(MongoError.create({
  1094. message: f('logout failed against db %s', dbName), errors: errors
  1095. }), false);
  1096. // No errors
  1097. callback();
  1098. }
  1099. })
  1100. }
  1101. }
  1102. /**
  1103. * Perform one or more remove operations
  1104. * @method
  1105. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  1106. * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId
  1107. * @param {object} [options.batchSize=0] Batchsize for the operation
  1108. * @param {array} [options.documents=[]] Initial documents list for cursor
  1109. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  1110. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  1111. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  1112. * @param {opResultCallback} callback A callback function
  1113. */
  1114. ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) {
  1115. cursorOptions = cursorOptions || {};
  1116. var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor;
  1117. return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options);
  1118. }
  1119. /**
  1120. * A replset connect event, used to verify that the connection is up and running
  1121. *
  1122. * @event ReplSet#connect
  1123. * @type {ReplSet}
  1124. */
  1125. /**
  1126. * A replset reconnect event, used to verify that the topology reconnected
  1127. *
  1128. * @event ReplSet#reconnect
  1129. * @type {ReplSet}
  1130. */
  1131. /**
  1132. * A replset fullsetup event, used to signal that all topology members have been contacted.
  1133. *
  1134. * @event ReplSet#fullsetup
  1135. * @type {ReplSet}
  1136. */
  1137. /**
  1138. * A replset all event, used to signal that all topology members have been contacted.
  1139. *
  1140. * @event ReplSet#all
  1141. * @type {ReplSet}
  1142. */
  1143. /**
  1144. * A replset failed event, used to signal that initial replset connection failed.
  1145. *
  1146. * @event ReplSet#failed
  1147. * @type {ReplSet}
  1148. */
  1149. /**
  1150. * A server member left the replicaset
  1151. *
  1152. * @event ReplSet#left
  1153. * @type {function}
  1154. * @param {string} type The type of member that left (primary|secondary|arbiter)
  1155. * @param {Server} server The server object that left
  1156. */
  1157. /**
  1158. * A server member joined the replicaset
  1159. *
  1160. * @event ReplSet#joined
  1161. * @type {function}
  1162. * @param {string} type The type of member that joined (primary|secondary|arbiter)
  1163. * @param {Server} server The server object that joined
  1164. */
  1165. /**
  1166. * A server opening SDAM monitoring event
  1167. *
  1168. * @event ReplSet#serverOpening
  1169. * @type {object}
  1170. */
  1171. /**
  1172. * A server closed SDAM monitoring event
  1173. *
  1174. * @event ReplSet#serverClosed
  1175. * @type {object}
  1176. */
  1177. /**
  1178. * A server description SDAM change monitoring event
  1179. *
  1180. * @event ReplSet#serverDescriptionChanged
  1181. * @type {object}
  1182. */
  1183. /**
  1184. * A topology open SDAM event
  1185. *
  1186. * @event ReplSet#topologyOpening
  1187. * @type {object}
  1188. */
  1189. /**
  1190. * A topology closed SDAM event
  1191. *
  1192. * @event ReplSet#topologyClosed
  1193. * @type {object}
  1194. */
  1195. /**
  1196. * A topology structure SDAM change event
  1197. *
  1198. * @event ReplSet#topologyDescriptionChanged
  1199. * @type {object}
  1200. */
  1201. /**
  1202. * A topology serverHeartbeatStarted SDAM event
  1203. *
  1204. * @event ReplSet#serverHeartbeatStarted
  1205. * @type {object}
  1206. */
  1207. /**
  1208. * A topology serverHeartbeatFailed SDAM event
  1209. *
  1210. * @event ReplSet#serverHeartbeatFailed
  1211. * @type {object}
  1212. */
  1213. /**
  1214. * A topology serverHeartbeatSucceeded SDAM change event
  1215. *
  1216. * @event ReplSet#serverHeartbeatSucceeded
  1217. * @type {object}
  1218. */
  1219. module.exports = ReplSet;