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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. 'use strict';
  2. const EventEmitter = require('events');
  3. const MongoError = require('../error').MongoError;
  4. const Pool = require('../connection/pool');
  5. const relayEvents = require('../utils').relayEvents;
  6. const calculateDurationInMs = require('../utils').calculateDurationInMs;
  7. const Query = require('../connection/commands').Query;
  8. const TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support');
  9. const ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support');
  10. const BSON = require('../connection/utils').retrieveBSON();
  11. const createClientInfo = require('../topologies/shared').createClientInfo;
  12. const Logger = require('../connection/logger');
  13. const ServerDescription = require('./server_description').ServerDescription;
  14. const ReadPreference = require('../topologies/read_preference');
  15. const monitorServer = require('./monitoring').monitorServer;
  16. /**
  17. *
  18. * @fires Server#serverHeartbeatStarted
  19. * @fires Server#serverHeartbeatSucceeded
  20. * @fires Server#serverHeartbeatFailed
  21. */
  22. class Server extends EventEmitter {
  23. /**
  24. * Create a server
  25. *
  26. * @param {ServerDescription} description
  27. * @param {Object} options
  28. */
  29. constructor(description, options) {
  30. super();
  31. this.s = {
  32. // the server description
  33. description,
  34. // a saved copy of the incoming options
  35. options,
  36. // the server logger
  37. logger: Logger('Server', options),
  38. // the bson parser
  39. bson: options.bson || new BSON(),
  40. // client metadata for the initial handshake
  41. clientInfo: createClientInfo(options),
  42. // state variable to determine if there is an active server check in progress
  43. monitoring: false,
  44. // the connection pool
  45. pool: null
  46. };
  47. }
  48. get description() {
  49. return this.s.description;
  50. }
  51. get name() {
  52. return this.s.description.address;
  53. }
  54. /**
  55. * Initiate server connect
  56. *
  57. * @param {Array} [options.auth] Array of auth options to apply on connect
  58. */
  59. connect(options) {
  60. options = options || {};
  61. // do not allow connect to be called on anything that's not disconnected
  62. if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) {
  63. throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`);
  64. }
  65. // create a pool
  66. this.s.pool = new Pool(this, Object.assign(this.s.options, options, { bson: this.s.bson }));
  67. // Set up listeners
  68. this.s.pool.on('connect', connectEventHandler(this));
  69. this.s.pool.on('close', closeEventHandler(this));
  70. // this.s.pool.on('error', errorEventHandler(this));
  71. // this.s.pool.on('timeout', timeoutEventHandler(this));
  72. // this.s.pool.on('parseError', errorEventHandler(this));
  73. // this.s.pool.on('reconnect', reconnectEventHandler(this));
  74. // this.s.pool.on('reconnectFailed', errorEventHandler(this));
  75. // relay all command monitoring events
  76. relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']);
  77. // If auth settings have been provided, use them
  78. if (options.auth) {
  79. this.s.pool.connect.apply(this.s.pool, options.auth);
  80. return;
  81. }
  82. this.s.pool.connect();
  83. }
  84. /**
  85. * Destroy the server connection
  86. *
  87. * @param {Boolean} [options.emitClose=false] Emit close event on destroy
  88. * @param {Boolean} [options.emitDestroy=false] Emit destroy event on destroy
  89. * @param {Boolean} [options.force=false] Force destroy the pool
  90. */
  91. destroy(callback) {
  92. if (typeof callback === 'function') {
  93. callback(null, null);
  94. }
  95. }
  96. /**
  97. * Immediately schedule monitoring of this server. If there already an attempt being made
  98. * this will be a no-op.
  99. */
  100. monitor() {
  101. if (this.s.monitoring) return;
  102. if (this.s.monitorId) clearTimeout(this.s.monitorId);
  103. monitorServer(this);
  104. }
  105. /**
  106. * Execute a command
  107. *
  108. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  109. * @param {object} cmd The command hash
  110. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  111. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  112. * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys.
  113. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  114. * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document.
  115. * @param {ClientSession} [options.session=null] Session to use for the operation
  116. * @param {opResultCallback} callback A callback function
  117. */
  118. command(ns, cmd, options, callback) {
  119. if (typeof options === 'function') {
  120. (callback = options), (options = {}), (options = options || {});
  121. }
  122. const error = basicReadValidations(this, options);
  123. if (error) {
  124. return callback(error, null);
  125. }
  126. // Clone the options
  127. options = Object.assign({}, options, { wireProtocolCommand: false });
  128. // Debug log
  129. if (this.s.logger.isDebug()) {
  130. this.s.logger.debug(
  131. `executing command [${JSON.stringify({ ns, cmd, options })}] against ${this.name}`
  132. );
  133. }
  134. // Check if we have collation support
  135. if (this.description.maxWireVersion < 5 && cmd.collation) {
  136. callback(new MongoError(`server ${this.name} does not support collation`));
  137. return;
  138. }
  139. // Are we executing against a specific topology
  140. const topology = options.topology || {};
  141. // Create the query object
  142. const query = this.s.wireProtocolHandler.command(this.s.bson, ns, cmd, {}, topology, options);
  143. // Set slave OK of the query
  144. query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false;
  145. // write options
  146. const writeOptions = {
  147. raw: typeof options.raw === 'boolean' ? options.raw : false,
  148. promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
  149. promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
  150. promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,
  151. command: true,
  152. monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false,
  153. fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false,
  154. requestId: query.requestId,
  155. socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null,
  156. session: options.session || null
  157. };
  158. // write the operation to the pool
  159. this.s.pool.write(query, writeOptions, callback);
  160. }
  161. /**
  162. * Insert one or more documents
  163. * @method
  164. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  165. * @param {array} ops An array of documents to insert
  166. * @param {boolean} [options.ordered=true] Execute in order or out of order
  167. * @param {object} [options.writeConcern={}] Write concern for the operation
  168. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  169. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  170. * @param {ClientSession} [options.session=null] Session to use for the operation
  171. * @param {opResultCallback} callback A callback function
  172. */
  173. insert(ns, ops, options, callback) {
  174. executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback);
  175. }
  176. /**
  177. * Perform one or more update operations
  178. * @method
  179. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  180. * @param {array} ops An array of updates
  181. * @param {boolean} [options.ordered=true] Execute in order or out of order
  182. * @param {object} [options.writeConcern={}] Write concern for the operation
  183. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  184. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  185. * @param {ClientSession} [options.session=null] Session to use for the operation
  186. * @param {opResultCallback} callback A callback function
  187. */
  188. update(ns, ops, options, callback) {
  189. executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback);
  190. }
  191. /**
  192. * Perform one or more remove operations
  193. * @method
  194. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  195. * @param {array} ops An array of removes
  196. * @param {boolean} [options.ordered=true] Execute in order or out of order
  197. * @param {object} [options.writeConcern={}] Write concern for the operation
  198. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  199. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  200. * @param {ClientSession} [options.session=null] Session to use for the operation
  201. * @param {opResultCallback} callback A callback function
  202. */
  203. remove(ns, ops, options, callback) {
  204. executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback);
  205. }
  206. }
  207. function basicWriteValidations(server) {
  208. if (!server.s.pool) {
  209. return new MongoError('server instance is not connected');
  210. }
  211. if (server.s.pool.isDestroyed()) {
  212. return new MongoError('server instance pool was destroyed');
  213. }
  214. return null;
  215. }
  216. function basicReadValidations(server, options) {
  217. const error = basicWriteValidations(server, options);
  218. if (error) {
  219. return error;
  220. }
  221. if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {
  222. return new MongoError('readPreference must be an instance of ReadPreference');
  223. }
  224. }
  225. function executeWriteOperation(args, options, callback) {
  226. if (typeof options === 'function') (callback = options), (options = {});
  227. options = options || {};
  228. // TODO: once we drop Node 4, use destructuring either here or in arguments.
  229. const server = args.server;
  230. const op = args.op;
  231. const ns = args.ns;
  232. const ops = Array.isArray(args.ops) ? args.ops : [args.ops];
  233. const error = basicWriteValidations(server, options);
  234. if (error) {
  235. callback(error, null);
  236. return;
  237. }
  238. // Check if we have collation support
  239. if (server.description.maxWireVersion < 5 && options.collation) {
  240. callback(new MongoError(`server ${this.name} does not support collation`));
  241. return;
  242. }
  243. // Execute write
  244. return server.s.wireProtocolHandler[op](server.s.pool, ns, server.s.bson, ops, options, callback);
  245. }
  246. function saslSupportedMechs(options) {
  247. if (!options) {
  248. return {};
  249. }
  250. const authArray = options.auth || [];
  251. const authMechanism = authArray[0] || options.authMechanism;
  252. const authSource = authArray[1] || options.authSource || options.dbName || 'admin';
  253. const user = authArray[2] || options.user;
  254. if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') {
  255. return {};
  256. }
  257. if (!user) {
  258. return {};
  259. }
  260. return { saslSupportedMechs: `${authSource}.${user}` };
  261. }
  262. function extractIsMasterError(err, result) {
  263. if (err) return err;
  264. if (result && result.result && result.result.ok === 0) {
  265. return new MongoError(result.result);
  266. }
  267. }
  268. function executeServerHandshake(server, callback) {
  269. // construct an `ismaster` query
  270. const compressors =
  271. server.s.options.compression && server.s.options.compression.compressors
  272. ? server.s.options.compression.compressors
  273. : [];
  274. const queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true };
  275. const query = new Query(
  276. server.s.bson,
  277. 'admin.$cmd',
  278. Object.assign(
  279. { ismaster: true, client: server.s.clientInfo, compression: compressors },
  280. saslSupportedMechs(server.s.options)
  281. ),
  282. queryOptions
  283. );
  284. // execute the query
  285. server.s.pool.write(
  286. query,
  287. { socketTimeout: server.s.options.connectionTimeout || 2000 },
  288. callback
  289. );
  290. }
  291. function configureWireProtocolHandler(ismaster) {
  292. // 3.2 wire protocol handler
  293. if (ismaster.maxWireVersion >= 4) {
  294. return new ThreeTwoWireProtocolSupport();
  295. }
  296. // default to 2.6 wire protocol handler
  297. return new TwoSixWireProtocolSupport();
  298. }
  299. function connectEventHandler(server) {
  300. return function() {
  301. // log information of received information if in info mode
  302. // if (server.s.logger.isInfo()) {
  303. // var object = err instanceof MongoError ? JSON.stringify(err) : {};
  304. // server.s.logger.info(`server ${server.name} fired event ${event} out with message ${object}`);
  305. // }
  306. // begin initial server handshake
  307. const start = process.hrtime();
  308. executeServerHandshake(server, (err, response) => {
  309. // Set initial lastIsMasterMS - is this needed?
  310. server.s.lastIsMasterMS = calculateDurationInMs(start);
  311. const serverError = extractIsMasterError(err, response);
  312. if (serverError) {
  313. server.emit('error', serverError);
  314. return;
  315. }
  316. // extract the ismaster from the server response
  317. const isMaster = response.result;
  318. // compression negotation
  319. if (isMaster && isMaster.compression) {
  320. const localCompressionInfo = server.s.options.compression;
  321. const localCompressors = localCompressionInfo.compressors;
  322. for (var i = 0; i < localCompressors.length; i++) {
  323. if (isMaster.compression.indexOf(localCompressors[i]) > -1) {
  324. server.s.pool.options.agreedCompressor = localCompressors[i];
  325. break;
  326. }
  327. }
  328. if (localCompressionInfo.zlibCompressionLevel) {
  329. server.s.pool.options.zlibCompressionLevel = localCompressionInfo.zlibCompressionLevel;
  330. }
  331. }
  332. // configure the wire protocol handler
  333. server.s.wireProtocolHandler = configureWireProtocolHandler(isMaster);
  334. // log the connection event if requested
  335. if (server.s.logger.isInfo()) {
  336. server.s.logger.info(
  337. `server ${server.name} connected with ismaster [${JSON.stringify(isMaster)}]`
  338. );
  339. }
  340. // emit an event indicating that our description has changed
  341. server.emit(
  342. 'descriptionReceived',
  343. new ServerDescription(server.description.address, isMaster)
  344. );
  345. // emit a connect event
  346. server.emit('connect', isMaster);
  347. });
  348. };
  349. }
  350. function closeEventHandler(server) {
  351. return function() {
  352. server.emit('close');
  353. };
  354. }
  355. module.exports = Server;