12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403 |
- "use strict"
- var inherits = require('util').inherits,
- f = require('util').format,
- EventEmitter = require('events').EventEmitter,
- ReadPreference = require('./read_preference'),
- BasicCursor = require('../cursor'),
- retrieveBSON = require('../connection/utils').retrieveBSON,
- Logger = require('../connection/logger'),
- MongoError = require('../error'),
- Server = require('./server'),
- ReplSetState = require('./replset_state'),
- assign = require('./shared').assign,
- clone = require('./shared').clone,
- createClientInfo = require('./shared').createClientInfo;
- var MongoCR = require('../auth/mongocr')
- , X509 = require('../auth/x509')
- , Plain = require('../auth/plain')
- , GSSAPI = require('../auth/gssapi')
- , SSPI = require('../auth/sspi')
- , ScramSHA1 = require('../auth/scram');
- var BSON = retrieveBSON();
- var DISCONNECTED = 'disconnected';
- var CONNECTING = 'connecting';
- var CONNECTED = 'connected';
- var DESTROYED = 'destroyed';
- function stateTransition(self, newState) {
- var legalTransitions = {
- 'disconnected': [CONNECTING, DESTROYED, DISCONNECTED],
- 'connecting': [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED],
- 'connected': [CONNECTED, DISCONNECTED, DESTROYED],
- 'destroyed': [DESTROYED]
- }
-
- var legalStates = legalTransitions[self.state];
- if(legalStates && legalStates.indexOf(newState) != -1) {
- self.state = newState;
- } else {
- self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]'
- , self.id, self.state, newState, legalStates));
- }
- }
- var id = 1;
- var handlers = ['connect', 'close', 'error', 'timeout', 'parseError'];
- var ReplSet = function(seedlist, options) {
- var self = this;
- options = options || {};
-
- if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array");
-
- if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry");
-
- seedlist.forEach(function(e) {
- if(typeof e.host != 'string' || typeof e.port != 'number')
- throw new MongoError("seedlist entry must contain a host and port");
- });
-
- EventEmitter.call(this);
-
- this.id = id++;
-
- var localThresholdMS = options.localThresholdMS || 15;
-
- if(options.acceptableLatency) localThresholdMS = options.acceptableLatency;
-
- var logger = Logger('ReplSet', options);
-
- this.s = {
- options: assign({}, options),
-
- bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128,
- BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey,
- BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]),
-
- Cursor: options.cursorFactory || BasicCursor,
-
- logger: logger,
-
- seedlist: seedlist,
-
- replicaSetState: new ReplSetState({
- id: this.id, setName: options.setName,
- acceptableLatency: localThresholdMS,
- heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000,
- logger: logger
- }),
-
- connectingServers: [],
-
- haInterval: options.haInterval ? options.haInterval : 10000,
-
- minHeartbeatFrequencyMS: 500,
-
- disconnectHandler: options.disconnectHandler,
-
- index: 0,
-
- connectOptions: {},
-
- debug: typeof options.debug == 'boolean' ? options.debug : false,
-
- clientInfo: createClientInfo(options)
- }
-
- this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { self.emit('topologyDescriptionChanged', r); });
-
-
- if(this.s.logger.isWarn()
- && this.s.options.socketTimeout != 0
- && this.s.options.socketTimeout < this.s.haInterval) {
- this.s.logger.warn(f('warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts'
- , this.s.options.socketTimeout, this.s.haInterval));
- }
-
- this.authProviders = options.authProviders || {
- 'mongocr': new MongoCR(this.s.bson), 'x509': new X509(this.s.bson)
- , 'plain': new Plain(this.s.bson), 'gssapi': new GSSAPI(this.s.bson)
- , 'sspi': new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson)
- }
-
- var types = ['joined', 'left'];
- types.forEach(function(x) {
- self.s.replicaSetState.on(x, function(t, s) {
- if(self.state === CONNECTED && x === 'joined' && t == 'primary') {
- self.emit('reconnect', self);
- }
- self.emit(x, t, s);
- });
- });
-
- this.initialConnectState = {
- connect: false, fullsetup: false, all: false
- }
-
- this.state = DISCONNECTED;
- this.haTimeoutId = null;
-
- this.authenticating = false;
-
- this.ismaster = null;
- }
- inherits(ReplSet, EventEmitter);
- Object.defineProperty(ReplSet.prototype, 'type', {
- enumerable:true, get: function() { return 'replset'; }
- });
- Object.defineProperty(ReplSet.prototype, 'parserType', {
- enumerable:true, get: function() {
- return BSON.native ? "c++" : "js";
- }
- });
- function attemptReconnect(self) {
- if(self.runningAttempReconnect) return;
-
- self.runningAttempReconnect = true;
-
- self.haTimeoutId = setTimeout(function() {
- if(self.state == DESTROYED) return;
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('attemptReconnect for replset with id %s', self.id));
- }
-
- var keys = Object.keys(self.s.replicaSetState.set);
- var servers = keys.map(function(x) {
- return new Server(assign({}, self.s.options, {
- host: x.split(':')[0], port: parseInt(x.split(':')[1], 10)
- }, {
- authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true
- }, {
- clientInfo: clone(self.s.clientInfo)
- }));
- });
-
- self.s.connectingServers = servers.slice(0);
-
- function _handleEvent(self, event) {
- return function() {
-
- if(self.state == DESTROYED) {
- return this.destroy();
- }
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('attemptReconnect for replset with id %s using server %s ended with event %s', self.id, this.name, event));
- }
-
- function done() {
-
- if(self.s.connectingServers.length == 0) {
- if(self.state == DESTROYED) return;
-
-
- if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) {
- self.s.disconnectHandler.execute();
- } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) {
- self.s.disconnectHandler.execute({ executePrimary:true });
- } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) {
- self.s.disconnectHandler.execute({ executeSecondary:true });
- }
-
- if(self.s.replicaSetState.hasPrimary()) {
-
- self.emit('reconnect', self);
-
- connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('attemptReconnect for replset with id successful resuming topologyMonitor', self.id));
- }
-
- self.runningAttempReconnect = false;
-
-
- setTimeout(function() {
- topologyMonitor(self);
- }, self.s.haInterval);
- });
- } else {
- if(self.listeners("close").length > 0) {
- self.emit('close', self);
- }
-
- self.runningAttempReconnect = false;
-
- attemptReconnect(self);
- }
- }
- }
-
- for(var i = 0; i < self.s.connectingServers.length; i++) {
- if(self.s.connectingServers[i].equals(this)) {
- self.s.connectingServers.splice(i, 1);
- }
- }
-
- var _self = this;
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('attemptReconnect in replset with id %s for', self.id));
- }
-
- if(event == 'connect' && !self.authenticating) {
- if(self.state == DESTROYED) {
- return _self.destroy();
- }
-
- if(self.s.replicaSetState.update(_self)) {
-
- if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) {
- self.ismaster = _self.lastIsMaster();
- }
-
- for(i = 0; i < handlers.length; i++) {
- _self.removeAllListeners(handlers[i]);
- }
-
- _self.on('error', handleEvent(self, 'error'));
- _self.on('close', handleEvent(self, 'close'));
- _self.on('timeout', handleEvent(self, 'timeout'));
- _self.on('parseError', handleEvent(self, 'parseError'));
- } else {
- _self.destroy();
- }
- } else if(event == 'connect' && self.authenticating) {
- this.destroy();
- }
- done();
- }
- }
-
-
- var timeoutInterval = 0;
- function connect(server, timeoutInterval) {
- setTimeout(function() {
- server.once('connect', _handleEvent(self, 'connect'));
- server.once('close', _handleEvent(self, 'close'));
- server.once('timeout', _handleEvent(self, 'timeout'));
- server.once('error', _handleEvent(self, 'error'));
- server.once('parseError', _handleEvent(self, 'parseError'));
-
- server.on('serverOpening', function(e) { self.emit('serverOpening', e); });
- server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); });
- server.on('serverClosed', function(e) { self.emit('serverClosed', e); });
- server.connect(self.s.connectOptions);
- }, timeoutInterval);
- }
-
- while(servers.length > 0) {
- connect(servers.shift(), timeoutInterval++);
- }
- }, self.s.minHeartbeatFrequencyMS);
- }
- function connectNewServers(self, servers, callback) {
-
- var count = servers.length;
-
- var _handleEvent = function(self, event) {
- return function() {
- var _self = this;
- count = count - 1;
-
- if(self.state == DESTROYED) {
- return this.destroy();
- }
- if(event == 'connect' && !self.authenticating) {
-
- if(self.state == DESTROYED) {
- return _self.destroy();
- }
- var result = self.s.replicaSetState.update(_self);
-
- if(result) {
-
- if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) {
- self.ismaster = _self.lastIsMaster();
- }
-
- for(var i = 0; i < handlers.length; i++) {
- _self.removeAllListeners(handlers[i]);
- }
-
- _self.on('error', handleEvent(self, 'error'));
- _self.on('close', handleEvent(self, 'close'));
- _self.on('timeout', handleEvent(self, 'timeout'));
- _self.on('parseError', handleEvent(self, 'parseError'));
- } else {
- _self.destroy();
- }
- } else if(event == 'connect' && self.authenticating) {
- this.destroy();
- }
-
- if(count == 0) { callback(); }
- }
- }
-
- if(count == 0) return callback();
-
- function execute(_server, i) {
- setTimeout(function() {
-
- if(self.state == DESTROYED) {
- return;
- }
-
- var server = new Server(assign({}, self.s.options, {
- host: _server.split(':')[0],
- port: parseInt(_server.split(':')[1], 10)
- }, {
- authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true
- }, {
- clientInfo: clone(self.s.clientInfo)
- }));
-
- server.once('connect', _handleEvent(self, 'connect'));
- server.once('close', _handleEvent(self, 'close'));
- server.once('timeout', _handleEvent(self, 'timeout'));
- server.once('error', _handleEvent(self, 'error'));
- server.once('parseError', _handleEvent(self, 'parseError'));
-
- server.on('serverOpening', function(e) { self.emit('serverOpening', e); });
- server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); });
- server.on('serverClosed', function(e) { self.emit('serverClosed', e); });
- server.connect(self.s.connectOptions);
- }, i);
- }
-
- for(var i = 0; i < servers.length; i++) {
- execute(servers[i], i);
- }
- }
- function topologyMonitor(self, options) {
- options = options || {};
-
- self.haTimeoutId = setTimeout(function() {
- if(self.state == DESTROYED) return;
-
-
-
-
- if(options.haInterval) {
- topologyMonitor(self);
- }
-
-
- if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) {
- self.s.disconnectHandler.execute();
- } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) {
- self.s.disconnectHandler.execute({ executePrimary:true });
- } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) {
- self.s.disconnectHandler.execute({ executeSecondary:true });
- }
-
- var connectingServers = self.s.replicaSetState.allServers();
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('topologyMonitor in replset with id %s connected servers [%s]'
- , self.id
- , connectingServers.map(function(x) {
- return x.name;
- })));
- }
-
- var count = connectingServers.length;
-
- if(count == 0 && !options.haInterval) {
- if(self.listeners("close").length > 0) {
- self.emit('close', self);
- }
- return attemptReconnect(self);
- }
-
- function pingServer(_self, _server, cb) {
-
- var start = new Date().getTime();
-
- emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name });
-
-
-
- _server.command('admin.$cmd', {
- ismaster:true
- }, {
- monitoring: true,
- socketTimeout: self.s.options.connectionTimeout || 2000,
- }, function(err, r) {
- if(self.state == DESTROYED) {
- _server.destroy();
- return cb(err, r);
- }
-
- var latencyMS = new Date().getTime() - start;
-
- var hrTime = process.hrtime();
-
- _server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1]/1000);
-
- if(err) {
-
- emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name });
-
- _self.s.replicaSetState.remove(_server);
- } else {
-
- _server.ismaster = r.result;
-
-
- if(_server.ismaster.lastWrite && _server.ismaster.lastWrite.lastWriteDate) {
- _server.lastWriteDate = _server.ismaster.lastWrite.lastWriteDate.getTime();
- }
-
- if(_server.lastIsMasterMS == -1) {
- _server.lastIsMasterMS = latencyMS;
- } else if(_server.lastIsMasterMS) {
-
-
-
-
-
-
- _server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * _server.lastIsMasterMS;
- }
- if(_self.s.replicaSetState.update(_server)) {
-
- if(_server.lastIsMaster() && _server.lastIsMaster().ismaster) {
- self.ismaster = _server.lastIsMaster();
- }
- }
-
- emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name });
- }
-
- self.s.replicaSetState.updateServerMaxStaleness(_server, self.s.haInterval);
-
- cb(err, r);
- });
- }
-
- function connectMissingServers() {
- if(self.state == DESTROYED) return;
-
- connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
- if(self.state == DESTROYED) return;
-
- if(options.haInterval) {
-
- if(self.state == CONNECTING
- && self.s.replicaSetState.hasPrimaryAndSecondary()) {
-
- stateTransition(self, CONNECTED);
-
- self.initialConnectState.connect = true;
- self.initialConnectState.fullsetup = true;
- self.initialConnectState.all = true;
-
- process.nextTick(function() {
- self.emit('connect', self);
- self.emit('fullsetup', self);
- self.emit('all', self);
- });
- } else if(self.state == CONNECTING
- && self.s.replicaSetState.hasPrimary()) {
-
- stateTransition(self, CONNECTED);
-
- self.initialConnectState.connect = true;
-
- process.nextTick(function() {
- self.emit('connect', self);
- });
- } else if(self.state == CONNECTING
- && self.s.replicaSetState.hasSecondary()
- && self.s.options.secondaryOnlyConnectionAllowed) {
-
- stateTransition(self, CONNECTED);
-
- self.initialConnectState.connect = true;
-
- process.nextTick(function() {
- self.emit('connect', self);
- });
- } else if(self.state == CONNECTING) {
- self.emit('error', new MongoError('no primary found in replicaset'));
-
- return self.destroy();
- } else if(self.state == CONNECTED
- && self.s.replicaSetState.hasPrimaryAndSecondary()
- && !self.initialConnectState.fullsetup) {
- self.initialConnectState.fullsetup = true;
-
- process.nextTick(function() {
- self.emit('fullsetup', self);
- self.emit('all', self);
- });
- }
- }
- if(!options.haInterval) topologyMonitor(self);
- });
- }
-
- if(connectingServers.length == 0
- && self.s.replicaSetState.unknownServers.length > 0 && options.haInterval) {
- return connectMissingServers();
- } else if(connectingServers.length == 0 && options.haInterval) {
- self.destroy();
- return self.emit('error', new MongoError('no valid replicaset members found'));
- }
-
- for(var i = 0; i < connectingServers.length; i++) {
- pingServer(self, connectingServers[i], function() {
- count = count - 1;
- if(count == 0) {
- connectMissingServers();
- }
- });
- }
- }, options.haInterval || self.s.haInterval)
- }
- function handleEvent(self, event) {
- return function() {
- if(self.state == DESTROYED) return;
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id));
- }
- self.s.replicaSetState.remove(this);
- }
- }
- function handleInitialConnectEvent(self, event) {
- return function() {
-
- if(self.s.logger.isDebug()) {
- self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s', event, this.name, self.id));
- }
-
- if(self.state == DESTROYED) {
- return this.destroy();
- }
-
- if(event == 'connect') {
-
- var result = self.s.replicaSetState.update(this);
- if(result == true) {
-
- if(this.lastIsMaster() && this.lastIsMaster().ismaster) {
- self.ismaster = this.lastIsMaster();
- }
-
- if(self.s.logger.isDebug()) {
- 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)));
- }
-
- for(var i = 0; i < handlers.length; i++) {
- this.removeAllListeners(handlers[i]);
- }
-
- this.on('error', handleEvent(self, 'error'));
- this.on('close', handleEvent(self, 'close'));
- this.on('timeout', handleEvent(self, 'timeout'));
- this.on('parseError', handleEvent(self, 'parseError'));
- } else if(result instanceof MongoError) {
- this.destroy();
- self.destroy();
- return self.emit('error', result);
- } else {
- this.destroy();
- }
- } else {
-
- self.emit('failed', this);
-
- self.s.replicaSetState.remove(this);
- }
-
- for(i = 0; i < self.s.connectingServers.length; i++) {
- if(self.s.connectingServers[i].equals(this)) {
- self.s.connectingServers.splice(i, 1);
- }
- }
-
- if(self.s.connectingServers.length == 0) {
- topologyMonitor(self, {haInterval: 1});
- }
- };
- }
- function connectServers(self, servers) {
-
- self.s.connectingServers = self.s.connectingServers.concat(servers);
-
-
- var timeoutInterval = 0;
- function connect(server, timeoutInterval) {
- setTimeout(function() {
-
- if(self.s.replicaSetState.update(server)) {
-
- if(server.lastIsMaster() && server.lastIsMaster().ismaster) {
- self.ismaster = server.lastIsMaster();
- }
- }
-
- server.once('close', handleInitialConnectEvent(self, 'close'));
- server.once('timeout', handleInitialConnectEvent(self, 'timeout'));
- server.once('parseError', handleInitialConnectEvent(self, 'parseError'));
- server.once('error', handleInitialConnectEvent(self, 'error'));
- server.once('connect', handleInitialConnectEvent(self, 'connect'));
-
- server.on('serverOpening', function(e) { self.emit('serverOpening', e); });
- server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); });
- server.on('serverClosed', function(e) { self.emit('serverClosed', e); });
-
- server.connect(self.s.connectOptions);
- }, timeoutInterval);
- }
-
- while(servers.length > 0) {
- connect(servers.shift(), timeoutInterval++);
- }
- }
- function emitSDAMEvent(self, event, description) {
- if(self.listeners(event).length > 0) {
- self.emit(event, description);
- }
- }
- ReplSet.prototype.connect = function(options) {
- var self = this;
-
- this.s.connectOptions = options || {};
-
- stateTransition(this, CONNECTING);
-
- var servers = this.s.seedlist.map(function(x) {
- return new Server(assign({}, self.s.options, x, {
- authProviders: self.authProviders, reconnect:false, monitoring:false, inTopology: true
- }, {
- clientInfo: clone(self.s.clientInfo)
- }));
- });
-
- if(this.s.options.socketTimeout > 0 && this.s.options.socketTimeout <= this.s.options.haInterval) {
- return self.emit('error', new MongoError(f("haInterval [%s] MS must be set to less than socketTimeout [%s] MS"
- , this.s.options.haInterval, this.s.options.socketTimeout)));
- }
-
- emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id });
-
- connectServers(self, servers);
- }
- ReplSet.prototype.destroy = function(options) {
- options = options || {};
-
- stateTransition(this, DESTROYED);
-
- if(this.haTimeoutId) clearTimeout(this.haTimeoutId);
-
- this.s.replicaSetState.destroy(options);
-
- this.s.connectingServers.forEach(function(x) {
- x.destroy(options);
- });
-
- emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id });
- }
- ReplSet.prototype.unref = function() {
-
- stateTransition(this, DISCONNECTED);
- this.s.replicaSetState.allServers().forEach(function(x) {
- x.unref();
- });
- clearTimeout(this.haTimeoutId);
- }
- ReplSet.prototype.lastIsMaster = function() {
- return this.s.replicaSetState.primary
- ? this.s.replicaSetState.primary.lastIsMaster() : this.ismaster;
- }
- ReplSet.prototype.connections = function() {
- var servers = this.s.replicaSetState.allServers();
- var connections = [];
- for(var i = 0; i < servers.length; i++) {
- connections = connections.concat(servers[i].connections());
- }
- return connections;
- }
- ReplSet.prototype.isConnected = function(options) {
- options = options || {};
-
-
- if(this.authenticating) return false;
-
-
- if(options.readPreference
- && options.readPreference.equals(ReadPreference.secondary)) {
- return this.s.replicaSetState.hasSecondary();
- }
- if(options.readPreference
- && options.readPreference.equals(ReadPreference.primary)) {
- return this.s.replicaSetState.hasPrimary();
- }
- if(options.readPreference
- && options.readPreference.equals(ReadPreference.primaryPreferred)) {
- return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary();
- }
- if(options.readPreference
- && options.readPreference.equals(ReadPreference.secondaryPreferred)) {
- return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary();
- }
- if(this.s.secondaryOnlyConnectionAllowed
- && this.s.replicaSetState.hasSecondary()) {
- return true;
- }
- return this.s.replicaSetState.hasPrimary();
- }
- ReplSet.prototype.isDestroyed = function() {
- return this.state == DESTROYED;
- }
- ReplSet.prototype.getServer = function(options) {
-
- options = options || {};
-
- var server = this.s.replicaSetState.pickServer(options.readPreference);
- if(this.s.debug) this.emit('pickedServer', options.readPreference, server);
- return server;
- }
- ReplSet.prototype.getServers = function() {
- return this.s.replicaSetState.allServers();
- }
- var executeWriteOperation = function(self, op, ns, ops, options, callback) {
- if(typeof options == 'function') callback = options, options = {}, options = options || {};
-
- options = options || {};
-
- if(self.s.replicaSetState.primary == null) {
- return callback(new MongoError("no primary server found"));
- }
-
- self.s.replicaSetState.primary[op](ns, ops, options, callback);
- }
- ReplSet.prototype.insert = function(ns, ops, options, callback) {
- if(typeof options == 'function') callback = options, options = {}, options = options || {};
- if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
-
- if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
- return this.s.disconnectHandler.add('insert', ns, ops, options, callback);
- }
-
- executeWriteOperation(this, 'insert', ns, ops, options, callback);
- }
- ReplSet.prototype.update = function(ns, ops, options, callback) {
- if(typeof options == 'function') callback = options, options = {}, options = options || {};
- if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
-
- if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
- return this.s.disconnectHandler.add('update', ns, ops, options, callback);
- }
-
- executeWriteOperation(this, 'update', ns, ops, options, callback);
- }
- ReplSet.prototype.remove = function(ns, ops, options, callback) {
- if(typeof options == 'function') callback = options, options = {}, options = options || {};
- if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
-
- if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
- return this.s.disconnectHandler.add('remove', ns, ops, options, callback);
- }
-
- executeWriteOperation(this, 'remove', ns, ops, options, callback);
- }
- ReplSet.prototype.command = function(ns, cmd, options, callback) {
- if(typeof options == 'function') callback = options, options = {}, options = options || {};
- if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
- var self = this;
-
- var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary;
-
- if(readPreference.preference == 'primary' && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
- return this.s.disconnectHandler.add('command', ns, cmd, options, callback);
- } else if(readPreference.preference == 'secondary' && !this.s.replicaSetState.hasSecondary() && this.s.disconnectHandler != null) {
- return this.s.disconnectHandler.add('command', ns, cmd, options, callback);
- } else if(readPreference.preference != 'primary' && !this.s.replicaSetState.hasSecondary() && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) {
- return this.s.disconnectHandler.add('command', ns, cmd, options, callback);
- }
-
- var server = this.s.replicaSetState.pickServer(readPreference);
-
- if(!(server instanceof Server)) return callback(server);
-
- if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server);
-
- if(server == null) {
- return callback(new MongoError(f("no server found that matches the provided readPreference %s", readPreference)));
- }
-
- server.command(ns, cmd, options, callback);
- }
- ReplSet.prototype.auth = function(mechanism, db) {
- var allArgs = Array.prototype.slice.call(arguments, 0).slice(0);
- var self = this;
- var args = Array.prototype.slice.call(arguments, 2);
- var callback = args.pop();
-
- if(this.authProviders[mechanism] == null && mechanism != 'default') {
- return callback(new MongoError(f("auth provider %s does not exist", mechanism)));
- }
-
- if(this.authenticating) {
- return callback(new MongoError('authentication or logout allready in process'));
- }
-
-
- if(!self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler != null) {
- return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback);
- }
-
- this.authenticating = true;
-
- var errors = [];
-
- var servers = this.s.replicaSetState.allServers();
-
- if(servers.length == 0) {
- this.authenticating = false;
- callback(null, true);
- }
-
- function auth(server) {
-
- var argsWithoutCallback = [mechanism, db].concat(args.slice(0));
-
- var finalArguments = argsWithoutCallback.concat([function(err) {
- count = count - 1;
-
- if(err) errors.push({name: server.name, err: err});
-
- if(count == 0) {
-
- self.authenticating = false;
-
- if(errors.length) return callback(MongoError.create({
- message: 'authentication fail', errors: errors
- }), false);
-
- callback(null, self);
- }
- }]);
- if(!server.lastIsMaster().arbiterOnly) {
-
- server.auth.apply(server, finalArguments);
- } else {
-
- finalArguments.pop()(null);
- }
- }
-
- var count = servers.length;
-
- while(servers.length > 0) {
- auth(servers.shift());
- }
- }
- ReplSet.prototype.logout = function(dbName, callback) {
- var self = this;
-
- if(this.authenticating) {
- throw new MongoError('authentication or logout allready in process');
- }
-
- this.authenticating = true;
-
- var providers = Object.keys(this.authProviders);
- for(var i = 0; i < providers.length; i++) {
- this.authProviders[providers[i]].logout(dbName);
- }
-
- var servers = this.s.replicaSetState.allServers();
- var count = servers.length;
- if(count == 0) return callback();
- var errors = [];
- function logoutServer(_server, cb) {
- _server.logout(dbName, function(err) {
- if(err) errors.push({name: _server.name, err: err});
- cb();
- });
- }
-
- for(i = 0; i < servers.length; i++) {
- logoutServer(servers[i], function() {
- count = count - 1;
- if(count == 0) {
-
- self.authenticating = false;
-
- if(errors.length) return callback(MongoError.create({
- message: f('logout failed against db %s', dbName), errors: errors
- }), false);
-
- callback();
- }
- })
- }
- }
- ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) {
- cursorOptions = cursorOptions || {};
- var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor;
- return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options);
- }
- module.exports = ReplSet;
|