-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathreplset.js
1564 lines (1352 loc) · 48.1 KB
/
replset.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const inherits = require('util').inherits;
const f = require('util').format;
const EventEmitter = require('events').EventEmitter;
const ReadPreference = require('./read_preference');
const CoreCursor = require('../cursor').CoreCursor;
const retrieveBSON = require('../connection/utils').retrieveBSON;
const Logger = require('../connection/logger');
const MongoError = require('../error').MongoError;
const Server = require('./server');
const ReplSetState = require('./replset_state');
const Timeout = require('./shared').Timeout;
const Interval = require('./shared').Interval;
const SessionMixins = require('./shared').SessionMixins;
const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported;
const relayEvents = require('../utils').relayEvents;
const BSON = retrieveBSON();
const getMMAPError = require('./shared').getMMAPError;
const makeClientMetadata = require('../utils').makeClientMetadata;
const legacyIsRetryableWriteError = require('./shared').legacyIsRetryableWriteError;
const now = require('../../utils').now;
const calculateDurationInMs = require('../../utils').calculateDurationInMs;
//
// States
var DISCONNECTED = 'disconnected';
var CONNECTING = 'connecting';
var CONNECTED = 'connected';
var UNREFERENCED = 'unreferenced';
var DESTROYED = 'destroyed';
function stateTransition(self, newState) {
var legalTransitions = {
disconnected: [CONNECTING, DESTROYED, DISCONNECTED],
connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED],
connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED],
unreferenced: [UNREFERENCED, DESTROYED],
destroyed: [DESTROYED]
};
// Get current state
var legalStates = legalTransitions[self.state];
if (legalStates && legalStates.indexOf(newState) !== -1) {
self.state = newState;
} else {
self.s.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
)
);
}
}
//
// ReplSet instance id
var id = 1;
var handlers = ['connect', 'close', 'error', 'timeout', 'parseError'];
/**
* Creates a new Replset instance
* @class
* @param {array} seedlist A list of seeds for the replicaset
* @param {boolean} options.setName The Replicaset set name
* @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset
* @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
* @param {boolean} [options.emitError=false] Server will emit errors events
* @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors
* @param {number} [options.size=5] Server connection pool size
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
* @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled
* @param {boolean} [options.noDelay=true] TCP Connection no delay
* @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting
* @param {number} [options.socketTimeout=0] TCP Socket timeout setting
* @param {boolean} [options.ssl=false] Use SSL for connection
* @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.
* @param {Buffer} [options.ca] SSL Certificate store binary buffer
* @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer
* @param {Buffer} [options.cert] SSL Certificate binary buffer
* @param {Buffer} [options.key] SSL Key file binary buffer
* @param {string} [options.passphrase] SSL Certificate pass phrase
* @param {string} [options.servername=null] String containing the server name requested via TLS SNI.
* @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates
* @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
* @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers
* @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
* @return {ReplSet} A cursor instance
* @fires ReplSet#connect
* @fires ReplSet#ha
* @fires ReplSet#joined
* @fires ReplSet#left
* @fires ReplSet#failed
* @fires ReplSet#fullsetup
* @fires ReplSet#all
* @fires ReplSet#error
* @fires ReplSet#serverHeartbeatStarted
* @fires ReplSet#serverHeartbeatSucceeded
* @fires ReplSet#serverHeartbeatFailed
* @fires ReplSet#topologyOpening
* @fires ReplSet#topologyClosed
* @fires ReplSet#topologyDescriptionChanged
* @property {string} type the topology type.
* @property {string} parserType the parser type used (c++ or js).
*/
var ReplSet = function(seedlist, options) {
var self = this;
options = options || {};
// Validate seedlist
if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array');
// Validate list
if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry');
// Validate entries
seedlist.forEach(function(e) {
if (typeof e.host !== 'string' || typeof e.port !== 'number')
throw new MongoError('seedlist entry must contain a host and port');
});
// Add event listener
EventEmitter.call(this);
// Get replSet Id
this.id = id++;
// Get the localThresholdMS
var localThresholdMS = options.localThresholdMS || 15;
// Backward compatibility
if (options.acceptableLatency) localThresholdMS = options.acceptableLatency;
// Create a logger
var logger = Logger('ReplSet', options);
// Internal state
this.s = {
options: Object.assign({ metadata: makeClientMetadata(options) }, options),
// BSON instance
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
]),
// Factory overrides
Cursor: options.cursorFactory || CoreCursor,
// Logger instance
logger: logger,
// Seedlist
seedlist: seedlist,
// Replicaset state
replicaSetState: new ReplSetState({
id: this.id,
setName: options.setName,
acceptableLatency: localThresholdMS,
heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000,
logger: logger
}),
// Current servers we are connecting to
connectingServers: [],
// Ha interval
haInterval: options.haInterval ? options.haInterval : 10000,
// Minimum heartbeat frequency used if we detect a server close
minHeartbeatFrequencyMS: 500,
// Disconnect handler
disconnectHandler: options.disconnectHandler,
// Server selection index
index: 0,
// Connect function options passed in
connectOptions: {},
// Are we running in debug mode
debug: typeof options.debug === 'boolean' ? options.debug : false
};
// Add handler for topology change
this.s.replicaSetState.on('topologyDescriptionChanged', function(r) {
self.emit('topologyDescriptionChanged', r);
});
// Log info warning if the socketTimeout < haInterval as it will cause
// a lot of recycled connections to happen.
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
)
);
}
// Add forwarding of events from state handler
var types = ['joined', 'left'];
types.forEach(function(x) {
self.s.replicaSetState.on(x, function(t, s) {
self.emit(x, t, s);
});
});
// Connect stat
this.initialConnectState = {
connect: false,
fullsetup: false,
all: false
};
// Disconnected state
this.state = DISCONNECTED;
this.haTimeoutId = null;
// Last ismaster
this.ismaster = null;
// Contains the intervalId
this.intervalIds = [];
// Highest clusterTime seen in responses from the current deployment
this.clusterTime = null;
};
inherits(ReplSet, EventEmitter);
Object.assign(ReplSet.prototype, SessionMixins);
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';
}
});
Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', {
enumerable: true,
get: function() {
return this.s.replicaSetState.logicalSessionTimeoutMinutes || null;
}
});
function rexecuteOperations(self) {
// If we have a primary and a disconnect handler, execute
// buffered operations
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 });
}
}
function connectNewServers(self, servers, callback) {
// No new servers
if (servers.length === 0) {
return callback();
}
// Count lefts
var count = servers.length;
var error = null;
function done() {
count = count - 1;
if (count === 0) {
callback(error);
}
}
// Handle events
var _handleEvent = function(self, event) {
return function(err) {
var _self = this;
// Destroyed
if (self.state === DESTROYED || self.state === UNREFERENCED) {
this.destroy({ force: true });
return done();
}
if (event === 'connect') {
// Update the state
var result = self.s.replicaSetState.update(_self);
// Update the state with the new server
if (result) {
// Primary lastIsMaster store it
if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) {
self.ismaster = _self.lastIsMaster();
}
// Remove the handlers
for (let i = 0; i < handlers.length; i++) {
_self.removeAllListeners(handlers[i]);
}
// Add stable state handlers
_self.on('error', handleEvent(self, 'error'));
_self.on('close', handleEvent(self, 'close'));
_self.on('timeout', handleEvent(self, 'timeout'));
_self.on('parseError', handleEvent(self, 'parseError'));
// Enalbe the monitoring of the new server
monitorServer(_self.lastIsMaster().me, self, {});
// Rexecute any stalled operation
rexecuteOperations(self);
} else {
_self.destroy({ force: true });
}
} else if (event === 'error') {
error = err;
}
// Rexecute any stalled operation
rexecuteOperations(self);
done();
};
};
// Execute method
function execute(_server, i) {
setTimeout(function() {
// Destroyed
if (self.state === DESTROYED || self.state === UNREFERENCED) {
return;
}
// remove existing connecting server if it's failed to connect, otherwise
// wait for that server to connect
const existingServerIdx = self.s.connectingServers.findIndex(s => s.name === _server);
if (existingServerIdx >= 0) {
const connectingServer = self.s.connectingServers[existingServerIdx];
connectingServer.destroy({ force: true });
self.s.connectingServers.splice(existingServerIdx, 1);
return done();
}
// Create a new server instance
var server = new Server(
Object.assign({}, self.s.options, {
host: _server.split(':')[0],
port: parseInt(_server.split(':')[1], 10),
reconnect: false,
monitoring: false,
parent: self
})
);
// Add temp handlers
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'));
// SDAM Monitoring events
server.on('serverOpening', e => self.emit('serverOpening', e));
server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e));
server.on('serverClosed', e => self.emit('serverClosed', e));
// Command Monitoring events
relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);
self.s.connectingServers.push(server);
server.connect(self.s.connectOptions);
}, i);
}
// Create new instances
for (var i = 0; i < servers.length; i++) {
execute(servers[i], i);
}
}
// Ping the server
var pingServer = function(self, server, cb) {
// Measure running time
var start = new Date().getTime();
// Emit the server heartbeat start
emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name });
// Execute ismaster
// Set the socketTimeout for a monitoring message to a low number
// Ensuring ismaster calls are timed out quickly
server.command(
'admin.$cmd',
{
ismaster: true
},
{
monitoring: true,
socketTimeout: self.s.options.connectionTimeout || 2000
},
function(err, r) {
if (self.state === DESTROYED || self.state === UNREFERENCED) {
server.destroy({ force: true });
return cb(err, r);
}
// Calculate latency
var latencyMS = new Date().getTime() - start;
// Set the last updatedTime
server.lastUpdateTime = now();
// We had an error, remove it from the state
if (err) {
// Emit the server heartbeat failure
emitSDAMEvent(self, 'serverHeartbeatFailed', {
durationMS: latencyMS,
failure: err,
connectionId: server.name
});
// Remove server from the state
self.s.replicaSetState.remove(server);
} else {
// Update the server ismaster
server.ismaster = r.result;
// Check if we have a lastWriteDate convert it to MS
// and store on the server instance for later use
if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) {
server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime();
}
// Do we have a brand new server
if (server.lastIsMasterMS === -1) {
server.lastIsMasterMS = latencyMS;
} else if (server.lastIsMasterMS) {
// After the first measurement, average RTT MUST be computed using an
// exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2.
// If the prior average is denoted old_rtt, then the new average (new_rtt) is
// computed from a new RTT measurement (x) using the following formula:
// alpha = 0.2
// new_rtt = alpha * x + (1 - alpha) * old_rtt
server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS;
}
if (self.s.replicaSetState.update(server)) {
// Primary lastIsMaster store it
if (server.lastIsMaster() && server.lastIsMaster().ismaster) {
self.ismaster = server.lastIsMaster();
}
}
// Server heart beat event
emitSDAMEvent(self, 'serverHeartbeatSucceeded', {
durationMS: latencyMS,
reply: r.result,
connectionId: server.name
});
}
// Calculate the staleness for this server
self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval);
// Callback
cb(err, r);
}
);
};
// Each server is monitored in parallel in their own timeout loop
var monitorServer = function(host, self, options) {
// If this is not the initial scan
// Is this server already being monitoried, then skip monitoring
if (!options.haInterval) {
for (var i = 0; i < self.intervalIds.length; i++) {
if (self.intervalIds[i].__host === host) {
return;
}
}
}
// Get the haInterval
var _process = options.haInterval ? Timeout : Interval;
var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval;
// Create the interval
var intervalId = new _process(function() {
if (self.state === DESTROYED || self.state === UNREFERENCED) {
// clearInterval(intervalId);
intervalId.stop();
return;
}
// Do we already have server connection available for this host
var _server = self.s.replicaSetState.get(host);
// Check if we have a known server connection and reuse
if (_server) {
// Ping the server
return pingServer(self, _server, function(err) {
if (err) {
// NOTE: should something happen here?
return;
}
if (self.state === DESTROYED || self.state === UNREFERENCED) {
intervalId.stop();
return;
}
// Filter out all called intervaliIds
self.intervalIds = self.intervalIds.filter(function(intervalId) {
return intervalId.isRunning();
});
// Initial sweep
if (_process === Timeout) {
if (
self.state === CONNECTING &&
((self.s.replicaSetState.hasSecondary() &&
self.s.options.secondaryOnlyConnectionAllowed) ||
self.s.replicaSetState.hasPrimary())
) {
stateTransition(self, CONNECTED);
// Emit connected sign
process.nextTick(function() {
self.emit('connect', self);
});
// Start topology interval check
topologyMonitor(self, {});
}
} else {
if (
self.state === DISCONNECTED &&
((self.s.replicaSetState.hasSecondary() &&
self.s.options.secondaryOnlyConnectionAllowed) ||
self.s.replicaSetState.hasPrimary())
) {
stateTransition(self, CONNECTED);
// Rexecute any stalled operation
rexecuteOperations(self);
// Emit connected sign
process.nextTick(function() {
self.emit('reconnect', self);
});
}
}
if (
self.initialConnectState.connect &&
!self.initialConnectState.fullsetup &&
self.s.replicaSetState.hasPrimaryAndSecondary()
) {
// Set initial connect state
self.initialConnectState.fullsetup = true;
self.initialConnectState.all = true;
process.nextTick(function() {
self.emit('fullsetup', self);
self.emit('all', self);
});
}
});
}
}, _haInterval);
// Start the interval
intervalId.start();
// Add the intervalId host name
intervalId.__host = host;
// Add the intervalId to our list of intervalIds
self.intervalIds.push(intervalId);
};
function topologyMonitor(self, options) {
if (self.state === DESTROYED || self.state === UNREFERENCED) return;
options = options || {};
// Get the servers
var servers = Object.keys(self.s.replicaSetState.set);
// Get the haInterval
var _process = options.haInterval ? Timeout : Interval;
var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval;
if (_process === Timeout) {
return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) {
// Don't emit errors if the connection was already
if (self.state === DESTROYED || self.state === UNREFERENCED) {
return;
}
if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) {
if (err) {
return self.emit('error', err);
}
self.emit(
'error',
new MongoError('no primary found in replicaset or invalid replica set name')
);
return self.destroy({ force: true });
} else if (
!self.s.replicaSetState.hasSecondary() &&
self.s.options.secondaryOnlyConnectionAllowed
) {
if (err) {
return self.emit('error', err);
}
self.emit(
'error',
new MongoError('no secondary found in replicaset or invalid replica set name')
);
return self.destroy({ force: true });
}
for (var i = 0; i < servers.length; i++) {
monitorServer(servers[i], self, options);
}
});
} else {
for (var i = 0; i < servers.length; i++) {
monitorServer(servers[i], self, options);
}
}
// Run the reconnect process
function executeReconnect(self) {
return function() {
if (self.state === DESTROYED || self.state === UNREFERENCED) {
return;
}
connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
var monitoringFrequencey = self.s.replicaSetState.hasPrimary()
? _haInterval
: self.s.minHeartbeatFrequencyMS;
// Create a timeout
self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start());
});
};
}
// Decide what kind of interval to use
var intervalTime = !self.s.replicaSetState.hasPrimary()
? self.s.minHeartbeatFrequencyMS
: _haInterval;
self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start());
}
function addServerToList(list, server) {
for (var i = 0; i < list.length; i++) {
if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true;
}
list.push(server);
}
function handleEvent(self, event) {
return function() {
if (self.state === DESTROYED || self.state === UNREFERENCED) return;
// Debug log
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)
);
}
// Remove from the replicaset state
self.s.replicaSetState.remove(this);
// Are we in a destroyed state return
if (self.state === DESTROYED || self.state === UNREFERENCED) return;
// If no primary and secondary available
if (
!self.s.replicaSetState.hasPrimary() &&
!self.s.replicaSetState.hasSecondary() &&
self.s.options.secondaryOnlyConnectionAllowed
) {
stateTransition(self, DISCONNECTED);
} else if (!self.s.replicaSetState.hasPrimary()) {
stateTransition(self, DISCONNECTED);
}
addServerToList(self.s.connectingServers, this);
};
}
function shouldTriggerConnect(self) {
const isConnecting = self.state === CONNECTING;
const hasPrimary = self.s.replicaSetState.hasPrimary();
const hasSecondary = self.s.replicaSetState.hasSecondary();
const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed;
const readPreferenceSecondary =
self.s.connectOptions.readPreference &&
self.s.connectOptions.readPreference.equals(ReadPreference.secondary);
return (
(isConnecting &&
((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) ||
(hasSecondary && secondaryOnlyConnectionAllowed)
);
}
function handleInitialConnectEvent(self, event) {
return function() {
var _this = this;
// Debug log
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
)
);
}
// Destroy the instance
if (self.state === DESTROYED || self.state === UNREFERENCED) {
return this.destroy({ force: true });
}
// Check the type of server
if (event === 'connect') {
// Update the state
var result = self.s.replicaSetState.update(_this);
if (result === true) {
// Primary lastIsMaster store it
if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) {
self.ismaster = _this.lastIsMaster();
}
// Debug log
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)
)
);
}
// Remove the handlers
for (let i = 0; i < handlers.length; i++) {
_this.removeAllListeners(handlers[i]);
}
// Add stable state handlers
_this.on('error', handleEvent(self, 'error'));
_this.on('close', handleEvent(self, 'close'));
_this.on('timeout', handleEvent(self, 'timeout'));
_this.on('parseError', handleEvent(self, 'parseError'));
// Do we have a primary or primaryAndSecondary
if (shouldTriggerConnect(self)) {
// We are connected
stateTransition(self, CONNECTED);
// Set initial connect state
self.initialConnectState.connect = true;
// Emit connect event
process.nextTick(function() {
self.emit('connect', self);
});
topologyMonitor(self, {});
}
} else if (result instanceof MongoError) {
_this.destroy({ force: true });
self.destroy({ force: true });
return self.emit('error', result);
} else {
_this.destroy({ force: true });
}
} else {
// Emit failure to connect
self.emit('failed', this);
addServerToList(self.s.connectingServers, this);
// Remove from the state
self.s.replicaSetState.remove(this);
}
if (
self.initialConnectState.connect &&
!self.initialConnectState.fullsetup &&
self.s.replicaSetState.hasPrimaryAndSecondary()
) {
// Set initial connect state
self.initialConnectState.fullsetup = true;
self.initialConnectState.all = true;
process.nextTick(function() {
self.emit('fullsetup', self);
self.emit('all', self);
});
}
// Remove from the list from connectingServers
for (var i = 0; i < self.s.connectingServers.length; i++) {
if (self.s.connectingServers[i].equals(this)) {
self.s.connectingServers.splice(i, 1);
}
}
// Trigger topologyMonitor
if (self.s.connectingServers.length === 0 && self.state === CONNECTING) {
topologyMonitor(self, { haInterval: 1 });
}
};
}
function connectServers(self, servers) {
// Update connectingServers
self.s.connectingServers = self.s.connectingServers.concat(servers);
// Index used to interleaf the server connects, avoiding
// runtime issues on io constrained vm's
var timeoutInterval = 0;
function connect(server, timeoutInterval) {
setTimeout(function() {
// Add the server to the state
if (self.s.replicaSetState.update(server)) {
// Primary lastIsMaster store it
if (server.lastIsMaster() && server.lastIsMaster().ismaster) {
self.ismaster = server.lastIsMaster();
}
}
// Add event handlers
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'));
// SDAM Monitoring events
server.on('serverOpening', e => self.emit('serverOpening', e));
server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e));
server.on('serverClosed', e => self.emit('serverClosed', e));
// Command Monitoring events
relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);
// Start connection
server.connect(self.s.connectOptions);
}, timeoutInterval);
}
// Start all the servers
while (servers.length > 0) {
connect(servers.shift(), timeoutInterval++);
}
}
/**
* Emit event if it exists
* @method
*/
function emitSDAMEvent(self, event, description) {
if (self.listeners(event).length > 0) {
self.emit(event, description);
}
}
/**
* Initiate server connect
*/
ReplSet.prototype.connect = function(options) {
var self = this;
// Add any connect level options to the internal state
this.s.connectOptions = options || {};
// Set connecting state
stateTransition(this, CONNECTING);
// Create server instances
var servers = this.s.seedlist.map(function(x) {
return new Server(
Object.assign({}, self.s.options, x, options, {
reconnect: false,
monitoring: false,
parent: self
})
);
});
// Error out as high availability interval must be < than socketTimeout
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
)
)
);
}
// Emit the topology opening event
emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id });
// Start all server connections
connectServers(self, servers);
};
/**
* Authenticate the topology.
* @method
* @param {MongoCredentials} credentials The credentials for authentication we are using
* @param {authResultCallback} callback A callback function
*/
ReplSet.prototype.auth = function(credentials, callback) {
if (typeof callback === 'function') callback(null, null);
};
/**
* Destroy the server connection
* @param {boolean} [options.force=false] Force destroy the pool
* @method
*/
ReplSet.prototype.destroy = function(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy`
const serverDestroyed = () => {
destroyCount--;
if (destroyCount > 0) {
return;
}
// Emit toplogy closing event
emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id });
if (typeof callback === 'function') {
callback(null, null);
}
};
if (this.state === DESTROYED) {
if (typeof callback === 'function') callback(null, null);
return;
}
// Transition state
stateTransition(this, DESTROYED);
// Clear out any monitoring process
if (this.haTimeoutId) clearTimeout(this.haTimeoutId);
// Clear out all monitoring
for (var i = 0; i < this.intervalIds.length; i++) {
this.intervalIds[i].stop();
}
// Reset list of intervalIds
this.intervalIds = [];