Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mongos.js 15KB

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