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.

server.js 15KB

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