server.js 12 KB

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