pool.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. 'use strict';
  2. const inherits = require('util').inherits;
  3. const EventEmitter = require('events').EventEmitter;
  4. const MongoError = require('../error').MongoError;
  5. const MongoNetworkError = require('../error').MongoNetworkError;
  6. const MongoWriteConcernError = require('../error').MongoWriteConcernError;
  7. const Logger = require('./logger');
  8. const f = require('util').format;
  9. const Msg = require('./msg').Msg;
  10. const CommandResult = require('./command_result');
  11. const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE;
  12. const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE;
  13. const opcodes = require('../wireprotocol/shared').opcodes;
  14. const compress = require('../wireprotocol/compression').compress;
  15. const compressorIDs = require('../wireprotocol/compression').compressorIDs;
  16. const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands;
  17. const apm = require('./apm');
  18. const Buffer = require('safe-buffer').Buffer;
  19. const connect = require('./connect');
  20. const updateSessionFromResponse = require('../sessions').updateSessionFromResponse;
  21. var DISCONNECTED = 'disconnected';
  22. var CONNECTING = 'connecting';
  23. var CONNECTED = 'connected';
  24. var DESTROYING = 'destroying';
  25. var DESTROYED = 'destroyed';
  26. var _id = 0;
  27. /**
  28. * Creates a new Pool instance
  29. * @class
  30. * @param {string} options.host The server host
  31. * @param {number} options.port The server port
  32. * @param {number} [options.size=5] Max server connection pool size
  33. * @param {number} [options.minSize=0] Minimum server connection pool size
  34. * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection
  35. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  36. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  37. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
  38. * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled
  39. * @param {boolean} [options.noDelay=true] TCP Connection no delay
  40. * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
  41. * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting
  42. * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket
  43. * @param {boolean} [options.ssl=false] Use SSL for connection
  44. * @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.
  45. * @param {Buffer} [options.ca] SSL Certificate store binary buffer
  46. * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer
  47. * @param {Buffer} [options.cert] SSL Certificate binary buffer
  48. * @param {Buffer} [options.key] SSL Key file binary buffer
  49. * @param {string} [options.passPhrase] SSL Certificate pass phrase
  50. * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates
  51. * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits
  52. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  53. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  54. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
  55. * @fires Pool#connect
  56. * @fires Pool#close
  57. * @fires Pool#error
  58. * @fires Pool#timeout
  59. * @fires Pool#parseError
  60. * @return {Pool} A cursor instance
  61. */
  62. var Pool = function(topology, options) {
  63. // Add event listener
  64. EventEmitter.call(this);
  65. // Store topology for later use
  66. this.topology = topology;
  67. // Add the options
  68. this.options = Object.assign(
  69. {
  70. // Host and port settings
  71. host: 'localhost',
  72. port: 27017,
  73. // Pool default max size
  74. size: 5,
  75. // Pool default min size
  76. minSize: 0,
  77. // socket settings
  78. connectionTimeout: 30000,
  79. socketTimeout: 360000,
  80. keepAlive: true,
  81. keepAliveInitialDelay: 300000,
  82. noDelay: true,
  83. // SSL Settings
  84. ssl: false,
  85. checkServerIdentity: true,
  86. ca: null,
  87. crl: null,
  88. cert: null,
  89. key: null,
  90. passPhrase: null,
  91. rejectUnauthorized: false,
  92. promoteLongs: true,
  93. promoteValues: true,
  94. promoteBuffers: false,
  95. // Reconnection options
  96. reconnect: true,
  97. reconnectInterval: 1000,
  98. reconnectTries: 30,
  99. // Enable domains
  100. domainsEnabled: false
  101. },
  102. options
  103. );
  104. // Identification information
  105. this.id = _id++;
  106. // Current reconnect retries
  107. this.retriesLeft = this.options.reconnectTries;
  108. this.reconnectId = null;
  109. // No bson parser passed in
  110. if (
  111. !options.bson ||
  112. (options.bson &&
  113. (typeof options.bson.serialize !== 'function' ||
  114. typeof options.bson.deserialize !== 'function'))
  115. ) {
  116. throw new Error('must pass in valid bson parser');
  117. }
  118. // Logger instance
  119. this.logger = Logger('Pool', options);
  120. // Pool state
  121. this.state = DISCONNECTED;
  122. // Connections
  123. this.availableConnections = [];
  124. this.inUseConnections = [];
  125. this.connectingConnections = 0;
  126. // Currently executing
  127. this.executing = false;
  128. // Operation work queue
  129. this.queue = [];
  130. // Contains the reconnect connection
  131. this.reconnectConnection = null;
  132. // Number of consecutive timeouts caught
  133. this.numberOfConsecutiveTimeouts = 0;
  134. // Current pool Index
  135. this.connectionIndex = 0;
  136. // event handlers
  137. const pool = this;
  138. this._messageHandler = messageHandler(this);
  139. this._connectionCloseHandler = function(err) {
  140. const connection = this;
  141. connectionFailureHandler(pool, 'close', err, connection);
  142. };
  143. this._connectionErrorHandler = function(err) {
  144. const connection = this;
  145. connectionFailureHandler(pool, 'error', err, connection);
  146. };
  147. this._connectionTimeoutHandler = function(err) {
  148. const connection = this;
  149. connectionFailureHandler(pool, 'timeout', err, connection);
  150. };
  151. this._connectionParseErrorHandler = function(err) {
  152. const connection = this;
  153. connectionFailureHandler(pool, 'parseError', err, connection);
  154. };
  155. };
  156. inherits(Pool, EventEmitter);
  157. Object.defineProperty(Pool.prototype, 'size', {
  158. enumerable: true,
  159. get: function() {
  160. return this.options.size;
  161. }
  162. });
  163. Object.defineProperty(Pool.prototype, 'minSize', {
  164. enumerable: true,
  165. get: function() {
  166. return this.options.minSize;
  167. }
  168. });
  169. Object.defineProperty(Pool.prototype, 'connectionTimeout', {
  170. enumerable: true,
  171. get: function() {
  172. return this.options.connectionTimeout;
  173. }
  174. });
  175. Object.defineProperty(Pool.prototype, 'socketTimeout', {
  176. enumerable: true,
  177. get: function() {
  178. return this.options.socketTimeout;
  179. }
  180. });
  181. function stateTransition(self, newState) {
  182. var legalTransitions = {
  183. disconnected: [CONNECTING, DESTROYING, DISCONNECTED],
  184. connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED],
  185. connected: [CONNECTED, DISCONNECTED, DESTROYING],
  186. destroying: [DESTROYING, DESTROYED],
  187. destroyed: [DESTROYED]
  188. };
  189. // Get current state
  190. var legalStates = legalTransitions[self.state];
  191. if (legalStates && legalStates.indexOf(newState) !== -1) {
  192. self.emit('stateChanged', self.state, newState);
  193. self.state = newState;
  194. } else {
  195. self.logger.error(
  196. f(
  197. 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]',
  198. self.id,
  199. self.state,
  200. newState,
  201. legalStates
  202. )
  203. );
  204. }
  205. }
  206. function connectionFailureHandler(pool, event, err, conn) {
  207. if (conn) {
  208. if (conn._connectionFailHandled) return;
  209. conn._connectionFailHandled = true;
  210. conn.destroy();
  211. // Remove the connection
  212. removeConnection(pool, conn);
  213. // Flush all work Items on this connection
  214. while (conn.workItems.length > 0) {
  215. const workItem = conn.workItems.shift();
  216. if (workItem.cb) workItem.cb(err);
  217. }
  218. }
  219. // Did we catch a timeout, increment the numberOfConsecutiveTimeouts
  220. if (event === 'timeout') {
  221. pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1;
  222. // Have we timed out more than reconnectTries in a row ?
  223. // Force close the pool as we are trying to connect to tcp sink hole
  224. if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) {
  225. pool.numberOfConsecutiveTimeouts = 0;
  226. // Destroy all connections and pool
  227. pool.destroy(true);
  228. // Emit close event
  229. return pool.emit('close', pool);
  230. }
  231. }
  232. // No more socket available propegate the event
  233. if (pool.socketCount() === 0) {
  234. if (pool.state !== DESTROYED && pool.state !== DESTROYING) {
  235. stateTransition(pool, DISCONNECTED);
  236. }
  237. // Do not emit error events, they are always close events
  238. // do not trigger the low level error handler in node
  239. event = event === 'error' ? 'close' : event;
  240. pool.emit(event, err);
  241. }
  242. // Start reconnection attempts
  243. if (!pool.reconnectId && pool.options.reconnect) {
  244. pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval);
  245. }
  246. // Do we need to do anything to maintain the minimum pool size
  247. const totalConnections = totalConnectionCount(pool);
  248. if (totalConnections < pool.minSize) {
  249. _createConnection(pool);
  250. }
  251. }
  252. function attemptReconnect(self) {
  253. return function() {
  254. self.emit('attemptReconnect', self);
  255. if (self.state === DESTROYED || self.state === DESTROYING) return;
  256. // We are connected do not try again
  257. if (self.isConnected()) {
  258. self.reconnectId = null;
  259. return;
  260. }
  261. self.connectingConnections++;
  262. connect(self.options, (err, connection) => {
  263. self.connectingConnections--;
  264. if (err) {
  265. if (self.logger.isDebug()) {
  266. self.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`);
  267. }
  268. self.retriesLeft = self.retriesLeft - 1;
  269. if (self.retriesLeft <= 0) {
  270. self.destroy();
  271. self.emit(
  272. 'reconnectFailed',
  273. new MongoNetworkError(
  274. f(
  275. 'failed to reconnect after %s attempts with interval %s ms',
  276. self.options.reconnectTries,
  277. self.options.reconnectInterval
  278. )
  279. )
  280. );
  281. } else {
  282. self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval);
  283. }
  284. return;
  285. }
  286. if (self.state === DESTROYED || self.state === DESTROYING) {
  287. return connection.destroy();
  288. }
  289. self.reconnectId = null;
  290. handlers.forEach(event => connection.removeAllListeners(event));
  291. connection.on('error', self._connectionErrorHandler);
  292. connection.on('close', self._connectionCloseHandler);
  293. connection.on('timeout', self._connectionTimeoutHandler);
  294. connection.on('parseError', self._connectionParseErrorHandler);
  295. connection.on('message', self._messageHandler);
  296. self.retriesLeft = self.options.reconnectTries;
  297. self.availableConnections.push(connection);
  298. self.reconnectConnection = null;
  299. self.emit('reconnect', self);
  300. _execute(self)();
  301. });
  302. };
  303. }
  304. function moveConnectionBetween(connection, from, to) {
  305. var index = from.indexOf(connection);
  306. // Move the connection from connecting to available
  307. if (index !== -1) {
  308. from.splice(index, 1);
  309. to.push(connection);
  310. }
  311. }
  312. function messageHandler(self) {
  313. return function(message, connection) {
  314. // workItem to execute
  315. var workItem = null;
  316. // Locate the workItem
  317. for (var i = 0; i < connection.workItems.length; i++) {
  318. if (connection.workItems[i].requestId === message.responseTo) {
  319. // Get the callback
  320. workItem = connection.workItems[i];
  321. // Remove from list of workItems
  322. connection.workItems.splice(i, 1);
  323. }
  324. }
  325. if (workItem && workItem.monitoring) {
  326. moveConnectionBetween(connection, self.inUseConnections, self.availableConnections);
  327. }
  328. // Reset timeout counter
  329. self.numberOfConsecutiveTimeouts = 0;
  330. // Reset the connection timeout if we modified it for
  331. // this operation
  332. if (workItem && workItem.socketTimeout) {
  333. connection.resetSocketTimeout();
  334. }
  335. // Log if debug enabled
  336. if (self.logger.isDebug()) {
  337. self.logger.debug(
  338. f(
  339. 'message [%s] received from %s:%s',
  340. message.raw.toString('hex'),
  341. self.options.host,
  342. self.options.port
  343. )
  344. );
  345. }
  346. function handleOperationCallback(self, cb, err, result) {
  347. // No domain enabled
  348. if (!self.options.domainsEnabled) {
  349. return process.nextTick(function() {
  350. return cb(err, result);
  351. });
  352. }
  353. // Domain enabled just call the callback
  354. cb(err, result);
  355. }
  356. // Keep executing, ensure current message handler does not stop execution
  357. if (!self.executing) {
  358. process.nextTick(function() {
  359. _execute(self)();
  360. });
  361. }
  362. // Time to dispatch the message if we have a callback
  363. if (workItem && !workItem.immediateRelease) {
  364. try {
  365. // Parse the message according to the provided options
  366. message.parse(workItem);
  367. } catch (err) {
  368. return handleOperationCallback(self, workItem.cb, new MongoError(err));
  369. }
  370. if (message.documents[0]) {
  371. const document = message.documents[0];
  372. const session = workItem.session;
  373. if (session) {
  374. updateSessionFromResponse(session, document);
  375. }
  376. if (document.$clusterTime) {
  377. self.topology.clusterTime = document.$clusterTime;
  378. }
  379. }
  380. // Establish if we have an error
  381. if (workItem.command && message.documents[0]) {
  382. const responseDoc = message.documents[0];
  383. if (responseDoc.writeConcernError) {
  384. const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc);
  385. return handleOperationCallback(self, workItem.cb, err);
  386. }
  387. if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) {
  388. return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc));
  389. }
  390. }
  391. // Add the connection details
  392. message.hashedName = connection.hashedName;
  393. // Return the documents
  394. handleOperationCallback(
  395. self,
  396. workItem.cb,
  397. null,
  398. new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message)
  399. );
  400. }
  401. };
  402. }
  403. /**
  404. * Return the total socket count in the pool.
  405. * @method
  406. * @return {Number} The number of socket available.
  407. */
  408. Pool.prototype.socketCount = function() {
  409. return this.availableConnections.length + this.inUseConnections.length;
  410. // + this.connectingConnections.length;
  411. };
  412. function totalConnectionCount(pool) {
  413. return (
  414. pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections
  415. );
  416. }
  417. /**
  418. * Return all pool connections
  419. * @method
  420. * @return {Connection[]} The pool connections
  421. */
  422. Pool.prototype.allConnections = function() {
  423. return this.availableConnections.concat(this.inUseConnections);
  424. };
  425. /**
  426. * Get a pool connection (round-robin)
  427. * @method
  428. * @return {Connection}
  429. */
  430. Pool.prototype.get = function() {
  431. return this.allConnections()[0];
  432. };
  433. /**
  434. * Is the pool connected
  435. * @method
  436. * @return {boolean}
  437. */
  438. Pool.prototype.isConnected = function() {
  439. // We are in a destroyed state
  440. if (this.state === DESTROYED || this.state === DESTROYING) {
  441. return false;
  442. }
  443. // Get connections
  444. var connections = this.availableConnections.concat(this.inUseConnections);
  445. // Check if we have any connected connections
  446. for (var i = 0; i < connections.length; i++) {
  447. if (connections[i].isConnected()) return true;
  448. }
  449. // Not connected
  450. return false;
  451. };
  452. /**
  453. * Was the pool destroyed
  454. * @method
  455. * @return {boolean}
  456. */
  457. Pool.prototype.isDestroyed = function() {
  458. return this.state === DESTROYED || this.state === DESTROYING;
  459. };
  460. /**
  461. * Is the pool in a disconnected state
  462. * @method
  463. * @return {boolean}
  464. */
  465. Pool.prototype.isDisconnected = function() {
  466. return this.state === DISCONNECTED;
  467. };
  468. /**
  469. * Connect pool
  470. */
  471. Pool.prototype.connect = function() {
  472. if (this.state !== DISCONNECTED) {
  473. throw new MongoError('connection in unlawful state ' + this.state);
  474. }
  475. const self = this;
  476. stateTransition(this, CONNECTING);
  477. self.connectingConnections++;
  478. connect(self.options, (err, connection) => {
  479. self.connectingConnections--;
  480. if (err) {
  481. if (self.logger.isDebug()) {
  482. self.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`);
  483. }
  484. if (self.state === CONNECTING) {
  485. self.emit('error', err);
  486. }
  487. return;
  488. }
  489. if (self.state === DESTROYED || self.state === DESTROYING) {
  490. return self.destroy();
  491. }
  492. // attach event handlers
  493. connection.on('error', self._connectionErrorHandler);
  494. connection.on('close', self._connectionCloseHandler);
  495. connection.on('timeout', self._connectionTimeoutHandler);
  496. connection.on('parseError', self._connectionParseErrorHandler);
  497. connection.on('message', self._messageHandler);
  498. // If we are in a topology, delegate the auth to it
  499. // This is to avoid issues where we would auth against an
  500. // arbiter
  501. if (self.options.inTopology) {
  502. stateTransition(self, CONNECTED);
  503. self.availableConnections.push(connection);
  504. return self.emit('connect', self, connection);
  505. }
  506. if (self.state === DESTROYED || self.state === DESTROYING) {
  507. return self.destroy();
  508. }
  509. if (err) {
  510. self.destroy();
  511. return self.emit('error', err);
  512. }
  513. stateTransition(self, CONNECTED);
  514. self.availableConnections.push(connection);
  515. if (self.minSize) {
  516. for (let i = 0; i < self.minSize; i++) {
  517. _createConnection(self);
  518. }
  519. }
  520. self.emit('connect', self, connection);
  521. });
  522. };
  523. /**
  524. * Authenticate using a specified mechanism
  525. * @param {authResultCallback} callback A callback function
  526. */
  527. Pool.prototype.auth = function(credentials, callback) {
  528. if (typeof callback === 'function') callback(null, null);
  529. };
  530. /**
  531. * Logout all users against a database
  532. * @param {authResultCallback} callback A callback function
  533. */
  534. Pool.prototype.logout = function(dbName, callback) {
  535. if (typeof callback === 'function') callback(null, null);
  536. };
  537. /**
  538. * Unref the pool
  539. * @method
  540. */
  541. Pool.prototype.unref = function() {
  542. // Get all the known connections
  543. var connections = this.availableConnections.concat(this.inUseConnections);
  544. connections.forEach(function(c) {
  545. c.unref();
  546. });
  547. };
  548. // Events
  549. var events = ['error', 'close', 'timeout', 'parseError', 'connect', 'message'];
  550. // Destroy the connections
  551. function destroy(self, connections, options, callback) {
  552. let connectionCount = connections.length;
  553. function connectionDestroyed() {
  554. connectionCount--;
  555. if (connectionCount > 0) {
  556. return;
  557. }
  558. // Zero out all connections
  559. self.inUseConnections = [];
  560. self.availableConnections = [];
  561. self.connectingConnections = 0;
  562. // Set state to destroyed
  563. stateTransition(self, DESTROYED);
  564. if (typeof callback === 'function') {
  565. callback(null, null);
  566. }
  567. }
  568. if (connectionCount === 0) {
  569. connectionDestroyed();
  570. return;
  571. }
  572. // Destroy all connections
  573. connections.forEach(conn => {
  574. for (var i = 0; i < events.length; i++) {
  575. conn.removeAllListeners(events[i]);
  576. }
  577. conn.destroy(options, connectionDestroyed);
  578. });
  579. }
  580. /**
  581. * Destroy pool
  582. * @method
  583. */
  584. Pool.prototype.destroy = function(force, callback) {
  585. var self = this;
  586. // Do not try again if the pool is already dead
  587. if (this.state === DESTROYED || self.state === DESTROYING) {
  588. if (typeof callback === 'function') callback(null, null);
  589. return;
  590. }
  591. // Set state to destroyed
  592. stateTransition(this, DESTROYING);
  593. // Are we force closing
  594. if (force) {
  595. // Get all the known connections
  596. var connections = self.availableConnections.concat(self.inUseConnections);
  597. // Flush any remaining work items with
  598. // an error
  599. while (self.queue.length > 0) {
  600. var workItem = self.queue.shift();
  601. if (typeof workItem.cb === 'function') {
  602. workItem.cb(new MongoError('Pool was force destroyed'));
  603. }
  604. }
  605. // Destroy the topology
  606. return destroy(self, connections, { force: true }, callback);
  607. }
  608. // Clear out the reconnect if set
  609. if (this.reconnectId) {
  610. clearTimeout(this.reconnectId);
  611. }
  612. // If we have a reconnect connection running, close
  613. // immediately
  614. if (this.reconnectConnection) {
  615. this.reconnectConnection.destroy();
  616. }
  617. // Wait for the operations to drain before we close the pool
  618. function checkStatus() {
  619. flushMonitoringOperations(self.queue);
  620. if (self.queue.length === 0) {
  621. // Get all the known connections
  622. var connections = self.availableConnections.concat(self.inUseConnections);
  623. // Check if we have any in flight operations
  624. for (var i = 0; i < connections.length; i++) {
  625. // There is an operation still in flight, reschedule a
  626. // check waiting for it to drain
  627. if (connections[i].workItems.length > 0) {
  628. return setTimeout(checkStatus, 1);
  629. }
  630. }
  631. destroy(self, connections, { force: false }, callback);
  632. // } else if (self.queue.length > 0 && !this.reconnectId) {
  633. } else {
  634. // Ensure we empty the queue
  635. _execute(self)();
  636. // Set timeout
  637. setTimeout(checkStatus, 1);
  638. }
  639. }
  640. // Initiate drain of operations
  641. checkStatus();
  642. };
  643. /**
  644. * Reset all connections of this pool
  645. *
  646. * @param {function} [callback]
  647. */
  648. Pool.prototype.reset = function(callback) {
  649. // this.destroy(true, err => {
  650. // if (err && typeof callback === 'function') {
  651. // callback(err, null);
  652. // return;
  653. // }
  654. // stateTransition(this, DISCONNECTED);
  655. // this.connect();
  656. // if (typeof callback === 'function') callback(null, null);
  657. // });
  658. if (typeof callback === 'function') callback();
  659. };
  660. // Prepare the buffer that Pool.prototype.write() uses to send to the server
  661. function serializeCommand(self, command, callback) {
  662. const originalCommandBuffer = command.toBin();
  663. // Check whether we and the server have agreed to use a compressor
  664. const shouldCompress = !!self.options.agreedCompressor;
  665. if (!shouldCompress || !canCompress(command)) {
  666. return callback(null, originalCommandBuffer);
  667. }
  668. // Transform originalCommandBuffer into OP_COMPRESSED
  669. const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer);
  670. const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);
  671. // Extract information needed for OP_COMPRESSED from the uncompressed message
  672. const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);
  673. // Compress the message body
  674. compress(self, messageToBeCompressed, function(err, compressedMessage) {
  675. if (err) return callback(err, null);
  676. // Create the msgHeader of OP_COMPRESSED
  677. const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);
  678. msgHeader.writeInt32LE(
  679. MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length,
  680. 0
  681. ); // messageLength
  682. msgHeader.writeInt32LE(command.requestId, 4); // requestID
  683. msgHeader.writeInt32LE(0, 8); // responseTo (zero)
  684. msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode
  685. // Create the compression details of OP_COMPRESSED
  686. const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);
  687. compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode
  688. compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader
  689. compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID
  690. return callback(null, [msgHeader, compressionDetails, compressedMessage]);
  691. });
  692. }
  693. /**
  694. * Write a message to MongoDB
  695. * @method
  696. * @return {Connection}
  697. */
  698. Pool.prototype.write = function(command, options, cb) {
  699. var self = this;
  700. // Ensure we have a callback
  701. if (typeof options === 'function') {
  702. cb = options;
  703. }
  704. // Always have options
  705. options = options || {};
  706. // We need to have a callback function unless the message returns no response
  707. if (!(typeof cb === 'function') && !options.noResponse) {
  708. throw new MongoError('write method must provide a callback');
  709. }
  710. // Pool was destroyed error out
  711. if (this.state === DESTROYED || this.state === DESTROYING) {
  712. // Callback with an error
  713. if (cb) {
  714. try {
  715. cb(new MongoError('pool destroyed'));
  716. } catch (err) {
  717. process.nextTick(function() {
  718. throw err;
  719. });
  720. }
  721. }
  722. return;
  723. }
  724. if (this.options.domainsEnabled && process.domain && typeof cb === 'function') {
  725. // if we have a domain bind to it
  726. var oldCb = cb;
  727. cb = process.domain.bind(function() {
  728. // v8 - argumentsToArray one-liner
  729. var args = new Array(arguments.length);
  730. for (var i = 0; i < arguments.length; i++) {
  731. args[i] = arguments[i];
  732. }
  733. // bounce off event loop so domain switch takes place
  734. process.nextTick(function() {
  735. oldCb.apply(null, args);
  736. });
  737. });
  738. }
  739. // Do we have an operation
  740. var operation = {
  741. cb: cb,
  742. raw: false,
  743. promoteLongs: true,
  744. promoteValues: true,
  745. promoteBuffers: false,
  746. fullResult: false
  747. };
  748. // Set the options for the parsing
  749. operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true;
  750. operation.promoteValues =
  751. typeof options.promoteValues === 'boolean' ? options.promoteValues : true;
  752. operation.promoteBuffers =
  753. typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false;
  754. operation.raw = typeof options.raw === 'boolean' ? options.raw : false;
  755. operation.immediateRelease =
  756. typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false;
  757. operation.documentsReturnedIn = options.documentsReturnedIn;
  758. operation.command = typeof options.command === 'boolean' ? options.command : false;
  759. operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false;
  760. operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false;
  761. operation.session = options.session || null;
  762. // Optional per operation socketTimeout
  763. operation.socketTimeout = options.socketTimeout;
  764. operation.monitoring = options.monitoring;
  765. // Custom socket Timeout
  766. if (options.socketTimeout) {
  767. operation.socketTimeout = options.socketTimeout;
  768. }
  769. // Get the requestId
  770. operation.requestId = command.requestId;
  771. // If command monitoring is enabled we need to modify the callback here
  772. if (self.options.monitorCommands) {
  773. this.emit('commandStarted', new apm.CommandStartedEvent(this, command));
  774. operation.started = process.hrtime();
  775. operation.cb = (err, reply) => {
  776. if (err) {
  777. self.emit(
  778. 'commandFailed',
  779. new apm.CommandFailedEvent(this, command, err, operation.started)
  780. );
  781. } else {
  782. if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) {
  783. self.emit(
  784. 'commandFailed',
  785. new apm.CommandFailedEvent(this, command, reply.result, operation.started)
  786. );
  787. } else {
  788. self.emit(
  789. 'commandSucceeded',
  790. new apm.CommandSucceededEvent(this, command, reply, operation.started)
  791. );
  792. }
  793. }
  794. if (typeof cb === 'function') cb(err, reply);
  795. };
  796. }
  797. // Prepare the operation buffer
  798. serializeCommand(self, command, (err, serializedBuffers) => {
  799. if (err) throw err;
  800. // Set the operation's buffer to the serialization of the commands
  801. operation.buffer = serializedBuffers;
  802. // If we have a monitoring operation schedule as the very first operation
  803. // Otherwise add to back of queue
  804. if (options.monitoring) {
  805. self.queue.unshift(operation);
  806. } else {
  807. self.queue.push(operation);
  808. }
  809. // Attempt to execute the operation
  810. if (!self.executing) {
  811. process.nextTick(function() {
  812. _execute(self)();
  813. });
  814. }
  815. });
  816. };
  817. // Return whether a command contains an uncompressible command term
  818. // Will return true if command contains no uncompressible command terms
  819. function canCompress(command) {
  820. const commandDoc = command instanceof Msg ? command.command : command.query;
  821. const commandName = Object.keys(commandDoc)[0];
  822. return uncompressibleCommands.indexOf(commandName) === -1;
  823. }
  824. // Remove connection method
  825. function remove(connection, connections) {
  826. for (var i = 0; i < connections.length; i++) {
  827. if (connections[i] === connection) {
  828. connections.splice(i, 1);
  829. return true;
  830. }
  831. }
  832. }
  833. function removeConnection(self, connection) {
  834. if (remove(connection, self.availableConnections)) return;
  835. if (remove(connection, self.inUseConnections)) return;
  836. }
  837. const handlers = ['close', 'message', 'error', 'timeout', 'parseError', 'connect'];
  838. function _createConnection(self) {
  839. if (self.state === DESTROYED || self.state === DESTROYING) {
  840. return;
  841. }
  842. self.connectingConnections++;
  843. connect(self.options, (err, connection) => {
  844. self.connectingConnections--;
  845. if (err) {
  846. if (self.logger.isDebug()) {
  847. self.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`);
  848. }
  849. if (!self.reconnectId && self.options.reconnect) {
  850. self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval);
  851. }
  852. return;
  853. }
  854. if (self.state === DESTROYED || self.state === DESTROYING) {
  855. removeConnection(self, connection);
  856. return connection.destroy();
  857. }
  858. connection.on('error', self._connectionErrorHandler);
  859. connection.on('close', self._connectionCloseHandler);
  860. connection.on('timeout', self._connectionTimeoutHandler);
  861. connection.on('parseError', self._connectionParseErrorHandler);
  862. connection.on('message', self._messageHandler);
  863. if (self.state === DESTROYED || self.state === DESTROYING) {
  864. return connection.destroy();
  865. }
  866. // Remove the connection from the connectingConnections list
  867. removeConnection(self, connection);
  868. // Handle error
  869. if (err) {
  870. return connection.destroy();
  871. }
  872. // Push to available
  873. self.availableConnections.push(connection);
  874. // Execute any work waiting
  875. _execute(self)();
  876. });
  877. }
  878. function flushMonitoringOperations(queue) {
  879. for (var i = 0; i < queue.length; i++) {
  880. if (queue[i].monitoring) {
  881. var workItem = queue[i];
  882. queue.splice(i, 1);
  883. workItem.cb(
  884. new MongoError({ message: 'no connection available for monitoring', driver: true })
  885. );
  886. }
  887. }
  888. }
  889. function _execute(self) {
  890. return function() {
  891. if (self.state === DESTROYED) return;
  892. // Already executing, skip
  893. if (self.executing) return;
  894. // Set pool as executing
  895. self.executing = true;
  896. // New pool connections are in progress, wait them to finish
  897. // before executing any more operation to ensure distribution of
  898. // operations
  899. if (self.connectingConnections > 0) {
  900. self.executing = false;
  901. return;
  902. }
  903. // As long as we have available connections
  904. // eslint-disable-next-line
  905. while (true) {
  906. // Total availble connections
  907. const totalConnections = totalConnectionCount(self);
  908. // No available connections available, flush any monitoring ops
  909. if (self.availableConnections.length === 0) {
  910. // Flush any monitoring operations
  911. flushMonitoringOperations(self.queue);
  912. break;
  913. }
  914. // No queue break
  915. if (self.queue.length === 0) {
  916. break;
  917. }
  918. var connection = null;
  919. const connections = self.availableConnections.filter(conn => conn.workItems.length === 0);
  920. // No connection found that has no work on it, just pick one for pipelining
  921. if (connections.length === 0) {
  922. connection =
  923. self.availableConnections[self.connectionIndex++ % self.availableConnections.length];
  924. } else {
  925. connection = connections[self.connectionIndex++ % connections.length];
  926. }
  927. // Is the connection connected
  928. if (!connection.isConnected()) {
  929. // Remove the disconnected connection
  930. removeConnection(self, connection);
  931. // Flush any monitoring operations in the queue, failing fast
  932. flushMonitoringOperations(self.queue);
  933. break;
  934. }
  935. // Get the next work item
  936. var workItem = self.queue.shift();
  937. // If we are monitoring we need to use a connection that is not
  938. // running another operation to avoid socket timeout changes
  939. // affecting an existing operation
  940. if (workItem.monitoring) {
  941. var foundValidConnection = false;
  942. for (let i = 0; i < self.availableConnections.length; i++) {
  943. // If the connection is connected
  944. // And there are no pending workItems on it
  945. // Then we can safely use it for monitoring.
  946. if (
  947. self.availableConnections[i].isConnected() &&
  948. self.availableConnections[i].workItems.length === 0
  949. ) {
  950. foundValidConnection = true;
  951. connection = self.availableConnections[i];
  952. break;
  953. }
  954. }
  955. // No safe connection found, attempt to grow the connections
  956. // if possible and break from the loop
  957. if (!foundValidConnection) {
  958. // Put workItem back on the queue
  959. self.queue.unshift(workItem);
  960. // Attempt to grow the pool if it's not yet maxsize
  961. if (totalConnections < self.options.size && self.queue.length > 0) {
  962. // Create a new connection
  963. _createConnection(self);
  964. }
  965. // Re-execute the operation
  966. setTimeout(function() {
  967. _execute(self)();
  968. }, 10);
  969. break;
  970. }
  971. }
  972. // Don't execute operation until we have a full pool
  973. if (totalConnections < self.options.size) {
  974. // Connection has work items, then put it back on the queue
  975. // and create a new connection
  976. if (connection.workItems.length > 0) {
  977. // Lets put the workItem back on the list
  978. self.queue.unshift(workItem);
  979. // Create a new connection
  980. _createConnection(self);
  981. // Break from the loop
  982. break;
  983. }
  984. }
  985. // Get actual binary commands
  986. var buffer = workItem.buffer;
  987. // If we are monitoring take the connection of the availableConnections
  988. if (workItem.monitoring) {
  989. moveConnectionBetween(connection, self.availableConnections, self.inUseConnections);
  990. }
  991. // Track the executing commands on the mongo server
  992. // as long as there is an expected response
  993. if (!workItem.noResponse) {
  994. connection.workItems.push(workItem);
  995. }
  996. // We have a custom socketTimeout
  997. if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') {
  998. connection.setSocketTimeout(workItem.socketTimeout);
  999. }
  1000. // Capture if write was successful
  1001. var writeSuccessful = true;
  1002. // Put operation on the wire
  1003. if (Array.isArray(buffer)) {
  1004. for (let i = 0; i < buffer.length; i++) {
  1005. writeSuccessful = connection.write(buffer[i]);
  1006. }
  1007. } else {
  1008. writeSuccessful = connection.write(buffer);
  1009. }
  1010. // if the command is designated noResponse, call the callback immeditely
  1011. if (workItem.noResponse && typeof workItem.cb === 'function') {
  1012. workItem.cb(null, null);
  1013. }
  1014. if (writeSuccessful === false) {
  1015. // If write not successful put back on queue
  1016. self.queue.unshift(workItem);
  1017. // Remove the disconnected connection
  1018. removeConnection(self, connection);
  1019. // Flush any monitoring operations in the queue, failing fast
  1020. flushMonitoringOperations(self.queue);
  1021. break;
  1022. }
  1023. }
  1024. self.executing = false;
  1025. };
  1026. }
  1027. // Make execution loop available for testing
  1028. Pool._execute = _execute;
  1029. /**
  1030. * A server connect event, used to verify that the connection is up and running
  1031. *
  1032. * @event Pool#connect
  1033. * @type {Pool}
  1034. */
  1035. /**
  1036. * A server reconnect event, used to verify that pool reconnected.
  1037. *
  1038. * @event Pool#reconnect
  1039. * @type {Pool}
  1040. */
  1041. /**
  1042. * The server connection closed, all pool connections closed
  1043. *
  1044. * @event Pool#close
  1045. * @type {Pool}
  1046. */
  1047. /**
  1048. * The server connection caused an error, all pool connections closed
  1049. *
  1050. * @event Pool#error
  1051. * @type {Pool}
  1052. */
  1053. /**
  1054. * The server connection timed out, all pool connections closed
  1055. *
  1056. * @event Pool#timeout
  1057. * @type {Pool}
  1058. */
  1059. /**
  1060. * The driver experienced an invalid message, all pool connections closed
  1061. *
  1062. * @event Pool#parseError
  1063. * @type {Pool}
  1064. */
  1065. /**
  1066. * The driver attempted to reconnect
  1067. *
  1068. * @event Pool#attemptReconnect
  1069. * @type {Pool}
  1070. */
  1071. /**
  1072. * The driver exhausted all reconnect attempts
  1073. *
  1074. * @event Pool#reconnectFailed
  1075. * @type {Pool}
  1076. */
  1077. module.exports = Pool;