server.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. , shallowClone = require('./utils').shallowClone;
  14. /**
  15. * @fileOverview The **Server** class is a class that represents a single server topology and is
  16. * used to construct connections.
  17. *
  18. * **Server Should not be used, use MongoClient.connect**
  19. * @example
  20. * var Db = require('mongodb').Db,
  21. * Server = require('mongodb').Server,
  22. * test = require('assert');
  23. * // Connect using single Server
  24. * var db = new Db('test', new Server('localhost', 27017););
  25. * db.open(function(err, db) {
  26. * // Get an additional db
  27. * db.close();
  28. * });
  29. */
  30. /**
  31. * Creates a new Server instance
  32. * @class
  33. * @deprecated
  34. * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host.
  35. * @param {number} [port] The server port if IP4.
  36. * @param {object} [options=null] Optional settings.
  37. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
  38. * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
  39. * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
  40. * @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.
  41. * @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)
  42. * @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)
  43. * @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)
  44. * @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)
  45. * @param {object} [options.socketOptions=null] Socket options
  46. * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error.
  47. * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
  48. * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start.
  49. * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting
  50. * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting
  51. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  52. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  53. * @fires Server#connect
  54. * @fires Server#close
  55. * @fires Server#error
  56. * @fires Server#timeout
  57. * @fires Server#parseError
  58. * @fires Server#reconnect
  59. * @return {Server} a Server instance.
  60. */
  61. var Server = function(host, port, options) {
  62. options = options || {};
  63. if(!(this instanceof Server)) return new Server(host, port, options);
  64. EventEmitter.call(this);
  65. var self = this;
  66. // Store option defaults
  67. var storeOptions = {
  68. force: false
  69. , bufferMaxEntries: -1
  70. }
  71. // Shared global store
  72. var store = options.store || new Store(self, storeOptions);
  73. // Detect if we have a socket connection
  74. if(host.indexOf('\/') != -1) {
  75. if(port != null && typeof port == 'object') {
  76. options = port;
  77. port = null;
  78. }
  79. } else if(port == null) {
  80. throw MongoError.create({message: 'port must be specified', driver:true});
  81. }
  82. // Clone options
  83. var clonedOptions = shallowClone(options);
  84. clonedOptions.host = host;
  85. clonedOptions.port = port;
  86. // Reconnect
  87. var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true;
  88. reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect;
  89. var emitError = typeof options.emitError == 'boolean' ? options.emitError : true;
  90. var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5;
  91. // Socket options passed down
  92. if(options.socketOptions) {
  93. if(options.socketOptions.connectTimeoutMS) {
  94. this.connectTimeoutMS = options.socketOptions.connectTimeoutMS;
  95. clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS;
  96. }
  97. if(options.socketOptions.socketTimeoutMS) {
  98. clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS;
  99. }
  100. if(typeof options.socketOptions.keepAlive == 'number') {
  101. clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive;
  102. clonedOptions.keepAlive = true;
  103. }
  104. if(typeof options.socketOptions.noDelay == 'boolean') {
  105. clonedOptions.noDelay = options.socketOptions.noDelay;
  106. }
  107. }
  108. // Add the cursor factory function
  109. clonedOptions.cursorFactory = Cursor;
  110. clonedOptions.reconnect = reconnect;
  111. clonedOptions.emitError = emitError;
  112. clonedOptions.size = poolSize;
  113. // Translate the options
  114. if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA;
  115. if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate;
  116. if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey;
  117. if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert;
  118. if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass;
  119. // Add the non connection store
  120. clonedOptions.disconnectHandler = store;
  121. // Create an instance of a server instance from mongodb-core
  122. var server = new CServer(clonedOptions);
  123. // Server capabilities
  124. var sCapabilities = null;
  125. // Define the internal properties
  126. this.s = {
  127. // Create an instance of a server instance from mongodb-core
  128. server: server
  129. // Server capabilities
  130. , sCapabilities: null
  131. // Cloned options
  132. , clonedOptions: clonedOptions
  133. // Reconnect
  134. , reconnect: reconnect
  135. // Emit error
  136. , emitError: emitError
  137. // Pool size
  138. , poolSize: poolSize
  139. // Store Options
  140. , storeOptions: storeOptions
  141. // Store
  142. , store: store
  143. // Host
  144. , host: host
  145. // Port
  146. , port: port
  147. // Options
  148. , options: options
  149. }
  150. // BSON property
  151. Object.defineProperty(this, 'bson', {
  152. enumerable: true, get: function() {
  153. return self.s.server.bson;
  154. }
  155. });
  156. // Last ismaster
  157. Object.defineProperty(this, 'isMasterDoc', {
  158. enumerable:true, get: function() {
  159. return self.s.server.lastIsMaster();
  160. }
  161. });
  162. // Last ismaster
  163. Object.defineProperty(this, 'poolSize', {
  164. enumerable:true, get: function() { return self.s.server.connections().length; }
  165. });
  166. Object.defineProperty(this, 'autoReconnect', {
  167. enumerable:true, get: function() { return self.s.reconnect; }
  168. });
  169. Object.defineProperty(this, 'host', {
  170. enumerable:true, get: function() { return self.s.host; }
  171. });
  172. Object.defineProperty(this, 'port', {
  173. enumerable:true, get: function() { return self.s.port; }
  174. });
  175. }
  176. inherits(Server, EventEmitter);
  177. var define = Server.define = new Define('Server', Server, false);
  178. Server.prototype.parserType = function() {
  179. return this.s.server.parserType();
  180. }
  181. define.classMethod('parserType', {callback: false, promise:false, returns: [String]});
  182. // Connect
  183. Server.prototype.connect = function(db, _options, callback) {
  184. var self = this;
  185. if('function' === typeof _options) callback = _options, _options = {};
  186. if(_options == null) _options = {};
  187. if(!('function' === typeof callback)) callback = null;
  188. self.s.options = _options;
  189. // Update bufferMaxEntries
  190. self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries;
  191. // Error handler
  192. var connectErrorHandler = function(event) {
  193. return function(err) {
  194. // Remove all event handlers
  195. var events = ['timeout', 'error', 'close'];
  196. events.forEach(function(e) {
  197. self.s.server.removeListener(e, connectHandlers[e]);
  198. });
  199. self.s.server.removeListener('connect', connectErrorHandler);
  200. // Try to callback
  201. try {
  202. callback(err);
  203. } catch(err) {
  204. process.nextTick(function() { throw err; })
  205. }
  206. }
  207. }
  208. // Actual handler
  209. var errorHandler = function(event) {
  210. return function(err) {
  211. if(event != 'error') {
  212. self.emit(event, err);
  213. }
  214. }
  215. }
  216. // Error handler
  217. var reconnectHandler = function(err) {
  218. self.emit('reconnect', self);
  219. self.s.store.execute();
  220. }
  221. // Destroy called on topology, perform cleanup
  222. var destroyHandler = function() {
  223. self.s.store.flush();
  224. }
  225. // Connect handler
  226. var connectHandler = function() {
  227. // Clear out all the current handlers left over
  228. ["timeout", "error", "close"].forEach(function(e) {
  229. self.s.server.removeAllListeners(e);
  230. });
  231. // Set up listeners
  232. self.s.server.once('timeout', errorHandler('timeout'));
  233. self.s.server.once('error', errorHandler('error'));
  234. self.s.server.on('close', errorHandler('close'));
  235. // Only called on destroy
  236. self.s.server.once('destroy', destroyHandler);
  237. // Emit open event
  238. self.emit('open', null, self);
  239. // Return correctly
  240. try {
  241. callback(null, self);
  242. } catch(err) {
  243. console.log(err.stack)
  244. process.nextTick(function() { throw err; })
  245. }
  246. }
  247. // Set up listeners
  248. var connectHandlers = {
  249. timeout: connectErrorHandler('timeout'),
  250. error: connectErrorHandler('error'),
  251. close: connectErrorHandler('close')
  252. };
  253. // Add the event handlers
  254. self.s.server.once('timeout', connectHandlers.timeout);
  255. self.s.server.once('error', connectHandlers.error);
  256. self.s.server.once('close', connectHandlers.close);
  257. self.s.server.once('connect', connectHandler);
  258. // Reconnect server
  259. self.s.server.on('reconnect', reconnectHandler);
  260. // Start connection
  261. self.s.server.connect(_options);
  262. }
  263. // Server capabilities
  264. Server.prototype.capabilities = function() {
  265. if(this.s.sCapabilities) return this.s.sCapabilities;
  266. if(this.s.server.lastIsMaster() == null) return null;
  267. this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster());
  268. return this.s.sCapabilities;
  269. }
  270. define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]});
  271. // Command
  272. Server.prototype.command = function(ns, cmd, options, callback) {
  273. this.s.server.command(ns, cmd, options, callback);
  274. }
  275. define.classMethod('command', {callback: true, promise:false});
  276. // Insert
  277. Server.prototype.insert = function(ns, ops, options, callback) {
  278. this.s.server.insert(ns, ops, options, callback);
  279. }
  280. define.classMethod('insert', {callback: true, promise:false});
  281. // Update
  282. Server.prototype.update = function(ns, ops, options, callback) {
  283. this.s.server.update(ns, ops, options, callback);
  284. }
  285. define.classMethod('update', {callback: true, promise:false});
  286. // Remove
  287. Server.prototype.remove = function(ns, ops, options, callback) {
  288. this.s.server.remove(ns, ops, options, callback);
  289. }
  290. define.classMethod('remove', {callback: true, promise:false});
  291. // IsConnected
  292. Server.prototype.isConnected = function() {
  293. return this.s.server.isConnected();
  294. }
  295. Server.prototype.isDestroyed = function() {
  296. return this.s.server.isDestroyed();
  297. }
  298. define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]});
  299. // Insert
  300. Server.prototype.cursor = function(ns, cmd, options) {
  301. options.disconnectHandler = this.s.store;
  302. return this.s.server.cursor(ns, cmd, options);
  303. }
  304. define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]});
  305. Server.prototype.setBSONParserType = function(type) {
  306. return this.s.server.setBSONParserType(type);
  307. }
  308. Server.prototype.lastIsMaster = function() {
  309. return this.s.server.lastIsMaster();
  310. }
  311. Server.prototype.close = function(forceClosed) {
  312. this.s.server.destroy();
  313. // We need to wash out all stored processes
  314. if(forceClosed == true) {
  315. this.s.storeOptions.force = forceClosed;
  316. this.s.store.flush();
  317. }
  318. }
  319. define.classMethod('close', {callback: false, promise:false});
  320. Server.prototype.auth = function() {
  321. var args = Array.prototype.slice.call(arguments, 0);
  322. this.s.server.auth.apply(this.s.server, args);
  323. }
  324. define.classMethod('auth', {callback: true, promise:false});
  325. /**
  326. * All raw connections
  327. * @method
  328. * @return {array}
  329. */
  330. Server.prototype.connections = function() {
  331. return this.s.server.connections();
  332. }
  333. define.classMethod('connections', {callback: false, promise:false, returns:[Array]});
  334. /**
  335. * Server connect event
  336. *
  337. * @event Server#connect
  338. * @type {object}
  339. */
  340. /**
  341. * Server close event
  342. *
  343. * @event Server#close
  344. * @type {object}
  345. */
  346. /**
  347. * Server reconnect event
  348. *
  349. * @event Server#reconnect
  350. * @type {object}
  351. */
  352. /**
  353. * Server error event
  354. *
  355. * @event Server#error
  356. * @type {MongoError}
  357. */
  358. /**
  359. * Server timeout event
  360. *
  361. * @event Server#timeout
  362. * @type {object}
  363. */
  364. /**
  365. * Server parseError event
  366. *
  367. * @event Server#parseError
  368. * @type {object}
  369. */
  370. module.exports = Server;