server.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. "use strict";
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('util').inherits
  4. , CServer = require('mongodb-core').Server
  5. , Cursor = require('./cursor')
  6. , AggregationCursor = require('./aggregation_cursor')
  7. , CommandCursor = require('./command_cursor')
  8. , f = require('util').format
  9. , ServerCapabilities = require('./topology_base').ServerCapabilities
  10. , Store = require('./topology_base').Store
  11. , Define = require('./metadata')
  12. , MongoError = require('mongodb-core').MongoError
  13. , MAX_JS_INT = require('./utils').MAX_JS_INT
  14. , translateOptions = require('./utils').translateOptions
  15. , filterOptions = require('./utils').filterOptions
  16. , mergeOptions = require('./utils').mergeOptions
  17. , os = require('os');
  18. // Get package.json variable
  19. var driverVersion = require(__dirname + '/../package.json').version;
  20. var nodejsversion = f('Node.js %s, %s', process.version, os.endianness());
  21. var type = os.type();
  22. var name = process.platform;
  23. var architecture = process.arch;
  24. var release = os.release();
  25. /**
  26. * @fileOverview The **Server** class is a class that represents a single server topology and is
  27. * used to construct connections.
  28. *
  29. * **Server Should not be used, use MongoClient.connect**
  30. * @example
  31. * var Db = require('mongodb').Db,
  32. * Server = require('mongodb').Server,
  33. * test = require('assert');
  34. * // Connect using single Server
  35. * var db = new Db('test', new Server('localhost', 27017););
  36. * db.open(function(err, db) {
  37. * // Get an additional db
  38. * db.close();
  39. * });
  40. */
  41. // Allowed parameters
  42. var legalOptionNames = ['ha', 'haInterval', 'acceptableLatencyMS'
  43. , 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate'
  44. , 'sslCA', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries'
  45. , 'store', 'auto_reconnect', 'autoReconnect', 'emitError'
  46. , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS'
  47. , 'loggerLevel', 'logger', 'reconnectTries', 'reconnectInterval', 'monitoring'
  48. , 'appname', 'domainsEnabled'
  49. , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers'];
  50. /**
  51. * Creates a new Server instance
  52. * @class
  53. * @deprecated
  54. * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host.
  55. * @param {number} [port] The server port if IP4.
  56. * @param {object} [options=null] Optional settings.
  57. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
  58. * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
  59. * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
  60. * @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.
  61. * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
  62. * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
  63. * @param {(Buffer|string)} [options.sslKey=null] 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)
  64. * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
  65. * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.
  66. * @param {object} [options.socketOptions=null] Socket options
  67. * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error.
  68. * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
  69. * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start.
  70. * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting
  71. * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting
  72. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  73. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  74. * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster
  75. * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled.
  76. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
  77. * @fires Server#connect
  78. * @fires Server#close
  79. * @fires Server#error
  80. * @fires Server#timeout
  81. * @fires Server#parseError
  82. * @fires Server#reconnect
  83. * @property {string} parserType the parser type used (c++ or js).
  84. * @return {Server} a Server instance.
  85. */
  86. var Server = function(host, port, options) {
  87. options = options || {};
  88. if(!(this instanceof Server)) return new Server(host, port, options);
  89. EventEmitter.call(this);
  90. var self = this;
  91. // Filter the options
  92. options = filterOptions(options, legalOptionNames);
  93. // Stored options
  94. var storeOptions = {
  95. force: false
  96. , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT
  97. }
  98. // Shared global store
  99. var store = options.store || new Store(self, storeOptions);
  100. // Detect if we have a socket connection
  101. if(host.indexOf('\/') != -1) {
  102. if(port != null && typeof port == 'object') {
  103. options = port;
  104. port = null;
  105. }
  106. } else if(port == null) {
  107. throw MongoError.create({message: 'port must be specified', driver:true});
  108. }
  109. // Get the reconnect option
  110. var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true;
  111. reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect;
  112. // Clone options
  113. var clonedOptions = mergeOptions({}, {
  114. host: host, port: port, disconnectHandler: store,
  115. cursorFactory: Cursor,
  116. reconnect: reconnect,
  117. emitError: typeof options.emitError == 'boolean' ? options.emitError : true,
  118. size: typeof options.poolSize == 'number' ? options.poolSize : 5
  119. });
  120. // Translate any SSL options and other connectivity options
  121. clonedOptions = translateOptions(clonedOptions, options);
  122. // Socket options
  123. var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0
  124. ? options.socketOptions : options;
  125. // Translate all the options to the mongodb-core ones
  126. clonedOptions = translateOptions(clonedOptions, socketOptions);
  127. if(typeof clonedOptions.keepAlive == 'number') {
  128. clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive;
  129. clonedOptions.keepAlive = clonedOptions.keepAlive > 0;
  130. }
  131. // Build default client information
  132. this.clientInfo = {
  133. driver: {
  134. name: "nodejs",
  135. version: driverVersion
  136. },
  137. os: {
  138. type: type,
  139. name: name,
  140. architecture: architecture,
  141. version: release
  142. },
  143. platform: nodejsversion
  144. }
  145. // Build default client information
  146. clonedOptions.clientInfo = this.clientInfo;
  147. // Do we have an application specific string
  148. if(options.appname) {
  149. clonedOptions.clientInfo.application = { name: options.appname };
  150. }
  151. // Create an instance of a server instance from mongodb-core
  152. var server = new CServer(clonedOptions);
  153. // Define the internal properties
  154. this.s = {
  155. // Create an instance of a server instance from mongodb-core
  156. server: server
  157. // Server capabilities
  158. , sCapabilities: null
  159. // Cloned options
  160. , clonedOptions: clonedOptions
  161. // Reconnect
  162. , reconnect: clonedOptions.reconnect
  163. // Emit error
  164. , emitError: clonedOptions.emitError
  165. // Pool size
  166. , poolSize: clonedOptions.size
  167. // Store Options
  168. , storeOptions: storeOptions
  169. // Store
  170. , store: store
  171. // Host
  172. , host: host
  173. // Port
  174. , port: port
  175. // Options
  176. , options: options
  177. }
  178. }
  179. inherits(Server, EventEmitter);
  180. var define = Server.define = new Define('Server', Server, false);
  181. // BSON property
  182. Object.defineProperty(Server.prototype, 'bson', {
  183. enumerable: true, get: function() {
  184. return this.s.server.s.bson;
  185. }
  186. });
  187. // Last ismaster
  188. Object.defineProperty(Server.prototype, 'isMasterDoc', {
  189. enumerable:true, get: function() {
  190. return this.s.server.lastIsMaster();
  191. }
  192. });
  193. Object.defineProperty(Server.prototype, 'parserType', {
  194. enumerable:true, get: function() {
  195. return this.s.server.parserType;
  196. }
  197. });
  198. // Last ismaster
  199. Object.defineProperty(Server.prototype, 'poolSize', {
  200. enumerable:true, get: function() { return this.s.server.connections().length; }
  201. });
  202. Object.defineProperty(Server.prototype, 'autoReconnect', {
  203. enumerable:true, get: function() { return this.s.reconnect; }
  204. });
  205. Object.defineProperty(Server.prototype, 'host', {
  206. enumerable:true, get: function() { return this.s.host; }
  207. });
  208. Object.defineProperty(Server.prototype, 'port', {
  209. enumerable:true, get: function() { return this.s.port; }
  210. });
  211. // Connect
  212. Server.prototype.connect = function(db, _options, callback) {
  213. var self = this;
  214. if('function' === typeof _options) callback = _options, _options = {};
  215. if(_options == null) _options = {};
  216. if(!('function' === typeof callback)) callback = null;
  217. self.s.options = _options;
  218. // Update bufferMaxEntries
  219. self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries;
  220. // Error handler
  221. var connectErrorHandler = function() {
  222. return function(err) {
  223. // Remove all event handlers
  224. var events = ['timeout', 'error', 'close'];
  225. events.forEach(function(e) {
  226. self.s.server.removeListener(e, connectHandlers[e]);
  227. });
  228. self.s.server.removeListener('connect', connectErrorHandler);
  229. // Try to callback
  230. try {
  231. callback(err);
  232. } catch(err) {
  233. process.nextTick(function() { throw err; })
  234. }
  235. }
  236. }
  237. // Actual handler
  238. var errorHandler = function(event) {
  239. return function(err) {
  240. if(event != 'error') {
  241. self.emit(event, err);
  242. }
  243. }
  244. }
  245. // Error handler
  246. var reconnectHandler = function() {
  247. self.emit('reconnect', self);
  248. self.s.store.execute();
  249. }
  250. // Reconnect failed
  251. var reconnectFailedHandler = function(err) {
  252. self.emit('reconnectFailed', err);
  253. self.s.store.flush(err);
  254. }
  255. // Destroy called on topology, perform cleanup
  256. var destroyHandler = function() {
  257. self.s.store.flush();
  258. }
  259. // Connect handler
  260. var connectHandler = function() {
  261. // Clear out all the current handlers left over
  262. ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted',
  263. 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening',
  264. 'topologyClosed', 'topologyDescriptionChanged'].forEach(function(e) {
  265. self.s.server.removeAllListeners(e);
  266. });
  267. // Set up listeners
  268. self.s.server.on('timeout', errorHandler('timeout'));
  269. self.s.server.once('error', errorHandler('error'));
  270. self.s.server.on('close', errorHandler('close'));
  271. // Only called on destroy
  272. self.s.server.on('destroy', destroyHandler);
  273. // relay the event
  274. var relay = function(event) {
  275. return function(t, server) {
  276. self.emit(event, t, server);
  277. }
  278. }
  279. // Set up SDAM listeners
  280. self.s.server.on('serverDescriptionChanged', relay('serverDescriptionChanged'));
  281. self.s.server.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));
  282. self.s.server.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));
  283. self.s.server.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));
  284. self.s.server.on('serverOpening', relay('serverOpening'));
  285. self.s.server.on('serverClosed', relay('serverClosed'));
  286. self.s.server.on('topologyOpening', relay('topologyOpening'));
  287. self.s.server.on('topologyClosed', relay('topologyClosed'));
  288. self.s.server.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));
  289. self.s.server.on('attemptReconnect', relay('attemptReconnect'));
  290. self.s.server.on('monitoring', relay('monitoring'));
  291. // Emit open event
  292. self.emit('open', null, self);
  293. // Return correctly
  294. try {
  295. callback(null, self);
  296. } catch(err) {
  297. console.log(err.stack)
  298. process.nextTick(function() { throw err; })
  299. }
  300. }
  301. // Set up listeners
  302. var connectHandlers = {
  303. timeout: connectErrorHandler('timeout'),
  304. error: connectErrorHandler('error'),
  305. close: connectErrorHandler('close')
  306. };
  307. // Add the event handlers
  308. self.s.server.once('timeout', connectHandlers.timeout);
  309. self.s.server.once('error', connectHandlers.error);
  310. self.s.server.once('close', connectHandlers.close);
  311. self.s.server.once('connect', connectHandler);
  312. // Reconnect server
  313. self.s.server.on('reconnect', reconnectHandler);
  314. self.s.server.on('reconnectFailed', reconnectFailedHandler);
  315. // Start connection
  316. self.s.server.connect(_options);
  317. }
  318. // Server capabilities
  319. Server.prototype.capabilities = function() {
  320. if(this.s.sCapabilities) return this.s.sCapabilities;
  321. if(this.s.server.lastIsMaster() == null) return null;
  322. this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster());
  323. return this.s.sCapabilities;
  324. }
  325. define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]});
  326. // Command
  327. Server.prototype.command = function(ns, cmd, options, callback) {
  328. this.s.server.command(ns, cmd, options, callback);
  329. }
  330. define.classMethod('command', {callback: true, promise:false});
  331. // Insert
  332. Server.prototype.insert = function(ns, ops, options, callback) {
  333. this.s.server.insert(ns, ops, options, callback);
  334. }
  335. define.classMethod('insert', {callback: true, promise:false});
  336. // Update
  337. Server.prototype.update = function(ns, ops, options, callback) {
  338. this.s.server.update(ns, ops, options, callback);
  339. }
  340. define.classMethod('update', {callback: true, promise:false});
  341. // Remove
  342. Server.prototype.remove = function(ns, ops, options, callback) {
  343. this.s.server.remove(ns, ops, options, callback);
  344. }
  345. define.classMethod('remove', {callback: true, promise:false});
  346. // IsConnected
  347. Server.prototype.isConnected = function() {
  348. return this.s.server.isConnected();
  349. }
  350. Server.prototype.isDestroyed = function() {
  351. return this.s.server.isDestroyed();
  352. }
  353. define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]});
  354. // Insert
  355. Server.prototype.cursor = function(ns, cmd, options) {
  356. options.disconnectHandler = this.s.store;
  357. return this.s.server.cursor(ns, cmd, options);
  358. }
  359. define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]});
  360. Server.prototype.lastIsMaster = function() {
  361. return this.s.server.lastIsMaster();
  362. }
  363. /**
  364. * Unref all sockets
  365. * @method
  366. */
  367. Server.prototype.unref = function() {
  368. this.s.server.unref();
  369. }
  370. Server.prototype.close = function(forceClosed) {
  371. this.s.server.destroy();
  372. // We need to wash out all stored processes
  373. if(forceClosed == true) {
  374. this.s.storeOptions.force = forceClosed;
  375. this.s.store.flush();
  376. }
  377. }
  378. define.classMethod('close', {callback: false, promise:false});
  379. Server.prototype.auth = function() {
  380. var args = Array.prototype.slice.call(arguments, 0);
  381. this.s.server.auth.apply(this.s.server, args);
  382. }
  383. define.classMethod('auth', {callback: true, promise:false});
  384. Server.prototype.logout = function() {
  385. var args = Array.prototype.slice.call(arguments, 0);
  386. this.s.server.logout.apply(this.s.server, args);
  387. }
  388. define.classMethod('logout', {callback: true, promise:false});
  389. /**
  390. * All raw connections
  391. * @method
  392. * @return {array}
  393. */
  394. Server.prototype.connections = function() {
  395. return this.s.server.connections();
  396. }
  397. define.classMethod('connections', {callback: false, promise:false, returns:[Array]});
  398. /**
  399. * Server connect event
  400. *
  401. * @event Server#connect
  402. * @type {object}
  403. */
  404. /**
  405. * Server close event
  406. *
  407. * @event Server#close
  408. * @type {object}
  409. */
  410. /**
  411. * Server reconnect event
  412. *
  413. * @event Server#reconnect
  414. * @type {object}
  415. */
  416. /**
  417. * Server error event
  418. *
  419. * @event Server#error
  420. * @type {MongoError}
  421. */
  422. /**
  423. * Server timeout event
  424. *
  425. * @event Server#timeout
  426. * @type {object}
  427. */
  428. /**
  429. * Server parseError event
  430. *
  431. * @event Server#parseError
  432. * @type {object}
  433. */
  434. module.exports = Server;