server.js 14 KB

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