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