mongos.js 14 KB

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