This repository has been archived by the owner on Feb 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 108
/
pool.js
1596 lines (1389 loc) · 49.4 KB
/
pool.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';
var inherits = require('util').inherits,
EventEmitter = require('events').EventEmitter,
Connection = require('./connection'),
MongoError = require('../error').MongoError,
MongoNetworkError = require('../error').MongoNetworkError,
Logger = require('./logger'),
f = require('util').format,
Query = require('./commands').Query,
CommandResult = require('./command_result'),
assign = require('../utils').assign,
MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE,
opcodes = require('../wireprotocol/shared').opcodes,
compress = require('../wireprotocol/compression').compress,
compressorIDs = require('../wireprotocol/compression').compressorIDs,
uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands,
resolveClusterTime = require('../topologies/shared').resolveClusterTime;
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 DISCONNECTED = 'disconnected';
var CONNECTING = 'connecting';
var CONNECTED = 'connected';
var DESTROYING = 'destroying';
var DESTROYED = 'destroyed';
var _id = 0;
function hasSessionSupport(topology) {
if (topology == null) return false;
return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6;
}
/**
* Creates a new Pool instance
* @class
* @param {string} options.host The server host
* @param {number} options.port The server port
* @param {number} [options.size=1] Max server connection pool size
* @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
* @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled
* @param {boolean} [options.noDelay=true] TCP Connection no delay
* @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
* @param {number} [options.socketTimeout=360000] TCP Socket timeout setting
* @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket
* @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 {boolean} [options.rejectUnauthorized=false] 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 {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
* @fires Pool#connect
* @fires Pool#close
* @fires Pool#error
* @fires Pool#timeout
* @fires Pool#parseError
* @return {Pool} A cursor instance
*/
var Pool = function(topology, options) {
// Add event listener
EventEmitter.call(this);
// Store topology for later use
this.topology = topology;
// Add the options
this.options = assign(
{
// Host and port settings
host: 'localhost',
port: 27017,
// Pool default max size
size: 5,
// socket settings
connectionTimeout: 30000,
socketTimeout: 360000,
keepAlive: true,
keepAliveInitialDelay: 300000,
noDelay: true,
// SSL Settings
ssl: false,
checkServerIdentity: true,
ca: null,
crl: null,
cert: null,
key: null,
passPhrase: null,
rejectUnauthorized: false,
promoteLongs: true,
promoteValues: true,
promoteBuffers: false,
// Reconnection options
reconnect: true,
reconnectInterval: 1000,
reconnectTries: 30,
// Enable domains
domainsEnabled: false
},
options
);
// Identification information
this.id = _id++;
// Current reconnect retries
this.retriesLeft = this.options.reconnectTries;
this.reconnectId = null;
// No bson parser passed in
if (
!options.bson ||
(options.bson &&
(typeof options.bson.serialize !== 'function' ||
typeof options.bson.deserialize !== 'function'))
) {
throw new Error('must pass in valid bson parser');
}
// Logger instance
this.logger = Logger('Pool', options);
// Pool state
this.state = DISCONNECTED;
// Connections
this.availableConnections = [];
this.inUseConnections = [];
this.connectingConnections = [];
// Currently executing
this.executing = false;
// Operation work queue
this.queue = [];
// All the authProviders
this.authProviders = options.authProviders || {
mongocr: new MongoCR(options.bson),
x509: new X509(options.bson),
plain: new Plain(options.bson),
gssapi: new GSSAPI(options.bson),
sspi: new SSPI(options.bson),
'scram-sha-1': new ScramSHA1(options.bson)
};
// Contains the reconnect connection
this.reconnectConnection = null;
// Are we currently authenticating
this.authenticating = false;
this.loggingout = false;
this.nonAuthenticatedConnections = [];
this.authenticatingTimestamp = null;
// Number of consecutive timeouts caught
this.numberOfConsecutiveTimeouts = 0;
// Current pool Index
this.connectionIndex = 0;
};
inherits(Pool, EventEmitter);
Object.defineProperty(Pool.prototype, 'size', {
enumerable: true,
get: function() {
return this.options.size;
}
});
Object.defineProperty(Pool.prototype, 'connectionTimeout', {
enumerable: true,
get: function() {
return this.options.connectionTimeout;
}
});
Object.defineProperty(Pool.prototype, 'socketTimeout', {
enumerable: true,
get: function() {
return this.options.socketTimeout;
}
});
function stateTransition(self, newState) {
var legalTransitions = {
disconnected: [CONNECTING, DESTROYING, DISCONNECTED],
connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED],
connected: [CONNECTED, DISCONNECTED, DESTROYING],
destroying: [DESTROYING, DESTROYED],
destroyed: [DESTROYED]
};
// Get current state
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
)
);
}
}
function authenticate(pool, auth, connection, cb) {
if (auth[0] === undefined) return cb(null);
// We need to authenticate the server
var mechanism = auth[0];
var db = auth[1];
// Validate if the mechanism exists
if (!pool.authProviders[mechanism]) {
throw new MongoError(f('authMechanism %s not supported', mechanism));
}
// Get the provider
var provider = pool.authProviders[mechanism];
// Authenticate using the provided mechanism
provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb]));
}
// The write function used by the authentication mechanism (bypasses external)
function write(self) {
return function(connection, command, callback) {
// Get the raw buffer
// Ensure we stop auth if pool was destroyed
if (self.state === DESTROYED || self.state === DESTROYING) {
return callback(new MongoError('pool destroyed'));
}
// Set the connection workItem callback
connection.workItems.push({
cb: callback,
command: true,
requestId: command.requestId
});
// Write the buffer out to the connection
connection.write(command.toBin());
};
}
function reauthenticate(pool, connection, cb) {
// Authenticate
function authenticateAgainstProvider(pool, connection, providers, cb) {
// Finished re-authenticating against providers
if (providers.length === 0) return cb();
// Get the provider name
var provider = pool.authProviders[providers.pop()];
// Auth provider
provider.reauthenticate(write(pool), [connection], function(err) {
// We got an error return immediately
if (err) return cb(err);
// Continue authenticating the connection
authenticateAgainstProvider(pool, connection, providers, cb);
});
}
// Start re-authenticating process
authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb);
}
function connectionFailureHandler(self, event) {
return function(err) {
if (this._connectionFailHandled) return;
this._connectionFailHandled = true;
// Destroy the connection
this.destroy();
// Remove the connection
removeConnection(self, this);
// Flush all work Items on this connection
while (this.workItems.length > 0) {
var workItem = this.workItems.shift();
if (workItem.cb) workItem.cb(err);
}
// Did we catch a timeout, increment the numberOfConsecutiveTimeouts
if (event === 'timeout') {
self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1;
// Have we timed out more than reconnectTries in a row ?
// Force close the pool as we are trying to connect to tcp sink hole
if (self.numberOfConsecutiveTimeouts > self.options.reconnectTries) {
self.numberOfConsecutiveTimeouts = 0;
// Destroy all connections and pool
self.destroy(true);
// Emit close event
return self.emit('close', self);
}
}
// No more socket available propegate the event
if (self.socketCount() === 0) {
if (self.state !== DESTROYED && self.state !== DESTROYING) {
stateTransition(self, DISCONNECTED);
}
// Do not emit error events, they are always close events
// do not trigger the low level error handler in node
event = event === 'error' ? 'close' : event;
self.emit(event, err);
}
// Start reconnection attempts
if (!self.reconnectId && self.options.reconnect) {
self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval);
}
};
}
function attemptReconnect(self) {
return function() {
self.emit('attemptReconnect', self);
if (self.state === DESTROYED || self.state === DESTROYING) return;
// We are connected do not try again
if (self.isConnected()) {
self.reconnectId = null;
return;
}
// If we have failure schedule a retry
function _connectionFailureHandler(self) {
return function() {
if (this._connectionFailHandled) return;
this._connectionFailHandled = true;
// Destroy the connection
this.destroy();
// Count down the number of reconnects
self.retriesLeft = self.retriesLeft - 1;
// How many retries are left
if (self.retriesLeft === 0) {
// Destroy the instance
self.destroy();
// Emit close event
self.emit(
'reconnectFailed',
new MongoNetworkError(
f(
'failed to reconnect after %s attempts with interval %s ms',
self.options.reconnectTries,
self.options.reconnectInterval
)
)
);
} else {
self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval);
}
};
}
// Got a connect handler
function _connectHandler(self) {
return function() {
// Assign
var connection = this;
// Pool destroyed stop the connection
if (self.state === DESTROYED || self.state === DESTROYING) {
return connection.destroy();
}
// Clear out all handlers
handlers.forEach(function(event) {
connection.removeAllListeners(event);
});
// Reset reconnect id
self.reconnectId = null;
// Apply pool connection handlers
connection.on('error', connectionFailureHandler(self, 'error'));
connection.on('close', connectionFailureHandler(self, 'close'));
connection.on('timeout', connectionFailureHandler(self, 'timeout'));
connection.on('parseError', connectionFailureHandler(self, 'parseError'));
// Apply any auth to the connection
reauthenticate(self, this, function() {
// Reset retries
self.retriesLeft = self.options.reconnectTries;
// Push to available connections
self.availableConnections.push(connection);
// Set the reconnectConnection to null
self.reconnectConnection = null;
// Emit reconnect event
self.emit('reconnect', self);
// Trigger execute to start everything up again
_execute(self)();
});
};
}
// Create a connection
self.reconnectConnection = new Connection(messageHandler(self), self.options);
// Add handlers
self.reconnectConnection.on('close', _connectionFailureHandler(self, 'close'));
self.reconnectConnection.on('error', _connectionFailureHandler(self, 'error'));
self.reconnectConnection.on('timeout', _connectionFailureHandler(self, 'timeout'));
self.reconnectConnection.on('parseError', _connectionFailureHandler(self, 'parseError'));
// On connection
self.reconnectConnection.on('connect', _connectHandler(self));
// Attempt connection
self.reconnectConnection.connect();
};
}
function moveConnectionBetween(connection, from, to) {
var index = from.indexOf(connection);
// Move the connection from connecting to available
if (index !== -1) {
from.splice(index, 1);
to.push(connection);
}
}
function messageHandler(self) {
return function(message, connection) {
// workItem to execute
var workItem = null;
// Locate the workItem
for (var i = 0; i < connection.workItems.length; i++) {
if (connection.workItems[i].requestId === message.responseTo) {
// Get the callback
workItem = connection.workItems[i];
// Remove from list of workItems
connection.workItems.splice(i, 1);
}
}
// Reset timeout counter
self.numberOfConsecutiveTimeouts = 0;
// Reset the connection timeout if we modified it for
// this operation
if (workItem.socketTimeout) {
connection.resetSocketTimeout();
}
// Log if debug enabled
if (self.logger.isDebug()) {
self.logger.debug(
f(
'message [%s] received from %s:%s',
message.raw.toString('hex'),
self.options.host,
self.options.port
)
);
}
// Authenticate any straggler connections
function authenticateStragglers(self, connection, callback) {
// Get any non authenticated connections
var connections = self.nonAuthenticatedConnections.slice(0);
var nonAuthenticatedConnections = self.nonAuthenticatedConnections;
self.nonAuthenticatedConnections = [];
// Establish if the connection need to be authenticated
// Add to authentication list if
// 1. we were in an authentication process when the operation was executed
// 2. our current authentication timestamp is from the workItem one, meaning an auth has happened
if (
connection.workItems.length === 1 &&
(connection.workItems[0].authenticating === true ||
(typeof connection.workItems[0].authenticatingTimestamp === 'number' &&
connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp))
) {
// Add connection to the list
connections.push(connection);
}
// No connections need to be re-authenticated
if (connections.length === 0) {
// Release the connection back to the pool
moveConnectionBetween(connection, self.inUseConnections, self.availableConnections);
// Finish
return callback();
}
// Apply re-authentication to all connections before releasing back to pool
var connectionCount = connections.length;
// Authenticate all connections
for (var i = 0; i < connectionCount; i++) {
reauthenticate(self, connections[i], function() {
connectionCount = connectionCount - 1;
if (connectionCount === 0) {
// Put non authenticated connections in available connections
self.availableConnections = self.availableConnections.concat(
nonAuthenticatedConnections
);
// Release the connection back to the pool
moveConnectionBetween(connection, self.inUseConnections, self.availableConnections);
// Return
callback();
}
});
}
}
function handleOperationCallback(self, cb, err, result) {
// No domain enabled
if (!self.options.domainsEnabled) {
return process.nextTick(function() {
return cb(err, result);
});
}
// Domain enabled just call the callback
cb(err, result);
}
authenticateStragglers(self, connection, function() {
// Keep executing, ensure current message handler does not stop execution
if (!self.executing) {
process.nextTick(function() {
_execute(self)();
});
}
// Time to dispatch the message if we have a callback
if (!workItem.immediateRelease) {
try {
// Parse the message according to the provided options
message.parse(workItem);
} catch (err) {
return handleOperationCallback(self, workItem.cb, new MongoError(err));
}
// Look for clusterTime, and operationTime and update them if necessary
if (message.documents[0]) {
if (message.documents[0].$clusterTime) {
const $clusterTime = message.documents[0].$clusterTime;
self.topology.clusterTime = $clusterTime;
if (workItem.session != null) {
resolveClusterTime(workItem.session, $clusterTime);
}
}
if (
message.documents[0].operationTime &&
workItem.session &&
workItem.session.supports.causalConsistency
) {
workItem.session.advanceOperationTime(message.documents[0].operationTime);
}
}
// Establish if we have an error
if (
workItem.command &&
message.documents[0] &&
(message.documents[0].ok === 0 ||
message.documents[0]['$err'] ||
message.documents[0]['errmsg'] ||
message.documents[0]['code'])
) {
return handleOperationCallback(self, workItem.cb, new MongoError(message.documents[0]));
}
// Add the connection details
message.hashedName = connection.hashedName;
// Return the documents
handleOperationCallback(
self,
workItem.cb,
null,
new CommandResult(
workItem.fullResult ? message : message.documents[0],
connection,
message
)
);
}
});
};
}
/**
* Return the total socket count in the pool.
* @method
* @return {Number} The number of socket available.
*/
Pool.prototype.socketCount = function() {
return this.availableConnections.length + this.inUseConnections.length;
// + this.connectingConnections.length;
};
/**
* Return all pool connections
* @method
* @return {Connection[]} The pool connections
*/
Pool.prototype.allConnections = function() {
return this.availableConnections.concat(this.inUseConnections).concat(this.connectingConnections);
};
/**
* Get a pool connection (round-robin)
* @method
* @return {Connection}
*/
Pool.prototype.get = function() {
return this.allConnections()[0];
};
/**
* Is the pool connected
* @method
* @return {boolean}
*/
Pool.prototype.isConnected = function() {
// We are in a destroyed state
if (this.state === DESTROYED || this.state === DESTROYING) {
return false;
}
// Get connections
var connections = this.availableConnections.concat(this.inUseConnections);
// Check if we have any connected connections
for (var i = 0; i < connections.length; i++) {
if (connections[i].isConnected()) return true;
}
// Might be authenticating, but we are still connected
if (connections.length === 0 && this.authenticating) {
return true;
}
// Not connected
return false;
};
/**
* Was the pool destroyed
* @method
* @return {boolean}
*/
Pool.prototype.isDestroyed = function() {
return this.state === DESTROYED || this.state === DESTROYING;
};
/**
* Is the pool in a disconnected state
* @method
* @return {boolean}
*/
Pool.prototype.isDisconnected = function() {
return this.state === DISCONNECTED;
};
/**
* Connect pool
* @method
*/
Pool.prototype.connect = function() {
if (this.state !== DISCONNECTED) {
throw new MongoError('connection in unlawful state ' + this.state);
}
var self = this;
// Transition to connecting state
stateTransition(this, CONNECTING);
// Create an array of the arguments
var args = Array.prototype.slice.call(arguments, 0);
// Create a connection
var connection = new Connection(messageHandler(self), this.options);
// Add to list of connections
this.connectingConnections.push(connection);
// Add listeners to the connection
connection.once('connect', function(connection) {
if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy();
// If we are in a topology, delegate the auth to it
// This is to avoid issues where we would auth against an
// arbiter
if (self.options.inTopology) {
// Set connected mode
stateTransition(self, CONNECTED);
// Move the active connection
moveConnectionBetween(connection, self.connectingConnections, self.availableConnections);
// Emit the connect event
return self.emit('connect', self);
}
// Apply any store credentials
reauthenticate(self, connection, function(err) {
if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy();
// We have an error emit it
if (err) {
// Destroy the pool
self.destroy();
// Emit the error
return self.emit('error', err);
}
// Authenticate
authenticate(self, args, connection, function(err) {
if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy();
// We have an error emit it
if (err) {
// Destroy the pool
self.destroy();
// Emit the error
return self.emit('error', err);
}
// Set connected mode
stateTransition(self, CONNECTED);
// Move the active connection
moveConnectionBetween(connection, self.connectingConnections, self.availableConnections);
// Emit the connect event
self.emit('connect', self);
});
});
});
// Add error handlers
connection.once('error', connectionFailureHandler(this, 'error'));
connection.once('close', connectionFailureHandler(this, 'close'));
connection.once('timeout', connectionFailureHandler(this, 'timeout'));
connection.once('parseError', connectionFailureHandler(this, 'parseError'));
try {
connection.connect();
} catch (err) {
// SSL or something threw on connect
process.nextTick(function() {
self.emit('error', err);
});
}
};
/**
* Authenticate using a specified mechanism
* @method
* @param {string} mechanism The Auth mechanism we are invoking
* @param {string} db The db we are invoking the mechanism against
* @param {...object} param Parameters for the specific mechanism
* @param {authResultCallback} callback A callback function
*/
Pool.prototype.auth = function(mechanism) {
var self = this;
var args = Array.prototype.slice.call(arguments, 0);
var callback = args.pop();
// If we don't have the mechanism fail
if (self.authProviders[mechanism] == null && mechanism !== 'default') {
throw new MongoError(f('auth provider %s does not exist', mechanism));
}
// Signal that we are authenticating a new set of credentials
this.authenticating = true;
this.authenticatingTimestamp = new Date().getTime();
// Authenticate all live connections
function authenticateLiveConnections(self, args, cb) {
// Get the current viable connections
var connections = self.allConnections();
// Allow nothing else to use the connections while we authenticate them
self.availableConnections = [];
self.inUseConnections = [];
self.connectingConnections = [];
var connectionsCount = connections.length;
var error = null;
// No connections available, return
if (connectionsCount === 0) {
self.authenticating = false;
return callback(null);
}
// Authenticate the connections
for (var i = 0; i < connections.length; i++) {
authenticate(self, args, connections[i], function(err) {
connectionsCount = connectionsCount - 1;
// Store the error
if (err) error = err;
// Processed all connections
if (connectionsCount === 0) {
// Auth finished
self.authenticating = false;
// Add the connections back to available connections
self.availableConnections = self.availableConnections.concat(connections);
// We had an error, return it
if (error) {
// Log the error
if (self.logger.isError()) {
self.logger.error(
f(
'[%s] failed to authenticate against server %s:%s',
self.id,
self.options.host,
self.options.port
)
);
}
return cb(error);
}
cb(null);
}
});
}
}
// Wait for a logout in process to happen
function waitForLogout(self, cb) {
if (!self.loggingout) return cb();
setTimeout(function() {
waitForLogout(self, cb);
}, 1);
}
// Wait for loggout to finish
waitForLogout(self, function() {
// Authenticate all live connections
authenticateLiveConnections(self, args, function(err) {
// Credentials correctly stored in auth provider if successful
// Any new connections will now reauthenticate correctly
self.authenticating = false;
// Return after authentication connections
callback(err);
});
});
};
/**
* Logout all users against a database
* @method
* @param {string} dbName The database name
* @param {authResultCallback} callback A callback function
*/
Pool.prototype.logout = function(dbName, callback) {
var self = this;
if (typeof dbName !== 'string') {
throw new MongoError('logout method requires a db name as first argument');
}
if (typeof callback !== 'function') {
throw new MongoError('logout method requires a callback');
}
// Indicate logout in process
this.loggingout = true;
// Get all relevant connections
var connections = self.availableConnections.concat(self.inUseConnections);
var count = connections.length;
// Store any error
var error = null;
// Send logout command over all the connections
for (var i = 0; i < connections.length; i++) {
write(self)(
connections[i],
new Query(
this.options.bson,
f('%s.$cmd', dbName),
{ logout: 1 },
{ numberToSkip: 0, numberToReturn: 1 }
),
function(err) {
count = count - 1;
if (err) error = err;
if (count === 0) {
self.loggingout = false;
callback(error);
}
}
);
}
};
/**
* Unref the pool
* @method
*/
Pool.prototype.unref = function() {
// Get all the known connections
var connections = this.availableConnections
.concat(this.inUseConnections)
.concat(this.connectingConnections);
connections.forEach(function(c) {
c.unref();
});
};
// Events
var events = ['error', 'close', 'timeout', 'parseError', 'connect'];
// Destroy the connections
function destroy(self, connections) {
// Destroy all connections
connections.forEach(function(c) {
// Remove all listeners
for (var i = 0; i < events.length; i++) {
c.removeAllListeners(events[i]);
}
// Destroy connection
c.destroy();
});
// Zero out all connections
self.inUseConnections = [];
self.availableConnections = [];
self.nonAuthenticatedConnections = [];
self.connectingConnections = [];
// Set state to destroyed
stateTransition(self, DESTROYED);
}
/**
* Destroy pool
* @method
*/
Pool.prototype.destroy = function(force) {
var self = this;
// Do not try again if the pool is already dead
if (this.state === DESTROYED || self.state === DESTROYING) return;
// Set state to destroyed
stateTransition(this, DESTROYING);
// Are we force closing
if (force) {
// Get all the known connections
var connections = self.availableConnections
.concat(self.inUseConnections)
.concat(self.nonAuthenticatedConnections)
.concat(self.connectingConnections);
// Flush any remaining work items with
// an error
while (self.queue.length > 0) {
var workItem = self.queue.shift();
if (typeof workItem.cb === 'function') {
workItem.cb(new MongoError('Pool was force destroyed'));
}
}
// Destroy the topology
return destroy(self, connections);
}
// Clear out the reconnect if set
if (this.reconnectId) {
clearTimeout(this.reconnectId);
}
// If we have a reconnect connection running, close
// immediately
if (this.reconnectConnection) {
this.reconnectConnection.destroy();
}
// Wait for the operations to drain before we close the pool
function checkStatus() {
flushMonitoringOperations(self.queue);
if (self.queue.length === 0) {
// Get all the known connections
var connections = self.availableConnections
.concat(self.inUseConnections)
.concat(self.nonAuthenticatedConnections)
.concat(self.connectingConnections);
// Check if we have any in flight operations
for (var i = 0; i < connections.length; i++) {
// There is an operation still in flight, reschedule a
// check waiting for it to drain
if (connections[i].workItems.length > 0) {