replset.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. 'use strict';
  2. const Server = require('./server');
  3. const Cursor = require('../cursor');
  4. const MongoError = require('../core').MongoError;
  5. const TopologyBase = require('./topology_base').TopologyBase;
  6. const Store = require('./topology_base').Store;
  7. const CReplSet = require('../core').ReplSet;
  8. const MAX_JS_INT = require('../utils').MAX_JS_INT;
  9. const translateOptions = require('../utils').translateOptions;
  10. const filterOptions = require('../utils').filterOptions;
  11. const mergeOptions = require('../utils').mergeOptions;
  12. /**
  13. * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is
  14. * used to construct connections.
  15. *
  16. * **ReplSet Should not be used, use MongoClient.connect**
  17. */
  18. // Allowed parameters
  19. var legalOptionNames = [
  20. 'ha',
  21. 'haInterval',
  22. 'replicaSet',
  23. 'rs_name',
  24. 'secondaryAcceptableLatencyMS',
  25. 'connectWithNoPrimary',
  26. 'poolSize',
  27. 'ssl',
  28. 'checkServerIdentity',
  29. 'sslValidate',
  30. 'sslCA',
  31. 'sslCert',
  32. 'ciphers',
  33. 'ecdhCurve',
  34. 'sslCRL',
  35. 'sslKey',
  36. 'sslPass',
  37. 'socketOptions',
  38. 'bufferMaxEntries',
  39. 'store',
  40. 'auto_reconnect',
  41. 'autoReconnect',
  42. 'emitError',
  43. 'keepAlive',
  44. 'keepAliveInitialDelay',
  45. 'noDelay',
  46. 'connectTimeoutMS',
  47. 'socketTimeoutMS',
  48. 'strategy',
  49. 'debug',
  50. 'family',
  51. 'loggerLevel',
  52. 'logger',
  53. 'reconnectTries',
  54. 'appname',
  55. 'domainsEnabled',
  56. 'servername',
  57. 'promoteLongs',
  58. 'promoteValues',
  59. 'promoteBuffers',
  60. 'bsonRegExp',
  61. 'maxStalenessSeconds',
  62. 'promiseLibrary',
  63. 'minSize',
  64. 'monitorCommands'
  65. ];
  66. /**
  67. * Creates a new ReplSet instance
  68. * @class
  69. * @deprecated
  70. * @param {Server[]} servers A seedlist of servers participating in the replicaset.
  71. * @param {object} [options] Optional settings.
  72. * @param {boolean} [options.ha=true] Turn on high availability monitoring.
  73. * @param {number} [options.haInterval=10000] Time between each replicaset status check.
  74. * @param {string} [options.replicaSet] The name of the replicaset to connect to.
  75. * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)
  76. * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
  77. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
  78. * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
  79. * @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.
  80. * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
  81. * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
  82. * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
  83. * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher.
  84. * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
  85. * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
  86. * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
  87. * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
  88. * @param {string} [options.servername] String containing the server name requested via TLS SNI.
  89. * @param {object} [options.socketOptions] Socket options
  90. * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
  91. * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled
  92. * @param {number} [options.socketOptions.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
  93. * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out
  94. * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out
  95. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
  96. * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed);
  97. * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
  98. * @fires ReplSet#connect
  99. * @fires ReplSet#ha
  100. * @fires ReplSet#joined
  101. * @fires ReplSet#left
  102. * @fires ReplSet#fullsetup
  103. * @fires ReplSet#open
  104. * @fires ReplSet#close
  105. * @fires ReplSet#error
  106. * @fires ReplSet#timeout
  107. * @fires ReplSet#parseError
  108. * @fires ReplSet#commandStarted
  109. * @fires ReplSet#commandSucceeded
  110. * @fires ReplSet#commandFailed
  111. * @property {string} parserType the parser type used (c++ or js).
  112. * @return {ReplSet} a ReplSet instance.
  113. */
  114. class ReplSet extends TopologyBase {
  115. constructor(servers, options) {
  116. super();
  117. options = options || {};
  118. var self = this;
  119. // Filter the options
  120. options = filterOptions(options, legalOptionNames);
  121. // Ensure all the instances are Server
  122. for (var i = 0; i < servers.length; i++) {
  123. if (!(servers[i] instanceof Server)) {
  124. throw MongoError.create({
  125. message: 'all seed list instances must be of the Server type',
  126. driver: true
  127. });
  128. }
  129. }
  130. // Stored options
  131. var storeOptions = {
  132. force: false,
  133. bufferMaxEntries:
  134. typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT
  135. };
  136. // Shared global store
  137. var store = options.store || new Store(self, storeOptions);
  138. // Build seed list
  139. var seedlist = servers.map(function(x) {
  140. return { host: x.host, port: x.port };
  141. });
  142. // Clone options
  143. var clonedOptions = mergeOptions(
  144. {},
  145. {
  146. disconnectHandler: store,
  147. cursorFactory: Cursor,
  148. reconnect: false,
  149. emitError: typeof options.emitError === 'boolean' ? options.emitError : true,
  150. size: typeof options.poolSize === 'number' ? options.poolSize : 5,
  151. monitorCommands:
  152. typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false
  153. }
  154. );
  155. // Translate any SSL options and other connectivity options
  156. clonedOptions = translateOptions(clonedOptions, options);
  157. // Socket options
  158. var socketOptions =
  159. options.socketOptions && Object.keys(options.socketOptions).length > 0
  160. ? options.socketOptions
  161. : options;
  162. // Translate all the options to the core types
  163. clonedOptions = translateOptions(clonedOptions, socketOptions);
  164. // Create the ReplSet
  165. var coreTopology = new CReplSet(seedlist, clonedOptions);
  166. // Listen to reconnect event
  167. coreTopology.on('reconnect', function() {
  168. self.emit('reconnect');
  169. store.execute();
  170. });
  171. // Internal state
  172. this.s = {
  173. // Replicaset
  174. coreTopology: coreTopology,
  175. // Server capabilities
  176. sCapabilities: null,
  177. // Debug tag
  178. tag: options.tag,
  179. // Store options
  180. storeOptions: storeOptions,
  181. // Cloned options
  182. clonedOptions: clonedOptions,
  183. // Store
  184. store: store,
  185. // Options
  186. options: options,
  187. // Server Session Pool
  188. sessionPool: null,
  189. // Active client sessions
  190. sessions: new Set(),
  191. // Promise library
  192. promiseLibrary: options.promiseLibrary || Promise
  193. };
  194. // Debug
  195. if (clonedOptions.debug) {
  196. // Last ismaster
  197. Object.defineProperty(this, 'replset', {
  198. enumerable: true,
  199. get: function() {
  200. return coreTopology;
  201. }
  202. });
  203. }
  204. }
  205. // Connect method
  206. connect(_options, callback) {
  207. var self = this;
  208. if ('function' === typeof _options) (callback = _options), (_options = {});
  209. if (_options == null) _options = {};
  210. if (!('function' === typeof callback)) callback = null;
  211. _options = Object.assign({}, this.s.clonedOptions, _options);
  212. self.s.options = _options;
  213. // Update bufferMaxEntries
  214. self.s.storeOptions.bufferMaxEntries =
  215. typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;
  216. // Actual handler
  217. var errorHandler = function(event) {
  218. return function(err) {
  219. if (event !== 'error') {
  220. self.emit(event, err);
  221. }
  222. };
  223. };
  224. // Clear out all the current handlers left over
  225. var events = [
  226. 'timeout',
  227. 'error',
  228. 'close',
  229. 'serverOpening',
  230. 'serverDescriptionChanged',
  231. 'serverHeartbeatStarted',
  232. 'serverHeartbeatSucceeded',
  233. 'serverHeartbeatFailed',
  234. 'serverClosed',
  235. 'topologyOpening',
  236. 'topologyClosed',
  237. 'topologyDescriptionChanged',
  238. 'commandStarted',
  239. 'commandSucceeded',
  240. 'commandFailed',
  241. 'joined',
  242. 'left',
  243. 'ping',
  244. 'ha'
  245. ];
  246. events.forEach(function(e) {
  247. self.s.coreTopology.removeAllListeners(e);
  248. });
  249. // relay the event
  250. var relay = function(event) {
  251. return function(t, server) {
  252. self.emit(event, t, server);
  253. };
  254. };
  255. // Replset events relay
  256. var replsetRelay = function(event) {
  257. return function(t, server) {
  258. self.emit(event, t, server.lastIsMaster(), server);
  259. };
  260. };
  261. // Relay ha
  262. var relayHa = function(t, state) {
  263. self.emit('ha', t, state);
  264. if (t === 'start') {
  265. self.emit('ha_connect', t, state);
  266. } else if (t === 'end') {
  267. self.emit('ha_ismaster', t, state);
  268. }
  269. };
  270. // Set up serverConfig listeners
  271. self.s.coreTopology.on('joined', replsetRelay('joined'));
  272. self.s.coreTopology.on('left', relay('left'));
  273. self.s.coreTopology.on('ping', relay('ping'));
  274. self.s.coreTopology.on('ha', relayHa);
  275. // Set up SDAM listeners
  276. self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));
  277. self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));
  278. self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));
  279. self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));
  280. self.s.coreTopology.on('serverOpening', relay('serverOpening'));
  281. self.s.coreTopology.on('serverClosed', relay('serverClosed'));
  282. self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));
  283. self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));
  284. self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));
  285. self.s.coreTopology.on('commandStarted', relay('commandStarted'));
  286. self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));
  287. self.s.coreTopology.on('commandFailed', relay('commandFailed'));
  288. self.s.coreTopology.on('fullsetup', function() {
  289. self.emit('fullsetup', self, self);
  290. });
  291. self.s.coreTopology.on('all', function() {
  292. self.emit('all', null, self);
  293. });
  294. // Connect handler
  295. var connectHandler = function() {
  296. // Set up listeners
  297. self.s.coreTopology.once('timeout', errorHandler('timeout'));
  298. self.s.coreTopology.once('error', errorHandler('error'));
  299. self.s.coreTopology.once('close', errorHandler('close'));
  300. // Emit open event
  301. self.emit('open', null, self);
  302. // Return correctly
  303. try {
  304. callback(null, self);
  305. } catch (err) {
  306. process.nextTick(function() {
  307. throw err;
  308. });
  309. }
  310. };
  311. // Error handler
  312. var connectErrorHandler = function() {
  313. return function(err) {
  314. ['timeout', 'error', 'close'].forEach(function(e) {
  315. self.s.coreTopology.removeListener(e, connectErrorHandler);
  316. });
  317. self.s.coreTopology.removeListener('connect', connectErrorHandler);
  318. // Destroy the replset
  319. self.s.coreTopology.destroy();
  320. // Try to callback
  321. try {
  322. callback(err);
  323. } catch (err) {
  324. if (!self.s.coreTopology.isConnected())
  325. process.nextTick(function() {
  326. throw err;
  327. });
  328. }
  329. };
  330. };
  331. // Set up listeners
  332. self.s.coreTopology.once('timeout', connectErrorHandler('timeout'));
  333. self.s.coreTopology.once('error', connectErrorHandler('error'));
  334. self.s.coreTopology.once('close', connectErrorHandler('close'));
  335. self.s.coreTopology.once('connect', connectHandler);
  336. // Start connection
  337. self.s.coreTopology.connect(_options);
  338. }
  339. close(forceClosed, callback) {
  340. ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e));
  341. super.close(forceClosed, callback);
  342. }
  343. }
  344. Object.defineProperty(ReplSet.prototype, 'haInterval', {
  345. enumerable: true,
  346. get: function() {
  347. return this.s.coreTopology.s.haInterval;
  348. }
  349. });
  350. /**
  351. * A replset connect event, used to verify that the connection is up and running
  352. *
  353. * @event ReplSet#connect
  354. * @type {ReplSet}
  355. */
  356. /**
  357. * The replset high availability event
  358. *
  359. * @event ReplSet#ha
  360. * @type {function}
  361. * @param {string} type The stage in the high availability event (start|end)
  362. * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only
  363. * @param {number} data.id The id for this high availability request
  364. * @param {object} data.state An object containing the information about the current replicaset
  365. */
  366. /**
  367. * A server member left the replicaset
  368. *
  369. * @event ReplSet#left
  370. * @type {function}
  371. * @param {string} type The type of member that left (primary|secondary|arbiter)
  372. * @param {Server} server The server object that left
  373. */
  374. /**
  375. * A server member joined the replicaset
  376. *
  377. * @event ReplSet#joined
  378. * @type {function}
  379. * @param {string} type The type of member that joined (primary|secondary|arbiter)
  380. * @param {Server} server The server object that joined
  381. */
  382. /**
  383. * ReplSet open event, emitted when replicaset can start processing commands.
  384. *
  385. * @event ReplSet#open
  386. * @type {Replset}
  387. */
  388. /**
  389. * ReplSet fullsetup event, emitted when all servers in the topology have been connected to.
  390. *
  391. * @event ReplSet#fullsetup
  392. * @type {Replset}
  393. */
  394. /**
  395. * ReplSet close event
  396. *
  397. * @event ReplSet#close
  398. * @type {object}
  399. */
  400. /**
  401. * ReplSet error event, emitted if there is an error listener.
  402. *
  403. * @event ReplSet#error
  404. * @type {MongoError}
  405. */
  406. /**
  407. * ReplSet timeout event
  408. *
  409. * @event ReplSet#timeout
  410. * @type {object}
  411. */
  412. /**
  413. * ReplSet parseError event
  414. *
  415. * @event ReplSet#parseError
  416. * @type {object}
  417. */
  418. /**
  419. * An event emitted indicating a command was started, if command monitoring is enabled
  420. *
  421. * @event ReplSet#commandStarted
  422. * @type {object}
  423. */
  424. /**
  425. * An event emitted indicating a command succeeded, if command monitoring is enabled
  426. *
  427. * @event ReplSet#commandSucceeded
  428. * @type {object}
  429. */
  430. /**
  431. * An event emitted indicating a command failed, if command monitoring is enabled
  432. *
  433. * @event ReplSet#commandFailed
  434. * @type {object}
  435. */
  436. module.exports = ReplSet;