├── .gitignore ├── LICENSE ├── README.md ├── example_config.json ├── index.js ├── lib ├── connection.js ├── logger.js ├── proxy.js ├── reply_message.js └── wire_message.js ├── package.json └── test ├── runner.js └── tests └── connection_tests.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | data/ 22 | db/ 23 | 24 | # Dependency directory 25 | # Commenting this out is preferred by some people, see 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 27 | node_modules 28 | 29 | # Users Environment Variables 30 | .lock-wscript 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MongoDB Proxy 2 | 3 | The MongoDB proxy was developed to help drivers who do not have either replicaset or advanced authentication support for MongoDB. It aims to make it possible for any basic mongodb driver to be able to tap into the advanced features provided by MongoDB. 4 | 5 | ## Design of Proxy 6 | 7 | The Proxy uses the node.js mongodb native driver to provide the glue between your driver and MongoDB. For each connection you open to the proxy an equal connection is opened to the MongoDB server on the other side (or in the case of a replicaset 1 connection per member in the Replicaset). The takes care of all the complex authentication mechanisms as well as managing connectivity to the MongoDB topology. 8 | 9 | The proxy identifies itself to the driver as a `mongos` proxy and the connecting driver can route queries sending the `$readPreference` field in the query. 10 | 11 | ## Proxy Configuration Settings 12 | 13 | ### JSON Configuration file settings 14 | 15 | The proxy configuration `json` file options 16 | 17 | | Option | Description | 18 | |------------------|-------------| 19 | | port | The tcp port the proxy binds to | 20 | | uri | The MongoDB Topology URI (See driver docs for parameters) | 21 | | bind_to | The tcp address to bind the proxy to | 22 | | log_level | The logging level [error/info/debug] | 23 | | log_file | The log file to append to | 24 | | auth.sslCA | Location of certificate authority file | 25 | | auth.sslCert | Location of public certificate file we are presenting | 26 | | auth.sslKey | Location of private certificate file we are presenting | 27 | | auth.sslPass | SSL Certificate password | 28 | | auth.sslValidate | Validate mongod certificate | 29 | 30 | Example configuration file 31 | 32 | ```js 33 | { 34 | "port": 51000 35 | , "uri": "mongodb://localhost:27017/test" 36 | , "bind_to": "127.0.0.1" 37 | , "auth": { 38 | "sslCA": "./ca.pem" 39 | , "sslCert": "./cert.pem" 40 | , "sslKey": "./cert.pem" 41 | , "sslPass": "somekey" 42 | , "sslValidate": false 43 | } 44 | , "log_level": "error" 45 | , "log_file": "./proxy.log" 46 | } 47 | ``` 48 | 49 | ### Command line configuration file settings 50 | 51 | ``` 52 | Usage: node ./index.js 53 | 54 | Examples: 55 | node ./index.js -p 51000 -b 127.0.0.1 -u mongodb://localhost:27017 Run proxy on port 51000 and bind to 127.0.0.1 56 | 57 | 58 | Options: 59 | -p, --port Port proxy is running on [default: 51000] 60 | -u, --uri Connection url to mongodb [default: "mongodb://localhost:27017/test"] 61 | -b, --bind_to Bind to host interface [default: "127.0.0.1"] 62 | -c, --config JSON configuration file 63 | --auth-sslCA Location of certificate authority file 64 | --auth-sslCert Location of public certificate file we are presenting 65 | --auth-sslKey Location of private certificate file we are presenting 66 | --auth-sslPass SSL Certificate password 67 | --auth-sslValidate Validate mongod certificate [default: false] 68 | --log_level [default: "error"] 69 | --log_file 70 | ``` 71 | 72 | ### Simple Example of running the proxy 73 | 74 | Start up a mongod process 75 | 76 | ``` 77 | mkdir data 78 | mongod --dbpath=./data 79 | ``` 80 | 81 | Start up the proxy 82 | 83 | ``` 84 | node ./index.js -u mongodb://localhost:27017/test -p 61000 85 | ``` 86 | 87 | Connect to MongoDB via the proxy using the shell 88 | 89 | ``` 90 | mongo --port 61000 91 | ``` -------------------------------------------------------------------------------- /example_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "port": 51000 3 | , "uri": "mongodb://localhost:27017/test" 4 | , "bind_to": "127.0.0.1" 5 | , "auth": { 6 | "sslCA": "./ca.pem" 7 | , "sslCert": "./cert.pem" 8 | , "sslKey": "./cert.pem" 9 | , "sslPass": "somekey" 10 | , "sslValidate": false 11 | } 12 | , "log_level": "error" 13 | , "log_file": "./proxy.log" 14 | } -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var Proxy = require('./lib/proxy') 2 | , fs = require('fs'); 3 | 4 | // Start the 5 | var yargs = require('yargs') 6 | .usage('Start a proxy.\nUsage: $0') 7 | .example('$0 -p 51000 -b 127.0.0.1 -u mongodb://localhost:27017', 'Run proxy on port 51000 and bind to 127.0.0.1') 8 | // The Monitor process port 9 | .describe('p', 'Port proxy is running on') 10 | .default('p', 51000) 11 | .alias('p', 'port') 12 | // Number of processes to use in the execution 13 | .describe('u', 'Connection url to mongodb') 14 | .default('u', 'mongodb://localhost:27017/test') 15 | .alias('u', 'uri') 16 | // Run all the processes locally 17 | .describe('b', 'Bind to host interface') 18 | .default('b', '127.0.0.1') 19 | .alias('b', 'bind_to') 20 | // Allow us to specify a json configuration file 21 | .describe('c', 'JSON configuration file') 22 | .alias('c', 'config') 23 | // SSL Cert options 24 | .describe('auth-sslCA', 'Location of certificate authority file') 25 | .describe('auth-sslCert', 'Location of public certificate file we are presenting') 26 | .describe('auth-sslKey', 'Location of private certificate file we are presenting') 27 | .describe('auth-sslPass', 'SSL Certificate password') 28 | .describe('auth-sslValidate', 'Validate mongod certificate') 29 | .default('auth-sslValidate', false) 30 | // Logger information 31 | .describe('log_level') 32 | .default('log_level', 'error') 33 | .describe('log_file') 34 | 35 | // Parse options 36 | var parseOptions = function(argv) { 37 | // Do we have a configuration file 38 | if(argv.c) return JSON.parse(fs.readFileSync(argv.c, 'utf8')); 39 | 40 | // Create options object from cmd line options 41 | var options = {auth: {}}; 42 | 43 | // Let's create the final object 44 | if(argv.p) options.port = argv.p; 45 | if(argv.u) options.uri = argv.u; 46 | if(argv.b) options.bind_to = argv.b; 47 | if(argv.debug) options.debug = argv.debug; 48 | 49 | // Set the authentication options 50 | if(argv['auth-sslCA']) options.auth.sslCA = argv['auth-sslCA']; 51 | if(argv['auth-sslCert']) options.auth.sslCert = argv['auth-sslCert']; 52 | if(argv['auth-sslKey']) options.auth.sslKey = argv['auth-sslKey']; 53 | if(argv['auth-sslPass']) options.auth.sslCA = argv['auth-sslPass']; 54 | options.auth.sslValidate = argv['auth-sslValidate']; 55 | 56 | // Logger options 57 | if(argv['log_level']) options['log_level'] = argv['log_level']; 58 | if(argv['log_file']) options['log_file'] = argv['log_file']; 59 | 60 | // Return the options 61 | return options; 62 | } 63 | 64 | // Get parsed arguments 65 | var argv = yargs.argv 66 | 67 | // List help 68 | if(argv.h) return console.log(yargs.help()) 69 | 70 | // Parse the options and generate final field 71 | var options = parseOptions(argv); 72 | 73 | // Create and start the proxy 74 | new Proxy(options).start(); -------------------------------------------------------------------------------- /lib/connection.js: -------------------------------------------------------------------------------- 1 | var WireMessage = require('./wire_message') 2 | , ReplyMessage = require('./reply_message') 3 | , ReadPreference = require('mongodb-core').ReadPreference 4 | , MongoClient = require('mongodb').MongoClient 5 | , f = require('util').format 6 | , m = require('mongodb'); 7 | 8 | /* 9 | * Connection wrapper 10 | */ 11 | var Connection = function(proxy, connection, logger) { 12 | var self = this; 13 | // The actual connection 14 | this.connection = connection; 15 | // Set up the message handler 16 | this.proxy = proxy; 17 | 18 | // Store logger 19 | this.logger = logger; 20 | 21 | // Get server config 22 | this.db = proxy.db; 23 | 24 | // Connections by cursorId 25 | this.connections = {} 26 | 27 | // Connection details 28 | var remoteAddress = this.connection.remoteAddress; 29 | var remotePort = this.connection.remotePort; 30 | 31 | // Create a MongoClient 32 | MongoClient.connect(proxy.options.uri, { 33 | server: { poolSize: 1 }, 34 | replSet: { poolSize: 1 }, 35 | mongos: { poolSize: 1 } 36 | }, function(err, db) { 37 | if(err) { 38 | if(self.logger.isError()) self.logger.error(f('failed to connect to MongoDB topology for client connection %s:%s' 39 | , remoteAddress 40 | , remotePort)); 41 | return connection.destroy(); 42 | } 43 | 44 | // Save the db reference 45 | self.db = db; 46 | 47 | // Log info about mongodb connection 48 | if(self.logger.isInfo()) self.logger.info(f('correctly connected to MongoDB topology for client connection %s:%s' 49 | , remoteAddress 50 | , remotePort)); 51 | 52 | // Unpack the mongodb-core 53 | if(self.db.serverConfig instanceof m.Server) { 54 | self.topology = self.db.serverConfig.s.server; 55 | } else if(self.db.serverConfig instanceof m.ReplSet) { 56 | self.topology = self.db.serverConfig.s.replset; 57 | } else if(this.db.serverConfig instanceof m.Mongos) { 58 | self.topology = self.db.serverConfig.s.mongos; 59 | } 60 | 61 | // Connection closed by peer 62 | connection.on('end', function() { 63 | if(self.logger.isInfo()) self.logger.info(f('connection closed from %s:%s' 64 | , remoteAddress 65 | , remotePort)); 66 | // Shut down db connection 67 | db.close(); 68 | }); 69 | 70 | // Data handler 71 | connection.on('data', dataHandler(self)); 72 | 73 | // Data handler 74 | connection.on('parseError', function(err) { 75 | if(self.logger.isError()) self.logger.error(f('connection closed from from %s:%s due to parseError', this.remoteAddress, this.remotePort)); 76 | connection.destroy(); 77 | }); 78 | }); 79 | } 80 | 81 | // Checks 82 | var ismaster = new Buffer('ismaster'); 83 | var readPreference = new Buffer('$readPreference'); 84 | 85 | Connection.prototype.messageHandler = function(data) { 86 | var self = this; 87 | if(self.logger.isDebug()) 88 | self.logger.debug(f('client message decoded: [%s]', data.toString('hex'))); 89 | 90 | // Get the request Id 91 | var message = new WireMessage(data); 92 | 93 | // We need this to build a response message 94 | var requestId = message.requestID(); 95 | var responseTo = message.responseTo(); 96 | var opCode = message.opCode(); 97 | 98 | // Check if we have an ismaster command 99 | if(bufferIndexOf(data, ismaster, 0) != -1) { 100 | if(self.logger.isDebug()) 101 | self.logger.debug(f('client sent ismaster command')); 102 | 103 | // Create the response document 104 | var ismasterResponse = { 105 | "ismaster" : true, 106 | "msg" : "isdbgrid", 107 | "maxBsonObjectSize" : 16777216, 108 | "maxMessageSizeBytes" : 48000000, 109 | "maxWriteBatchSize" : 1000, 110 | "localTime" : new Date(), 111 | "maxWireVersion" : 3, 112 | "minWireVersion" : 0, 113 | "ok" : 1 114 | } 115 | 116 | // Create a new Message Response and reply to the ismaster 117 | var reply = new ReplyMessage(self.topology.bson, requestId, responseTo, [ismasterResponse]); 118 | // Write it to the connection 119 | try { 120 | self.connection.write(reply.toBin()); 121 | } catch(err) { 122 | if(self.logger.isError()) 123 | self.logger.error(f('failed to write to client connection %s:%s' 124 | , self.connection.remoteAddress, self.connection.remotePort)); 125 | return; 126 | } 127 | } else { 128 | // No read preference 129 | var preference = null; 130 | // Read preference index 131 | var rIndex = bufferIndexOf(data, readPreference, 0); 132 | 133 | // Check if we have a $readpreference 134 | if(rIndex != -1) { 135 | // We need to snip out the bson object and decode it to know the routing 136 | // of the query, locate the length part of the doc 137 | rIndex = rIndex + '$readPreference'.length + 1; 138 | // Decode the read preference doc length 139 | var readPreferenceDocLength = data[rIndex] | data[rIndex + 1] << 8 | data[rIndex + 2] << 16 | data[rIndex + 3] << 24; 140 | // Deserialize bson of read preference doc 141 | var doc = self.topology.bson.deserialize(data.slice(rIndex, rIndex + readPreferenceDocLength)); 142 | // Create the read Preference 143 | preference = new ReadPreference(doc.mode, doc.tags); 144 | } 145 | 146 | // Client message 147 | var clientMessage = new WireMessage(data); 148 | var server = null; 149 | 150 | // We have a OP_GETMORE pick the right server callback pool 151 | if(clientMessage.opCode() == 2005) { 152 | server = self.connections[clientMessage.getMoreCursorID().toString()].server; 153 | } else { 154 | try { 155 | server = this.topology.getServer({ 156 | readPreference: preference 157 | }); 158 | } catch(err) { 159 | if(self.logger.isError()) 160 | self.logger.error(f('routing OP_CODE=%s with readPreference [%s] to a server failed with error = [%s]' 161 | , clientMessage.opCode(), JSON.stringify(preference), err)); 162 | return; 163 | } 164 | } 165 | 166 | if(self.logger.isDebug()) 167 | self.logger.debug(f('routing OP_CODE=%s with readPreference [%s] to server %s' 168 | , clientMessage.opCode(), JSON.stringify(preference), server.name)); 169 | 170 | // No server able to service the result 171 | if(server == null) { 172 | if(self.logger.isError()) 173 | self.logger.error(f('routing OP_CODE=%s with readPreference [%s] to a server failed due to no server found for readPreference' 174 | , clientMessage.opCode(), JSON.stringify(preference))); 175 | return; 176 | } 177 | 178 | // Associate responses with specfic connections 179 | var callbackFunction = function(_server, _clientMessage, _clientConnection) { 180 | // Store a new connection if needed 181 | var connection = null; 182 | 183 | // Client message 184 | var clientMessage = new WireMessage(_clientMessage); 185 | 186 | // If we have a getmore 187 | if(clientMessage.opCode() == 2005) { 188 | // Unpack the cursor Id 189 | var curs = clientMessage.getMoreCursorID(); 190 | // Use the pinned connection 191 | try { 192 | self.connections[curs.toString()].conn.connection.write(_clientMessage); 193 | } catch(err) { 194 | if(self.logger.isError()) 195 | self.logger.error(f('failed to write to client connection %s:%s' 196 | , self.connections[curs.toString()].conn.connection.remoteAddress 197 | , self.connections[curs.toString()].conn.connection.remotePort)); 198 | return; 199 | } 200 | } else if(clientMessage.opCode() == 2004) { 201 | // Get the connection 202 | connection = server.getConnection(); 203 | // Write the data to the connection 204 | if(connection.isConnected()) 205 | connection.connection.write(_clientMessage); 206 | } 207 | 208 | // 209 | // Return the handler 210 | return function(err, data) { 211 | if(err) return; 212 | // Extract WireProtocol information 213 | var responseMessage = new WireMessage(data.raw); 214 | // Extract the cursor 215 | var cursorID = responseMessage.responseCursorID(); 216 | 217 | // If we have a zero cursorId delete any pinned connections 218 | if(cursorID.isZero() 219 | && (clientMessage.opCode() == 2004 || clientMessage.opCode() == 2005)) { 220 | delete self.connections[clientMessage.getMoreCursorID()]; 221 | } else if(!cursorID.isZero() 222 | && self.connections[cursorID] == null && (clientMessage.opCode() == 2004 || clientMessage.opCode() == 2005)) { 223 | self.connections[cursorID] = { 224 | conn: connection 225 | , server: _server 226 | } 227 | } 228 | 229 | // Return the result 230 | try { 231 | _clientConnection.write(data.raw); 232 | } catch(err) { 233 | if(self.logger.isError()) 234 | self.logger.error(f('failed to write to client connection %s:%s' 235 | , _clientConnection.remoteAddress, _clientConnection.remotePort)); 236 | return; 237 | } 238 | } 239 | } 240 | 241 | // Get the callbacks 242 | var callbacks = server.s.callbacks; 243 | // Register a callback 244 | callbacks.register(requestId, callbackFunction(server, data, this.connection)); 245 | } 246 | } 247 | 248 | /* 249 | * Buffer indexOf 250 | */ 251 | var bufferIndexOf = function(buf,search,offset){ 252 | offset = offset||0 253 | 254 | var m = 0; 255 | var s = -1; 256 | for(var i=offset;i -1 && buf.length - s < search.length) return -1; 268 | return s; 269 | } 270 | 271 | /* 272 | * Read wire protocol message off the sockets 273 | */ 274 | var dataHandler = function(self) { 275 | return function(data) { 276 | // Parse until we are done with the data 277 | while(data.length > 0) { 278 | // If we still have bytes to read on the current message 279 | if(self.bytesRead > 0 && self.sizeOfMessage > 0) { 280 | // Calculate the amount of remaining bytes 281 | var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; 282 | // Check if the current chunk contains the rest of the message 283 | if(remainingBytesToRead > data.length) { 284 | // Copy the new data into the exiting buffer (should have been allocated when we know the message size) 285 | data.copy(self.buffer, self.bytesRead); 286 | // Adjust the number of bytes read so it point to the correct index in the buffer 287 | self.bytesRead = self.bytesRead + data.length; 288 | 289 | // Reset state of buffer 290 | data = new Buffer(0); 291 | } else { 292 | // Copy the missing part of the data into our current buffer 293 | data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); 294 | // Slice the overflow into a new buffer that we will then re-parse 295 | data = data.slice(remainingBytesToRead); 296 | 297 | // Emit current complete message 298 | try { 299 | var emitBuffer = self.buffer; 300 | // Reset state of buffer 301 | self.buffer = null; 302 | self.sizeOfMessage = 0; 303 | self.bytesRead = 0; 304 | self.stubBuffer = null; 305 | // Emit the buffer 306 | self.messageHandler(emitBuffer, self); 307 | } catch(err) { 308 | var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ 309 | sizeOfMessage:self.sizeOfMessage, 310 | bytesRead:self.bytesRead, 311 | stubBuffer:self.stubBuffer}}; 312 | // We got a parse Error fire it off then keep going 313 | self.emit("parseError", errorObject, self); 314 | } 315 | } 316 | } else { 317 | // Stub buffer is kept in case we don't get enough bytes to determine the 318 | // size of the message (< 4 bytes) 319 | if(self.stubBuffer != null && self.stubBuffer.length > 0) { 320 | // If we have enough bytes to determine the message size let's do it 321 | if(self.stubBuffer.length + data.length > 4) { 322 | // Prepad the data 323 | var newData = new Buffer(self.stubBuffer.length + data.length); 324 | self.stubBuffer.copy(newData, 0); 325 | data.copy(newData, self.stubBuffer.length); 326 | // Reassign for parsing 327 | data = newData; 328 | 329 | // Reset state of buffer 330 | self.buffer = null; 331 | self.sizeOfMessage = 0; 332 | self.bytesRead = 0; 333 | self.stubBuffer = null; 334 | 335 | } else { 336 | 337 | // Add the the bytes to the stub buffer 338 | var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); 339 | // Copy existing stub buffer 340 | self.stubBuffer.copy(newStubBuffer, 0); 341 | // Copy missing part of the data 342 | data.copy(newStubBuffer, self.stubBuffer.length); 343 | // Exit parsing loop 344 | data = new Buffer(0); 345 | } 346 | } else { 347 | if(data.length > 4) { 348 | // Retrieve the message size 349 | // var sizeOfMessage = data.readUInt32LE(0); 350 | var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; 351 | // If we have a negative sizeOfMessage emit error and return 352 | if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { 353 | var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ 354 | sizeOfMessage: sizeOfMessage, 355 | bytesRead: self.bytesRead, 356 | stubBuffer: self.stubBuffer}}; 357 | // We got a parse Error fire it off then keep going 358 | self.emit("parseError", errorObject, self); 359 | return; 360 | } 361 | 362 | // Ensure that the size of message is larger than 0 and less than the max allowed 363 | if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { 364 | self.buffer = new Buffer(sizeOfMessage); 365 | // Copy all the data into the buffer 366 | data.copy(self.buffer, 0); 367 | // Update bytes read 368 | self.bytesRead = data.length; 369 | // Update sizeOfMessage 370 | self.sizeOfMessage = sizeOfMessage; 371 | // Ensure stub buffer is null 372 | self.stubBuffer = null; 373 | // Exit parsing loop 374 | data = new Buffer(0); 375 | 376 | } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { 377 | try { 378 | var emitBuffer = data; 379 | // Reset state of buffer 380 | self.buffer = null; 381 | self.sizeOfMessage = 0; 382 | self.bytesRead = 0; 383 | self.stubBuffer = null; 384 | // Exit parsing loop 385 | data = new Buffer(0); 386 | // Emit the message 387 | self.messageHandler(emitBuffer, self); 388 | } catch (err) { 389 | var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ 390 | sizeOfMessage:self.sizeOfMessage, 391 | bytesRead:self.bytesRead, 392 | stubBuffer:self.stubBuffer}}; 393 | // We got a parse Error fire it off then keep going 394 | self.emit("parseError", errorObject, self); 395 | } 396 | } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { 397 | var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ 398 | sizeOfMessage:sizeOfMessage, 399 | bytesRead:0, 400 | buffer:null, 401 | stubBuffer:null}}; 402 | // We got a parse Error fire it off then keep going 403 | self.emit("parseError", errorObject, self); 404 | 405 | // Clear out the state of the parser 406 | self.buffer = null; 407 | self.sizeOfMessage = 0; 408 | self.bytesRead = 0; 409 | self.stubBuffer = null; 410 | // Exit parsing loop 411 | data = new Buffer(0); 412 | } else { 413 | var emitBuffer = data.slice(0, sizeOfMessage); 414 | // Reset state of buffer 415 | self.buffer = null; 416 | self.sizeOfMessage = 0; 417 | self.bytesRead = 0; 418 | self.stubBuffer = null; 419 | // Copy rest of message 420 | data = data.slice(sizeOfMessage); 421 | // Emit the message 422 | self.messageHandler(emitBuffer, self); 423 | } 424 | } else { 425 | // Create a buffer that contains the space for the non-complete message 426 | self.stubBuffer = new Buffer(data.length) 427 | // Copy the data to the stub buffer 428 | data.copy(self.stubBuffer, 0); 429 | // Exit parsing loop 430 | data = new Buffer(0); 431 | } 432 | } 433 | } 434 | } 435 | } 436 | } 437 | 438 | module.exports = Connection; -------------------------------------------------------------------------------- /lib/logger.js: -------------------------------------------------------------------------------- 1 | var f = require('util').format 2 | , fs = require('fs'); 3 | 4 | var Logger = function(logger, level) { 5 | this.logger = logger; 6 | this.level = level; 7 | } 8 | 9 | Logger.prototype.isError = function() { 10 | return this.level == 'error'; 11 | } 12 | 13 | Logger.prototype.isInfo = function() { 14 | return this.level == 'info'; 15 | } 16 | 17 | Logger.prototype.isDebug = function() { 18 | return this.level == 'debug'; 19 | } 20 | 21 | Logger.prototype.error = function(message) { 22 | this.logger.log(f('[ERROR] %s %s', new Date(), message)); 23 | } 24 | 25 | Logger.prototype.info = function(message) { 26 | this.logger.log(f('[INFO] %s %s', new Date(), message)); 27 | } 28 | 29 | Logger.prototype.debug = function(message) { 30 | this.logger.log(f('[DEBUG] %s %s', new Date(), message)); 31 | } 32 | 33 | Logger.createFileLogger = function(file, level) { 34 | return new Logger(new FileLogger(file), level); 35 | } 36 | 37 | Logger.createStdioLogger = function(level) { 38 | return new Logger(new StdioLogger(), level); 39 | } 40 | 41 | /* 42 | * File logger 43 | */ 44 | var FileLogger = function(file) { 45 | this.file = file; 46 | } 47 | 48 | FileLogger.prototype.log = function(message) { 49 | fs.appendFileSync(this.file, f("%s\n", message)); 50 | } 51 | 52 | /* 53 | * StdioLogger 54 | */ 55 | var StdioLogger = function() { 56 | } 57 | 58 | StdioLogger.prototype.log = function(message) { 59 | console.log(message); 60 | } 61 | 62 | module.exports = Logger; -------------------------------------------------------------------------------- /lib/proxy.js: -------------------------------------------------------------------------------- 1 | var MongoClient = require('mongodb').MongoClient 2 | , net = require('net') 3 | , f = require('util').format 4 | , Logger = require('./logger') 5 | , Connection = require('./connection'); 6 | 7 | var Message = function() { 8 | this.bytes = new Buffer(); 9 | } 10 | 11 | Message.prototype.length = function() { 12 | return this.bytes.length; 13 | } 14 | 15 | var Proxy = function(options) { 16 | this.options = options; 17 | this.debug = options.debug; 18 | 19 | // Create log file based logger or stdio 20 | if(options.log_file) { 21 | this.logger = Logger.createFileLogger(options.log_file, options.log_level); 22 | } else { 23 | this.logger = Logger.createStdioLogger(options.log_level); 24 | } 25 | } 26 | 27 | Proxy.prototype.start = function(callback) { 28 | var self = this; 29 | 30 | // Create a new tcp server 31 | self.server = net.createServer(function(conn) { 32 | // if(self.debug) console.log('client connected'); 33 | if(self.logger.isInfo()) self.logger.info(f('client connected from %s:%s', conn.remoteAddress, conn.remotePort)); 34 | 35 | // Create connection object 36 | var connection = new Connection(self, conn, self.logger); 37 | }); 38 | 39 | // Listen to server 40 | self.server.listen(self.options.port, self.options.bind_to, callback); 41 | } 42 | 43 | module.exports = Proxy; -------------------------------------------------------------------------------- /lib/reply_message.js: -------------------------------------------------------------------------------- 1 | var Buffer = require('buffer').Buffer; 2 | 3 | var ReplyMessage = function(bson, requestId, responseTo, documents) { 4 | this.bson = bson; 5 | this.requestId = requestId; 6 | this.responseTo = responseTo; 7 | this.documents = documents; 8 | } 9 | 10 | // 11 | // Uses a single allocated buffer for the process, avoiding multiple memory allocations 12 | ReplyMessage.prototype.toBin = function() { 13 | // var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); 14 | var length = 16 + 4 + 8 + 4 + 4; 15 | 16 | // Calculate documents length 17 | for(var i = 0; i < this.documents.length; i++) { 18 | length += this.bson.calculateObjectSize(this.documents[0]); 19 | } 20 | 21 | // Create command buffer 22 | var index = 0; 23 | // Allocate buffer 24 | var _buffer = new Buffer(length); 25 | 26 | // Write header length 27 | _buffer[index + 3] = (length >> 24) & 0xff; 28 | _buffer[index + 2] = (length >> 16) & 0xff; 29 | _buffer[index + 1] = (length >> 8) & 0xff; 30 | _buffer[index] = (length) & 0xff; 31 | index = index + 4; 32 | 33 | // Write responseTo as requestId 34 | _buffer[index + 3] = (this.responseTo >> 24) & 0xff; 35 | _buffer[index + 2] = (this.responseTo >> 16) & 0xff; 36 | _buffer[index + 1] = (this.responseTo >> 8) & 0xff; 37 | _buffer[index] = (this.responseTo) & 0xff; 38 | index = index + 4; 39 | 40 | // Write requestId as responseTo 41 | _buffer[index + 3] = (this.requestId >> 24) & 0xff; 42 | _buffer[index + 2] = (this.requestId >> 16) & 0xff; 43 | _buffer[index + 1] = (this.requestId >> 8) & 0xff; 44 | _buffer[index] = (this.requestId) & 0xff; 45 | index = index + 4; 46 | 47 | // Write opCode OP_REPLY 48 | _buffer[index + 3] = (1 >> 24) & 0xff; 49 | _buffer[index + 2] = (1 >> 16) & 0xff; 50 | _buffer[index + 1] = (1 >> 8) & 0xff; 51 | _buffer[index] = (1) & 0xff; 52 | index = index + 4; 53 | 54 | // Write reponseFlags 55 | _buffer[index + 3] = (0 >> 24) & 0xff; 56 | _buffer[index + 2] = (0 >> 16) & 0xff; 57 | _buffer[index + 1] = (0 >> 8) & 0xff; 58 | _buffer[index] = (0) & 0xff; 59 | index = index + 4; 60 | 61 | // Write cursorId 0 part 1 62 | _buffer[index + 3] = (0 >> 24) & 0xff; 63 | _buffer[index + 2] = (0 >> 16) & 0xff; 64 | _buffer[index + 1] = (0 >> 8) & 0xff; 65 | _buffer[index] = (0) & 0xff; 66 | index = index + 4; 67 | 68 | // Write cursorId 0 part 2 69 | _buffer[index + 3] = (0 >> 24) & 0xff; 70 | _buffer[index + 2] = (0 >> 16) & 0xff; 71 | _buffer[index + 1] = (0 >> 8) & 0xff; 72 | _buffer[index] = (0) & 0xff; 73 | index = index + 4; 74 | 75 | // Starting from 76 | _buffer[index + 3] = (0 >> 24) & 0xff; 77 | _buffer[index + 2] = (0 >> 16) & 0xff; 78 | _buffer[index + 1] = (0 >> 8) & 0xff; 79 | _buffer[index] = (0) & 0xff; 80 | index = index + 4; 81 | 82 | // Write number of documents returned 83 | _buffer[index + 3] = (this.documents.length >> 24) & 0xff; 84 | _buffer[index + 2] = (this.documents.length >> 16) & 0xff; 85 | _buffer[index + 1] = (this.documents.length >> 8) & 0xff; 86 | _buffer[index] = (this.documents.length) & 0xff; 87 | index = index + 4; 88 | 89 | // Write all the documents 90 | for(var i = 0; i < this.documents.length; i++) { 91 | var buffer = this.bson.serialize(this.documents[i], false, true); 92 | // Write the document into the buffer 93 | buffer.copy(_buffer, index, 0, buffer.length); 94 | // Adjust the index 95 | index = index + buffer.length; 96 | } 97 | 98 | // Return buffer 99 | return _buffer; 100 | } 101 | 102 | module.exports = ReplyMessage; -------------------------------------------------------------------------------- /lib/wire_message.js: -------------------------------------------------------------------------------- 1 | var Long = require('mongodb').Long; 2 | 3 | var WireMessage = function(data) { 4 | this.data = data; 5 | } 6 | 7 | WireMessage.prototype.messageLength = function() { 8 | var index = 0; 9 | // Return the messageLength 10 | return this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 11 | } 12 | 13 | WireMessage.prototype.requestID = function() { 14 | var index = 4; 15 | // Return the messageLength 16 | return this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 17 | } 18 | 19 | WireMessage.prototype.responseTo = function() { 20 | var index = 8; 21 | // Return the messageLength 22 | return this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 23 | } 24 | 25 | WireMessage.prototype.opCode = function() { 26 | var index = 12; 27 | // Return the messageLength 28 | return this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 29 | } 30 | 31 | WireMessage.prototype.responseResponseFlags = function() { 32 | var index = 16; 33 | // Return the messageLength 34 | return this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 35 | } 36 | 37 | WireMessage.prototype.responseCursorID = function() { 38 | var index = 20; 39 | 40 | // Unpack the cursor 41 | var lowBits = this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 42 | index = index + 4; 43 | var highBits = this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 44 | index = index + 4; 45 | 46 | // Create long object 47 | return new Long(lowBits, highBits); 48 | } 49 | 50 | WireMessage.prototype.getMoreCursorID = function() { 51 | var index = this.data.length - 8; 52 | // Unpack the cursor 53 | var lowBits = this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 54 | index = index + 4; 55 | var highBits = this.data[index] | this.data[index + 1] << 8 | this.data[index + 2] << 16 | this.data[index + 3] << 24; 56 | index = index + 4; 57 | 58 | // Create long object 59 | return new Long(lowBits, highBits); 60 | } 61 | 62 | module.exports = WireMessage; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mongodb-proxy", 3 | "version": "1.0.0", 4 | "description": "MongoDB Proxy for thirdparty driver", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/christkv/mongodb-proxy.git" 12 | }, 13 | "keywords": [ 14 | "mongodb", 15 | "proxy", 16 | "replicaset", 17 | "mongos" 18 | ], 19 | "dependencies": { 20 | "mongodb": "~2.0" 21 | , "mongodb-core": "~1.1" 22 | , "yargs": "~1.3" 23 | }, 24 | "devDependencies": { 25 | "integra": "0.1.8" 26 | , "optimist": "0.6.1" 27 | , "mongodb-version-manager": "^0.5.0" 28 | , "mongodb-tools": "~1.0" 29 | , "mkdirp": "0.5.0" 30 | , "rimraf": "2.2.6" 31 | }, 32 | "author": "Christian Kvalheim", 33 | "license": "Apache 2.0", 34 | "bugs": { 35 | "url": "https://github.com/christkv/mongodb-proxy/issues" 36 | }, 37 | "homepage": "https://github.com/christkv/mongodb-proxy" 38 | } 39 | -------------------------------------------------------------------------------- /test/runner.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var Runner = require('integra').Runner 4 | , FileFilter = require('integra').FileFilter 5 | , FileFilter = require('integra').FileFilter 6 | , TestNameFilter = require('integra').TestNameFilter 7 | , rimraf = require('rimraf') 8 | , m = require('mongodb-version-manager') 9 | , f = require('util').format; 10 | 11 | var argv = require('optimist') 12 | .usage('Usage: $0 -n [name] -f [filename]') 13 | .argv; 14 | 15 | var shallowClone = function(obj) { 16 | var copy = {}; 17 | for(var name in obj) copy[name] = obj[name]; 18 | return copy; 19 | } 20 | 21 | // Skipping parameters 22 | var startupOptions = { 23 | skipStartup: true 24 | , skipRestart: true 25 | , skipShutdown: true 26 | , skip: false 27 | } 28 | 29 | /** 30 | * Standalone MongoDB Configuration 31 | */ 32 | var createConfiguration = function(options) { 33 | options = options || {}; 34 | 35 | // Create the configuration 36 | var Configuration = function(context) { 37 | var mongo = require('mongodb'); 38 | var Db = mongo.Db; 39 | var Server = mongo.Server; 40 | var Logger = mongo.Logger; 41 | var ServerManager = require('mongodb-tools').ServerManager; 42 | var database = "integration_tests"; 43 | var url = options.url || "mongodb://%slocalhost:27017/" + database; 44 | var port = options.port || 27017; 45 | var host = options.host || 'localhost'; 46 | var replicasetName = options.replicasetName || 'rs'; 47 | var writeConcern = options.writeConcern || {w:1}; 48 | var writeConcernMax = options.writeConcernMax || {w:1}; 49 | 50 | Logger.setCurrentLogger(function() {}); 51 | Logger.setLevel('debug'); 52 | 53 | // Shallow clone the options 54 | var fOptions = shallowClone(options); 55 | options.journal = false; 56 | 57 | // Override manager or use default 58 | var manager = options.manager ? options.manager() : new ServerManager(fOptions); 59 | 60 | // clone 61 | var clone = function(o) { 62 | var p = {}; for(var name in o) p[name] = o[name]; 63 | return p; 64 | } 65 | 66 | // return configuration 67 | return { 68 | manager: manager, 69 | replicasetName: replicasetName, 70 | 71 | start: function(callback) { 72 | if(startupOptions.skipStartup) return callback(); 73 | manager.start({purge:true, signal:-9, kill:true}, function(err) { 74 | if(err) throw err; 75 | callback(); 76 | }); 77 | }, 78 | 79 | stop: function(callback) { 80 | if(startupOptions.skipShutdown) return callback(); 81 | manager.stop({signal: -15}, callback); 82 | }, 83 | 84 | restart: function(options, callback) { 85 | if(typeof options == 'function') callback = options, options = {}; 86 | if(startupOptions.skipRestart) return callback(); 87 | var purge = typeof options.purge == 'boolean' ? options.purge : true; 88 | var kill = typeof options.kill == 'boolean' ? options.kill : true; 89 | manager.restart({purge:purge, kill:kill}, function() { 90 | setTimeout(function() { 91 | callback(); 92 | }, 1000); 93 | }); 94 | }, 95 | 96 | setup: function(callback) { 97 | callback(); 98 | }, 99 | 100 | teardown: function(callback) { 101 | callback(); 102 | }, 103 | 104 | newDbInstance: function(dbOptions, serverOptions) { 105 | serverOptions = serverOptions || {}; 106 | // Override implementation 107 | if(options.newDbInstance) return options.newDbInstance(dbOptions, serverOptions); 108 | 109 | // Set up the options 110 | var keys = Object.keys(options); 111 | if(keys.indexOf('sslOnNormalPorts') != -1) serverOptions.ssl = true; 112 | 113 | // Fall back 114 | var port = serverOptions && serverOptions.port || options.port || 27017; 115 | var host = serverOptions && serverOptions.host || 'localhost'; 116 | 117 | // Default topology 118 | var topology = Server; 119 | // If we have a specific topology 120 | if(options.topology) { 121 | topology = options.topology; 122 | } 123 | 124 | // Return a new db instance 125 | return new Db(database, new topology(host, port, serverOptions), dbOptions); 126 | }, 127 | 128 | newDbInstanceWithDomainSocket: function(dbOptions, serverOptions) { 129 | // Override implementation 130 | if(options.newDbInstanceWithDomainSocket) return options.newDbInstanceWithDomainSocket(dbOptions, serverOptions); 131 | 132 | // Default topology 133 | var topology = Server; 134 | // If we have a specific topology 135 | if(options.topology) { 136 | topology = options.topology; 137 | } 138 | 139 | // Fall back 140 | var host = serverOptions && serverOptions.host || "/tmp/mongodb-27017.sock"; 141 | 142 | // Set up the options 143 | var keys = Object.keys(options); 144 | if(keys.indexOf('sslOnNormalPorts') != -1) serverOptions.ssl = true; 145 | // If we explicitly testing undefined port behavior 146 | if(serverOptions && serverOptions.port == 'undefined') { 147 | return new Db('integration_tests', topology(host, undefined, serverOptions), dbOptions); 148 | } 149 | 150 | // Normal socket connection 151 | return new Db('integration_tests', topology(host, serverOptions), dbOptions); 152 | }, 153 | 154 | url: function(username, password) { 155 | // Fall back 156 | var auth = ""; 157 | 158 | if(username && password) { 159 | auth = f("%s:%s@", username, password); 160 | } 161 | 162 | return f(url, auth); 163 | }, 164 | 165 | // Additional parameters needed 166 | require: mongo, 167 | database: database || options.database, 168 | nativeParser: true, 169 | port: port, 170 | host: host, 171 | writeConcern: function() { return clone(writeConcern) }, 172 | writeConcernMax: function() { return clone(writeConcernMax) } 173 | } 174 | } 175 | 176 | return Configuration; 177 | } 178 | 179 | // Set up the runner 180 | var runner = new Runner({ 181 | logLevel:'debug' 182 | , runners: 1 183 | , failFast: true 184 | }); 185 | 186 | var testFiles =[ 187 | '/test/tests/connection_tests.js' 188 | ] 189 | 190 | // Add all the tests to run 191 | testFiles.forEach(function(t) { 192 | if(t != "") runner.add(t); 193 | }); 194 | 195 | // Exit when done 196 | runner.on('exit', function(errors, results) { 197 | process.exit(0) 198 | }); 199 | 200 | // Create a configuration 201 | var config = createConfiguration(); 202 | // If we have a test we are filtering by 203 | if(argv.f) runner.plugin(new FileFilter(argv.f)); 204 | if(argv.n) runner.plugin(new TestNameFilter(argv.n)); 205 | return runner.run(config); 206 | 207 | // Kill any running MongoDB processes and 208 | // `install $MONGODB_VERSION` || `use existing installation` || `install stable` 209 | m(function(err){ 210 | if(err) return console.error(err) && process.exit(1); 211 | 212 | m.current(function(err, version){ 213 | if(err) return console.error(err) && process.exit(1); 214 | console.log('Running tests against MongoDB version `%s`', version); 215 | // Run the configuration 216 | runner.run(config); 217 | }); 218 | }); -------------------------------------------------------------------------------- /test/tests/connection_tests.js: -------------------------------------------------------------------------------- 1 | exports.beforeTests = function(configuration, callback) { 2 | var Proxy = require('../../lib/proxy') 3 | , MongoClient = require('mongodb').MongoClient; 4 | 5 | // URI 6 | var mongodburi = "mongodb://localhost:31000/test"; 7 | // Create a new proxy and start it 8 | var proxy = new Proxy({ 9 | p: 51000, u: mongodburi, b: '127.0.0.1', debug:true 10 | }); 11 | 12 | MongoClient.connect(mongodburi, function(err, db) { 13 | db.dropDatabase(function() { 14 | // Start the proxy 15 | proxy.start(callback); 16 | }); 17 | }); 18 | } 19 | 20 | exports['Should correctly connect to proxy'] = { 21 | metadata: { requires: { } }, 22 | 23 | // The actual test we wish to run 24 | test: function(configuration, test) { 25 | var MongoClient = require('mongodb').MongoClient; 26 | 27 | // Url for connection to proxy 28 | var url = 'mongodb://localhost:51000/test'; 29 | 30 | // Connect to mongodb 31 | MongoClient.connect(url, function(err, db) { 32 | test.equal(null, err); 33 | 34 | // Perform an inserts 35 | db.collection('t').insert([{a:1}, {b:1}, {c:1}, {d:1}], function(err, r) { 36 | test.equal(null, err); 37 | 38 | db.collection('t').find({}).batchSize(2).toArray(function(err, docs) { 39 | test.equal(null, err); 40 | 41 | db.close(); 42 | test.done(); 43 | }); 44 | }); 45 | }); 46 | } 47 | } 48 | 49 | exports['Concurrent cursors'] = { 50 | metadata: { requires: { } }, 51 | 52 | // The actual test we wish to run 53 | test: function(configuration, test) { 54 | var MongoClient = require('mongodb').MongoClient; 55 | 56 | // Url for connection to proxy 57 | var url = 'mongodb://localhost:51000/test'; 58 | 59 | // Connect to mongodb 60 | MongoClient.connect(url, function(err, db) { 61 | test.equal(null, err); 62 | 63 | // Perform an inserts 64 | db.collection('t2').insert([{a:1}, {b:1}, {c:1}, {d:1}], function(err, r) { 65 | test.equal(null, err); 66 | 67 | var total = 10; 68 | var numberLeft = total; 69 | 70 | for(var i = 0; i < total; i++) { 71 | db.collection('t2').find({}).batchSize(2).toArray(function(err, docs) { 72 | test.equal(null, err); 73 | numberLeft = numberLeft - 1; 74 | 75 | if(numberLeft == 0) { 76 | db.close(); 77 | test.done(); 78 | } 79 | }); 80 | } 81 | }); 82 | }); 83 | } 84 | } 85 | 86 | exports['Should correctly connect to proxy and use readPreference secondary'] = { 87 | metadata: { requires: { } }, 88 | 89 | // The actual test we wish to run 90 | test: function(configuration, test) { 91 | var MongoClient = require('mongodb').MongoClient; 92 | 93 | // Url for connection to proxy 94 | var url = 'mongodb://localhost:51000/test?readPreference=secondary'; 95 | 96 | // Connect to mongodb 97 | MongoClient.connect(url, function(err, db) { 98 | test.equal(null, err); 99 | 100 | // Perform an inserts 101 | db.collection('t3').insert([{a:1}, {b:1}, {c:1}, {d:1}], function(err, r) { 102 | test.equal(null, err); 103 | 104 | db.collection('t3').find({}).batchSize(2).toArray(function(err, docs) { 105 | test.equal(null, err); 106 | 107 | db.close(); 108 | test.done(); 109 | }); 110 | }); 111 | }); 112 | } 113 | } 114 | 115 | exports['Concurrent cursors against secondary'] = { 116 | metadata: { requires: { } }, 117 | 118 | // The actual test we wish to run 119 | test: function(configuration, test) { 120 | var MongoClient = require('mongodb').MongoClient; 121 | 122 | // Url for connection to proxy 123 | var url = 'mongodb://localhost:51000/test?readPreference=secondary'; 124 | 125 | // Connect to mongodb 126 | MongoClient.connect(url, function(err, db) { 127 | test.equal(null, err); 128 | 129 | // Perform an inserts 130 | db.collection('t4').insert([{a:1}, {b:1}, {c:1}, {d:1}], {w:'majority'}, function(err, r) { 131 | test.equal(null, err); 132 | 133 | var total = 10; 134 | var numberLeft = total; 135 | 136 | for(var i = 0; i < total; i++) { 137 | db.collection('t4').find({}).batchSize(2).toArray(function(err, docs) { 138 | test.equal(null, err); 139 | numberLeft = numberLeft - 1; 140 | 141 | if(numberLeft == 0) { 142 | db.close(); 143 | test.done(); 144 | } 145 | }); 146 | } 147 | }); 148 | }); 149 | } 150 | } 151 | --------------------------------------------------------------------------------