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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. // Create the query object
  140. const query = this.s.wireProtocolHandler.command(this, ns, cmd, {}, options);
  141. // Set slave OK of the query
  142. query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false;
  143. // write options
  144. const writeOptions = {
  145. raw: typeof options.raw === 'boolean' ? options.raw : false,
  146. promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
  147. promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
  148. promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,
  149. command: true,
  150. monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false,
  151. fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false,
  152. requestId: query.requestId,
  153. socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null,
  154. session: options.session || null
  155. };
  156. // write the operation to the pool
  157. this.s.pool.write(query, writeOptions, callback);
  158. }
  159. /**
  160. * Insert one or more documents
  161. * @method
  162. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  163. * @param {array} ops An array of documents to insert
  164. * @param {boolean} [options.ordered=true] Execute in order or out of order
  165. * @param {object} [options.writeConcern={}] Write concern for the operation
  166. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  167. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  168. * @param {ClientSession} [options.session=null] Session to use for the operation
  169. * @param {opResultCallback} callback A callback function
  170. */
  171. insert(ns, ops, options, callback) {
  172. executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback);
  173. }
  174. /**
  175. * Perform one or more update operations
  176. * @method
  177. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  178. * @param {array} ops An array of updates
  179. * @param {boolean} [options.ordered=true] Execute in order or out of order
  180. * @param {object} [options.writeConcern={}] Write concern for the operation
  181. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  182. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  183. * @param {ClientSession} [options.session=null] Session to use for the operation
  184. * @param {opResultCallback} callback A callback function
  185. */
  186. update(ns, ops, options, callback) {
  187. executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback);
  188. }
  189. /**
  190. * Perform one or more remove operations
  191. * @method
  192. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  193. * @param {array} ops An array of removes
  194. * @param {boolean} [options.ordered=true] Execute in order or out of order
  195. * @param {object} [options.writeConcern={}] Write concern for the operation
  196. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  197. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  198. * @param {ClientSession} [options.session=null] Session to use for the operation
  199. * @param {opResultCallback} callback A callback function
  200. */
  201. remove(ns, ops, options, callback) {
  202. executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback);
  203. }
  204. }
  205. function basicWriteValidations(server) {
  206. if (!server.s.pool) {
  207. return new MongoError('server instance is not connected');
  208. }
  209. if (server.s.pool.isDestroyed()) {
  210. return new MongoError('server instance pool was destroyed');
  211. }
  212. return null;
  213. }
  214. function basicReadValidations(server, options) {
  215. const error = basicWriteValidations(server, options);
  216. if (error) {
  217. return error;
  218. }
  219. if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {
  220. return new MongoError('readPreference must be an instance of ReadPreference');
  221. }
  222. }
  223. function executeWriteOperation(args, options, callback) {
  224. if (typeof options === 'function') (callback = options), (options = {});
  225. options = options || {};
  226. // TODO: once we drop Node 4, use destructuring either here or in arguments.
  227. const server = args.server;
  228. const op = args.op;
  229. const ns = args.ns;
  230. const ops = Array.isArray(args.ops) ? args.ops : [args.ops];
  231. const error = basicWriteValidations(server, options);
  232. if (error) {
  233. callback(error, null);
  234. return;
  235. }
  236. // Check if we have collation support
  237. if (server.description.maxWireVersion < 5 && options.collation) {
  238. callback(new MongoError(`server ${this.name} does not support collation`));
  239. return;
  240. }
  241. // Execute write
  242. return server.s.wireProtocolHandler[op](server.s.pool, ns, server.s.bson, ops, options, callback);
  243. }
  244. function saslSupportedMechs(options) {
  245. if (!options) {
  246. return {};
  247. }
  248. const authArray = options.auth || [];
  249. const authMechanism = authArray[0] || options.authMechanism;
  250. const authSource = authArray[1] || options.authSource || options.dbName || 'admin';
  251. const user = authArray[2] || options.user;
  252. if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') {
  253. return {};
  254. }
  255. if (!user) {
  256. return {};
  257. }
  258. return { saslSupportedMechs: `${authSource}.${user}` };
  259. }
  260. function extractIsMasterError(err, result) {
  261. if (err) return err;
  262. if (result && result.result && result.result.ok === 0) {
  263. return new MongoError(result.result);
  264. }
  265. }
  266. function executeServerHandshake(server, callback) {
  267. // construct an `ismaster` query
  268. const compressors =
  269. server.s.options.compression && server.s.options.compression.compressors
  270. ? server.s.options.compression.compressors
  271. : [];
  272. const queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true };
  273. const query = new Query(
  274. server.s.bson,
  275. 'admin.$cmd',
  276. Object.assign(
  277. { ismaster: true, client: server.s.clientInfo, compression: compressors },
  278. saslSupportedMechs(server.s.options)
  279. ),
  280. queryOptions
  281. );
  282. // execute the query
  283. server.s.pool.write(
  284. query,
  285. { socketTimeout: server.s.options.connectionTimeout || 2000 },
  286. callback
  287. );
  288. }
  289. function configureWireProtocolHandler(ismaster) {
  290. // 3.2 wire protocol handler
  291. if (ismaster.maxWireVersion >= 4) {
  292. return new ThreeTwoWireProtocolSupport();
  293. }
  294. // default to 2.6 wire protocol handler
  295. return new TwoSixWireProtocolSupport();
  296. }
  297. function connectEventHandler(server) {
  298. return function() {
  299. // log information of received information if in info mode
  300. // if (server.s.logger.isInfo()) {
  301. // var object = err instanceof MongoError ? JSON.stringify(err) : {};
  302. // server.s.logger.info(`server ${server.name} fired event ${event} out with message ${object}`);
  303. // }
  304. // begin initial server handshake
  305. const start = process.hrtime();
  306. executeServerHandshake(server, (err, response) => {
  307. // Set initial lastIsMasterMS - is this needed?
  308. server.s.lastIsMasterMS = calculateDurationInMs(start);
  309. const serverError = extractIsMasterError(err, response);
  310. if (serverError) {
  311. server.emit('error', serverError);
  312. return;
  313. }
  314. // extract the ismaster from the server response
  315. const isMaster = response.result;
  316. // compression negotation
  317. if (isMaster && isMaster.compression) {
  318. const localCompressionInfo = server.s.options.compression;
  319. const localCompressors = localCompressionInfo.compressors;
  320. for (var i = 0; i < localCompressors.length; i++) {
  321. if (isMaster.compression.indexOf(localCompressors[i]) > -1) {
  322. server.s.pool.options.agreedCompressor = localCompressors[i];
  323. break;
  324. }
  325. }
  326. if (localCompressionInfo.zlibCompressionLevel) {
  327. server.s.pool.options.zlibCompressionLevel = localCompressionInfo.zlibCompressionLevel;
  328. }
  329. }
  330. // configure the wire protocol handler
  331. server.s.wireProtocolHandler = configureWireProtocolHandler(isMaster);
  332. // log the connection event if requested
  333. if (server.s.logger.isInfo()) {
  334. server.s.logger.info(
  335. `server ${server.name} connected with ismaster [${JSON.stringify(isMaster)}]`
  336. );
  337. }
  338. // emit an event indicating that our description has changed
  339. server.emit(
  340. 'descriptionReceived',
  341. new ServerDescription(server.description.address, isMaster)
  342. );
  343. // emit a connect event
  344. server.emit('connect', isMaster);
  345. });
  346. };
  347. }
  348. function closeEventHandler(server) {
  349. return function() {
  350. server.emit('close');
  351. };
  352. }
  353. module.exports = Server;