Page MenuHomeSealhub

bin_node_modules_mongodb_lib_mongodb_connection_mongos.js.html
No OneTemporary

Authored By
Unknown
Size
38 KB
Referenced Files
None
Subscribers
None

bin_node_modules_mongodb_lib_mongodb_connection_mongos.js.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>bin/node_modules/mongodb/lib/mongodb/connection/mongos.js - Prometheus Framework</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title="Prometheus Framework"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: 0.1</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/Represents a
Replicaset Configuration.html">Represents a
Replicaset Configuration</a></li>
<li><a href="../classes/Represents a BatchWriteResult.html">Represents a BatchWriteResult</a></li>
<li><a href="../classes/Represents a Collection.html">Represents a Collection</a></li>
<li><a href="../classes/Represents a Cursor..html">Represents a Cursor.</a></li>
<li><a href="../classes/Represents a CursorStream..html">Represents a CursorStream.</a></li>
<li><a href="../classes/Represents a Db.html">Represents a Db</a></li>
<li><a href="../classes/Represents a GridFS File Stream..html">Represents a GridFS File Stream.</a></li>
<li><a href="../classes/.html"></a></li>
<li><a href="../classes/Represents a MongoClient.html">Represents a MongoClient</a></li>
<li><a href="../classes/Represents a Mongos connection with failover to backup proxies.html">Represents a Mongos connection with failover to backup proxies</a></li>
<li><a href="../classes/Represents a OrderedBulkOperation.html">Represents a OrderedBulkOperation</a></li>
<li><a href="../classes/Represents a Read Preference..html">Represents a Read Preference.</a></li>
<li><a href="../classes/Represents a Server connection..html">Represents a Server connection.</a></li>
<li><a href="../classes/Represents a UnorderedBulkOperation.html">Represents a UnorderedBulkOperation</a></li>
<li><a href="../classes/Represents the Admin methods of MongoDB..html">Represents the Admin methods of MongoDB.</a></li>
<li><a href="../classes/Represents the Grid..html">Represents the Grid.</a></li>
<li><a href="../classes/Represents the GridStore..html">Represents the GridStore.</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/association.html">association</a></li>
<li><a href="../modules/database-accessor.html">database-accessor</a></li>
<li><a href="../modules/field-type-manager.html">field-type-manager</a></li>
<li><a href="../modules/resource-type-manager.html">resource-type-manager</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: bin/node_modules/mongodb/lib/mongodb/connection/mongos.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
var ReadPreference = require(&#x27;./read_preference&#x27;).ReadPreference
, Base = require(&#x27;./base&#x27;).Base
, Server = require(&#x27;./server&#x27;).Server
, format = require(&#x27;util&#x27;).format
, timers = require(&#x27;timers&#x27;)
, utils = require(&#x27;../utils&#x27;)
, inherits = require(&#x27;util&#x27;).inherits;
// Set processor, setImmediate if 0.10 otherwise nextTick
var processor = require(&#x27;../utils&#x27;).processor();
/**
* Mongos constructor provides a connection to a mongos proxy including failover to additional servers
*
* Options
* - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
* - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies
* - **haInterval** {Number, default:2000}, time between each replicaset status check.
*
* @class Represents a Mongos connection with failover to backup proxies
* @param {Array} list of mongos server objects
* @param {Object} [options] additional options for the mongos connection
*/
var Mongos = function Mongos(servers, options) {
// Set up basic
if(!(this instanceof Mongos))
return new Mongos(servers, options);
// Set up event emitter
Base.call(this);
// Throw error on wrong setup
if(servers == null || !Array.isArray(servers) || servers.length == 0)
throw new Error(&quot;At least one mongos proxy must be in the array&quot;);
// Ensure we have at least an empty options object
this.options = options == null ? {} : options;
// Set default connection pool options
this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
// Enabled ha
this.haEnabled = this.options[&#x27;ha&#x27;] == null ? true : this.options[&#x27;ha&#x27;];
this._haInProgress = false;
// How often are we checking for new servers in the replicaset
this.mongosStatusCheckInterval = this.options[&#x27;haInterval&#x27;] == null ? 1000 : this.options[&#x27;haInterval&#x27;];
// Save all the server connections
this.servers = servers;
// Servers we need to attempt reconnect with
this.downServers = {};
// Servers that are up
this.upServers = {};
// Up servers by ping time
this.upServersByUpTime = {};
// Emit open setup
this.emitOpen = this.options.emitOpen || true;
// Just contains the current lowest ping time and server
this.lowestPingTimeServer = null;
this.lowestPingTime = 0;
// Connection timeout
this._connectTimeoutMS = this.socketOptions.connectTimeoutMS
? this.socketOptions.connectTimeoutMS
: 1000;
// Add options to servers
for(var i = 0; i &lt; this.servers.length; i++) {
var server = this.servers[i];
server._callBackStore = this._callBackStore;
server.auto_reconnect = false;
// Default empty socket options object
var socketOptions = {host: server.host, port: server.port};
// If a socket option object exists clone it
if(this.socketOptions != null) {
var keys = Object.keys(this.socketOptions);
for(var k = 0; k &lt; keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]];
}
// Set socket options
server.socketOptions = socketOptions;
}
// Allow setting the socketTimeoutMS on all connections
// to work around issues such as secondaries blocking due to compaction
utils.setSocketTimeoutProperty(this, this.socketOptions);
}
/**
* @ignore
*/
inherits(Mongos, Base);
/**
* @ignore
*/
Mongos.prototype.isMongos = function() {
return true;
}
/**
* @ignore
*/
Mongos.prototype.connect = function(db, options, callback) {
if(&#x27;function&#x27; === typeof options) callback = options, options = {};
if(options == null) options = {};
if(!(&#x27;function&#x27; === typeof callback)) callback = null;
var self = this;
// Keep reference to parent
this.db = db;
// Set server state to connecting
this._serverState = &#x27;connecting&#x27;;
// Number of total servers that need to initialized (known servers)
this._numberOfServersLeftToInitialize = this.servers.length;
// Connect handler
var connectHandler = function(_server) {
return function(err, result) {
self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1;
// Add the server to the list of servers that are up
if(!err) {
self.upServers[format(&quot;%s:%s&quot;, _server.host, _server.port)] = _server;
}
// We are done connecting
if(self._numberOfServersLeftToInitialize == 0) {
// If we have no valid mongos server instances error out
if(Object.keys(self.upServers).length == 0) {
// return self.emit(&quot;connectionError&quot;, new Error(&quot;No valid mongos instances found&quot;));
return callback(new Error(&quot;No valid mongos instances found&quot;), null);
}
// Start ha function if it exists
if(self.haEnabled) {
// Setup the ha process
if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId);
self._replicasetTimeoutId = setInterval(self.mongosCheckFunction, self.mongosStatusCheckInterval);
}
// Set the mongos to connected
self._serverState = &quot;connected&quot;;
// Emit the open event
if(self.emitOpen)
self._emitAcrossAllDbInstances(self, null, &quot;open&quot;, null, null, null);
self._emitAcrossAllDbInstances(self, null, &quot;fullsetup&quot;, null, null, null);
// Callback
callback(null, self.db);
}
}
};
// Error handler
var errorOrCloseHandler = function(_server) {
return function(err, result) {
// Emit left event, signaling mongos left the ha
self.emit(&#x27;left&#x27;, &#x27;mongos&#x27;, _server);
// Execute all the callbacks with errors
self.__executeAllCallbacksWithError(err);
// Check if we have the server
var found = false;
// Get the server name
var server_name = format(&quot;%s:%s&quot;, _server.host, _server.port);
// Add the downed server
self.downServers[server_name] = _server;
// Remove the current server from the list
delete self.upServers[server_name];
// Emit close across all the attached db instances
if(Object.keys(self.upServers).length == 0) {
self._emitAcrossAllDbInstances(self, null, &quot;close&quot;, new Error(&quot;mongos disconnected, no valid proxies contactable over tcp&quot;), null, null);
}
}
}
// Mongo function
this.mongosCheckFunction = function() {
// Set as not waiting for check event
self._haInProgress = true;
// Servers down
var numberOfServersLeft = Object.keys(self.downServers).length;
// Check downed servers
if(numberOfServersLeft &gt; 0) {
for(var name in self.downServers) {
// Pop a downed server
var downServer = self.downServers[name];
// Set up the connection options for a Mongos
var options = {
auto_reconnect: false,
returnIsMasterResults: true,
slaveOk: true,
poolSize: downServer.poolSize,
socketOptions: {
connectTimeoutMS: self._connectTimeoutMS,
socketTimeoutMS: self._socketTimeoutMS
}
}
// Create a new server object
var newServer = new Server(downServer.host, downServer.port, options);
// Setup the connection function
var connectFunction = function(_db, _server, _options, _callback) {
return function() {
// Attempt to connect
_server.connect(_db, _options, function(err, result) {
numberOfServersLeft = numberOfServersLeft - 1;
if(err) {
return _callback(err, _server);
} else {
// Set the new server settings
_server._callBackStore = self._callBackStore;
// Add server event handlers
_server.on(&quot;close&quot;, errorOrCloseHandler(_server));
_server.on(&quot;timeout&quot;, errorOrCloseHandler(_server));
_server.on(&quot;error&quot;, errorOrCloseHandler(_server));
// Get a read connection
var _connection = _server.checkoutReader();
// Get the start time
var startTime = new Date().getTime();
// Execute ping command to mark each server with the expected times
self.db.command({ping:1}
, {failFast:true, connection:_connection}, function(err, result) {
// Get the start time
var endTime = new Date().getTime();
// Mark the server with the ping time
_server.runtimeStats[&#x27;pingMs&#x27;] = endTime - startTime;
// If we have any buffered commands let&#x27;s signal reconnect event
if(self._commandsStore.count() &gt; 0) {
self.emit(&#x27;reconnect&#x27;);
}
// Execute any waiting reads
self._commandsStore.execute_writes();
self._commandsStore.execute_queries();
// Callback
return _callback(null, _server);
});
}
});
}
}
// Attempt to connect to the database
connectFunction(self.db, newServer, options, function(err, _server) {
// If we have an error
if(err) {
self.downServers[format(&quot;%s:%s&quot;, _server.host, _server.port)] = _server;
}
// Connection function
var connectionFunction = function(_auth, _connection, _callback) {
var pending = _auth.length();
for(var j = 0; j &lt; pending; j++) {
// Get the auth object
var _auth = _auth.get(j);
// Unpack the parameter
var username = _auth.username;
var password = _auth.password;
var options = {
authMechanism: _auth.authMechanism
, authSource: _auth.authdb
, connection: _connection
};
// If we have changed the service name
if(_auth.gssapiServiceName)
options.gssapiServiceName = _auth.gssapiServiceName;
// Hold any error
var _error = null;
// Authenticate against the credentials
self.db.authenticate(username, password, options, function(err, result) {
_error = err != null ? err : _error;
// Adjust the pending authentication
pending = pending - 1;
// Finished up
if(pending == 0) _callback(_error ? _error : null, _error ? false : true);
});
}
}
// Run auths against the connections
if(self.auth.length() &gt; 0) {
var connections = _server.allRawConnections();
var pendingAuthConn = connections.length;
// No connections we are done
if(connections.length == 0) {
// Set ha done
if(numberOfServersLeft == 0) {
self._haInProgress = false;
}
}
// Final error object
var finalError = null;
// Go over all the connections
for(var j = 0; j &lt; connections.length; j++) {
// Execute against all the connections
connectionFunction(self.auth, connections[j], function(err, result) {
// Pending authentication
pendingAuthConn = pendingAuthConn - 1 ;
// Save error if any
finalError = err ? err : finalError;
// If we are done let&#x27;s finish up
if(pendingAuthConn == 0) {
// Set ha done
if(numberOfServersLeft == 0) {
self._haInProgress = false;
}
if(!err) {
add_server(self, _server);
}
// If we have any buffered commands let&#x27;s signal reconnect event
if(self._commandsStore.count() &gt; 0) {
self.emit(&#x27;reconnect&#x27;);
}
// Execute any waiting reads
self._commandsStore.execute_writes();
self._commandsStore.execute_queries();
}
});
}
} else {
if(!err) {
add_server(self, _server);
}
// Set ha done
if(numberOfServersLeft == 0) {
self._haInProgress = false;
// If we have any buffered commands let&#x27;s signal reconnect event
if(self._commandsStore.count() &gt; 0) {
self.emit(&#x27;reconnect&#x27;);
}
// Execute any waiting reads
self._commandsStore.execute_writes();
self._commandsStore.execute_queries();
}
}
})();
}
} else {
self._haInProgress = false;
}
}
// Connect all the server instances
for(var i = 0; i &lt; this.servers.length; i++) {
// Get the connection
var server = this.servers[i];
server.mongosInstance = this;
// Add server event handlers
server.on(&quot;close&quot;, errorOrCloseHandler(server));
server.on(&quot;timeout&quot;, errorOrCloseHandler(server));
server.on(&quot;error&quot;, errorOrCloseHandler(server));
// Configuration
var options = {
slaveOk: true,
poolSize: server.poolSize,
socketOptions: { connectTimeoutMS: self._connectTimeoutMS },
returnIsMasterResults: true
}
// Connect the instance
server.connect(self.db, options, connectHandler(server));
}
}
/**
* @ignore
* Add a server to the list of up servers and sort them by ping time
*/
var add_server = function(self, _server) {
// Emit a new server joined
self.emit(&#x27;joined&#x27;, &quot;mongos&quot;, null, _server);
// Get the server url
var server_key = format(&quot;%s:%s&quot;, _server.host, _server.port);
// Push to list of valid server
self.upServers[server_key] = _server;
// Remove the server from the list of downed servers
delete self.downServers[server_key];
// Sort the keys by ping time
var keys = Object.keys(self.upServers);
var _upServersSorted = {};
var _upServers = []
// Get all the servers
for(var name in self.upServers) {
_upServers.push(self.upServers[name]);
}
// Sort all the server
_upServers.sort(function(a, b) {
return a.runtimeStats[&#x27;pingMs&#x27;] &gt; b.runtimeStats[&#x27;pingMs&#x27;];
});
// Rebuild the upServer
for(var i = 0; i &lt; _upServers.length; i++) {
_upServersSorted[format(&quot;%s:%s&quot;, _upServers[i].host, _upServers[i].port)] = _upServers[i];
}
// Set the up servers
self.upServers = _upServersSorted;
}
/**
* @ignore
* Just return the currently picked active connection
*/
Mongos.prototype.allServerInstances = function() {
return this.servers;
}
/**
* @ignore
*/
Mongos.prototype.setSocketOptions = function(options) {
var servers = this.allServerInstances();
for(var i = 0; i &lt; servers.length; i++) {
servers[i].setSocketOptions(options);
}
}
/**
* Always ourselves
* @ignore
*/
Mongos.prototype.setReadPreference = function() {}
/**
* @ignore
*/
Mongos.prototype.allRawConnections = function() {
// Neeed to build a complete list of all raw connections, start with master server
var allConnections = [];
// Get all connected connections
for(var name in this.upServers) {
allConnections = allConnections.concat(this.upServers[name].allRawConnections());
}
// Return all the conections
return allConnections;
}
/**
* @ignore
*/
Mongos.prototype.isConnected = function() {
return Object.keys(this.upServers).length &gt; 0;
}
/**
* @ignore
*/
Mongos.prototype.isAutoReconnect = function() {
return true;
}
/**
* @ignore
*/
Mongos.prototype.canWrite = Mongos.prototype.isConnected;
/**
* @ignore
*/
Mongos.prototype.canRead = Mongos.prototype.isConnected;
/**
* @ignore
*/
Mongos.prototype.isDestroyed = function() {
return this._serverState == &#x27;destroyed&#x27;;
}
/**
* @ignore
*/
Mongos.prototype.checkoutWriter = function() {
// Checkout a writer
var keys = Object.keys(this.upServers);
if(keys.length == 0) return null;
return this.upServers[keys[0]].checkoutWriter();
}
/**
* @ignore
*/
Mongos.prototype.checkoutReader = function(read) {
// If read is set to null default to primary
read = read || &#x27;primary&#x27;
// If we have a read preference object unpack it
if(read != null &amp;&amp; typeof read == &#x27;object&#x27; &amp;&amp; read[&#x27;_type&#x27;] == &#x27;ReadPreference&#x27;) {
// Validate if the object is using a valid mode
if(!read.isValid()) throw new Error(&quot;Illegal readPreference mode specified, &quot; + JSON.stringify(read));
} else if(!ReadPreference.isValid(read)) {
throw new Error(&quot;Illegal readPreference mode specified, &quot; + JSON.stringify(read));
}
// Checkout a writer
var keys = Object.keys(this.upServers);
if(keys.length == 0) return null;
return this.upServers[keys[0]].checkoutWriter();
}
/**
* @ignore
*/
Mongos.prototype.close = function(callback) {
var self = this;
// Set server status as disconnected
this._serverState = &#x27;destroyed&#x27;;
// Number of connections to close
var numberOfConnectionsToClose = self.servers.length;
// If we have a ha process running kill it
if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId);
self._replicasetTimeoutId = null;
// Emit close event
processor(function() {
self._emitAcrossAllDbInstances(self, null, &quot;close&quot;, null, null, true)
});
// Flush out any remaining call handlers
self._flushAllCallHandlers(utils.toError(&quot;Connection Closed By Application&quot;));
// No up servers just return
if(Object.keys(this.upServers) == 0) {
return callback(null);
}
// Close all the up servers
for(var name in this.upServers) {
this.upServers[name].close(function(err, result) {
numberOfConnectionsToClose = numberOfConnectionsToClose - 1;
// Callback if we have one defined
if(numberOfConnectionsToClose == 0 &amp;&amp; typeof callback == &#x27;function&#x27;) {
callback(null);
}
});
}
}
/**
* @ignore
* Return the used state
*/
Mongos.prototype._isUsed = function() {
return this._used;
}
exports.Mongos = Mongos;
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>

File Metadata

Mime Type
text/html
Expires
Mon, Nov 9, 13:42 (5 h, 11 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1182214
Default Alt Text
bin_node_modules_mongodb_lib_mongodb_connection_mongos.js.html (38 KB)

Event Timeline