├── .npmignore ├── images ├── logo.png └── logo.svg ├── src ├── printHelp.js ├── options.js ├── download.js └── topologyManagerPatch.js ├── test └── download.test.js ├── .gitignore ├── package.json ├── CHANGELOG.md ├── README.md ├── index.js └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | 3.* 2 | 4.* 3 | data 4 | 5 | README.md 6 | -------------------------------------------------------------------------------- /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vkarpov15/run-rs/HEAD/images/logo.png -------------------------------------------------------------------------------- /src/printHelp.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const options = require('./options'); 4 | 5 | module.exports = () => console.log(` 6 | Usage: run-rs [options] 7 | 8 | Options: 9 | 10 | ${stringifyOptions()} 11 | `); 12 | 13 | function stringifyOptions() { 14 | const maxLen = options.reduce((cur, opt) => Math.max(cur, opt.option.length), 0); 15 | return options. 16 | map(opt => `${padEnd(opt.option, maxLen)} ${opt.description}`). 17 | map(line => ' ' + line). 18 | join('\n'); 19 | } 20 | 21 | function padEnd(str, len) { 22 | while (str.length < len) { 23 | str = str + ' '; 24 | } 25 | return str; 26 | } -------------------------------------------------------------------------------- /test/download.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const download = require('../src/download'); 5 | const sinon = require('sinon'); 6 | 7 | const childProcess = require('child_process'); 8 | 9 | describe('download', function() { 10 | beforeEach(function() { 11 | sinon.stub(childProcess, 'execSync').callsFake(() => {}); 12 | }); 13 | 14 | afterEach(function() { 15 | childProcess.execSync.restore(); 16 | }); 17 | 18 | it('basic download', function() { 19 | let { url } = download('4.0.6', 'ubuntu1604', 'linux'); 20 | assert.equal(url, 'http://downloads.mongodb.org/linux/mongodb-linux-x86_64-4.0.6.tgz'); 21 | 22 | ({ url } = download('4.2.0', 'ubuntu1604', 'linux')); 23 | assert.equal(url, 'http://downloads.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.2.0.tgz'); 24 | }); 25 | 26 | it('osx 4.2.0', function() { 27 | let { url } = download('4.2.0', null, 'darwin'); 28 | assert.equal(url, 'https://fastdl.mongodb.org/osx/mongodb-macos-x86_64-4.2.0.tgz'); 29 | }); 30 | 31 | it('osx < 4.2.0', function() { 32 | let { url } = download('4.0.6', null, 'darwin'); 33 | assert.equal(url, 'http://downloads.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.6.tgz'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | data 64 | package-lock.json 65 | 3.* 66 | 4.* 67 | 68 | .vscode 69 | -------------------------------------------------------------------------------- /images/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | RUN 20 | 21 | RS 22 | 23 | 24 | 27 | 28 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/options.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = Object.freeze([ 4 | { option: '-v, --version [version]', description: 'Version to use' }, 5 | { 6 | option: '-k, --keep', 7 | description: 'Use this flag to skip clearing the database on startup' 8 | }, 9 | { 10 | option: '-s, --shell', 11 | description: 'Use this flag to automatically open up a MongoDB shell when the replica set is started' 12 | }, 13 | { 14 | option: '-q, --quiet', 15 | description: 'Use this flag to suppress any output after starting' 16 | }, 17 | { 18 | option: '-m, --mongod [string]', 19 | description: 'Skip downloading MongoDB and use this executable. If blank, just uses `mongod`. For instance, `run-rs --mongod` is equivalent to `run-rs --mongod mongod`' 20 | }, 21 | { 22 | option: '-n, --number [num]', 23 | description: 'Number of mongods in the replica set. 3 by default.' 24 | }, 25 | { 26 | option: '-p, --portStart [num]', 27 | description: 'Start binding mongods contiguously from this port. 27017 by default.' 28 | }, 29 | { 30 | option: '-d, --dbpath [string]', 31 | description: 'Specify a path for mongod to use as a data directory. `./data` by default.' 32 | }, 33 | { 34 | option: '-h, --host [string]', 35 | description: 'Override the default ip binding and bind mongodb to listen to other ip addresses. Bind to localhost or 127.0.0.1 by default' 36 | }, 37 | { 38 | option: '-l, --linux [string]', 39 | description: 'Override the default system linux. Only for linux version. `ubuntu1604` by default' 40 | }, 41 | { 42 | option: '-p, --bind_ip_all', 43 | description: 'Allow connections from remote servers, not just from localhost.' 44 | }, 45 | { 46 | option: '--help', 47 | description: 'Output help' 48 | } 49 | ]); 50 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "run-rs", 3 | "version": "0.7.7", 4 | "description": "Run a MongoDB replica set locally for development and clear the database each time", 5 | "main": "index.js", 6 | "bin": { 7 | "run-rs": "./index.js" 8 | }, 9 | "scripts": { 10 | "lint": "eslint .", 11 | "test": "mocha test/*.test.js" 12 | }, 13 | "author": "Valeri Karpov ", 14 | "license": "Apache 2.0", 15 | "keywords": [ 16 | "mongodb", 17 | "replica", 18 | "replica set", 19 | "runner" 20 | ], 21 | "repository": { 22 | "type": "git", 23 | "url": "git://github.com/vkarpov15/run-rs.git" 24 | }, 25 | "dependencies": { 26 | "chalk": "2.4.1", 27 | "co": "4.6.0", 28 | "commander": "2.15.1", 29 | "moment": "^2.29.2", 30 | "mongodb": "3.6.x", 31 | "mongodb-topology-manager": "2.1.0", 32 | "prettyjson": "1.2.2" 33 | }, 34 | "devDependencies": { 35 | "eslint": "5.3.0", 36 | "mocha": "6.x", 37 | "sinon": "7.x" 38 | }, 39 | "eslintConfig": { 40 | "extends": [ 41 | "eslint:recommended" 42 | ], 43 | "parserOptions": { 44 | "ecmaVersion": 2015 45 | }, 46 | "env": { 47 | "node": true, 48 | "es6": true 49 | }, 50 | "rules": { 51 | "comma-style": "error", 52 | "consistent-this": [ 53 | "error", 54 | "_this" 55 | ], 56 | "indent": [ 57 | "error", 58 | 2, 59 | { 60 | "SwitchCase": 1, 61 | "VariableDeclarator": 2 62 | } 63 | ], 64 | "keyword-spacing": "error", 65 | "no-buffer-constructor": "warn", 66 | "no-console": "off", 67 | "no-multi-spaces": "error", 68 | "func-call-spacing": "error", 69 | "no-trailing-spaces": "error", 70 | "quotes": [ 71 | "error", 72 | "single" 73 | ], 74 | "semi": "error", 75 | "space-before-blocks": "error", 76 | "space-before-function-paren": [ 77 | "error", 78 | "never" 79 | ], 80 | "space-infix-ops": "error", 81 | "space-unary-ops": "error", 82 | "no-var": "warn", 83 | "prefer-const": "warn", 84 | "strict": [ 85 | "error", 86 | "global" 87 | ], 88 | "no-restricted-globals": [ 89 | "error", 90 | { 91 | "name": "context", 92 | "message": "Don't use Mocha's global context" 93 | } 94 | ] 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/download.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const childProcess = require('child_process'); 4 | const path = require('path'); 5 | 6 | module.exports = function download(version, systemLinux, os) { 7 | const execSync = childProcess.execSync; 8 | const versionMatch = version.match(/^(\d)\.(\d)\.(\d+)$/); 9 | if (!versionMatch) { 10 | throw new Error('Version must be in x.x.x format'); 11 | } 12 | const major = parseInt(versionMatch[1]); 13 | const minor = parseInt(versionMatch[2]); 14 | // const patch = parseInt(versionMatch[3]); 15 | 16 | os = os || process.platform; 17 | let dirname; 18 | let filename; 19 | let base = 'https://downloads.mongodb.org'; 20 | 21 | const mainScriptDir = path.resolve(__dirname, '..'); 22 | const isBefore42 = major < 4 || (major === 4 && minor < 2); 23 | 24 | switch (os) { 25 | case 'linux': 26 | if (isBefore42) { 27 | filename = `mongodb-linux-x86_64-${version}.tgz`; 28 | dirname = `mongodb-linux-x86_64-${version}`; 29 | } else { 30 | filename = `mongodb-linux-x86_64-${systemLinux}-${version}.tgz`; 31 | dirname = `mongodb-linux-x86_64-${systemLinux}-${version}`; 32 | } 33 | break; 34 | case 'darwin': 35 | os = 'osx'; 36 | if (isBefore42) { 37 | filename = `mongodb-osx-ssl-x86_64-${version}.tgz`; 38 | dirname = `mongodb-osx-x86_64-${version}`; 39 | } else { 40 | base = 'https://fastdl.mongodb.org'; 41 | filename = `mongodb-macos-x86_64-${version}.tgz`; 42 | dirname = `mongodb-macos-x86_64-${version}`; 43 | } 44 | break; 45 | case 'win32': 46 | if (major < 3) { 47 | filename = `mongodb-win32-x86_64-2008plus-${version}.zip`; 48 | dirname = `mongodb-win32-x86_64-2008plus-${version}`; 49 | } else if (major <= 4 && minor < 2) { 50 | filename = `mongodb-win32-x86_64-2008plus-ssl-${version}.zip`; 51 | dirname = `mongodb-win32-x86_64-2008plus-ssl-${version}`; 52 | } else if (major <= 4 && minor < 4) { 53 | filename = `mongodb-win32-x86_64-2012plus-${version}.zip`; 54 | dirname = `mongodb-win32-x86_64-2012plus-${version}`; 55 | } else { 56 | os = 'windows'; 57 | filename = `mongodb-windows-x86_64-${version}.zip`; 58 | dirname = `mongodb-win32-x86_64-windows-${version}`; 59 | } 60 | break; 61 | default: 62 | throw new Error(`Unrecognized os ${os}`); 63 | } 64 | 65 | const url = `${base}/${os}/${filename}`; 66 | 67 | if (os.startsWith('win')) { 68 | execSync('powershell.exe -nologo -noprofile -command "&{' + 69 | 'Add-Type -AssemblyName System.IO.Compression.FileSystem;' + 70 | `(New-Object Net.WebClient).DownloadFile('${url}', '${filename}');` + 71 | `[System.IO.Compression.ZipFile]::ExtractToDirectory('${filename}','.');` + 72 | `mv './${dirname}/bin' '${mainScriptDir}/${version}';` + 73 | `rd -r './${dirname}';` + 74 | `rm './${filename}';` + 75 | '}"' 76 | ); 77 | } else { 78 | execSync(`curl -OL ${url}`); 79 | execSync(`tar -zxvf ${filename}`); 80 | execSync(`mv ./${dirname}/bin ${mainScriptDir}/${version}`); 81 | execSync(`rm -rf ./${dirname}`); 82 | execSync(`rm ./${filename}`); 83 | } 84 | 85 | return { path: `${mainScriptDir}/${version}`, url: url }; 86 | }; 87 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 0.7.7 / 2022-07-20 2 | ================== 3 | * fix: upgrade moment dependency #68 [sanguineti](https://github.com/sanguineti) 4 | 5 | 0.7.6 / 2022-01-13 6 | ================== 7 | * fix: the new prettyjson 1.2.2 to fix colors #65 #64 [gracicot](https://github.com/gracicot) 8 | 9 | 0.7.5 / 2021-06-19 10 | ================== 11 | * fix: upgrade mongodb driver -> 3.6.x to fix deprecation warnings #59 12 | 13 | 0.7.4 / 2020-12-08 14 | ================== 15 | * fix: update compatibility with windows and mongodb 4.4.0+ #56 [Xaseron](https://github.com/Xaseron) 16 | 17 | 0.7.3 / 2020-11-27 18 | ================== 19 | * fix: use https to download mongodb #55 [Xaseron](https://github.com/Xaseron) 20 | * fix: fixed cannot read property undefined in accessing message property #48 [ucejtech](https://github.com/ucejtech) 21 | 22 | 0.7.2 / 2020-11-21 23 | ================== 24 | * fix: work around log message change for MongoDB 4.4 #53 25 | 26 | 0.7.1 / 2020-10-11 27 | ================== 28 | * fix: correctly return options when creating replica set #50 29 | 30 | 0.6.2 / 2019-10-12 31 | ================== 32 | * fix: correct OSX download URL for 4.2 33 | 34 | 0.6.1 / 2019-09-27 35 | ================== 36 | * fix: fix OSX download URL for 3.2, 3.4, 3.6 37 | 38 | 0.6.0 / 2019-09-24 39 | ================== 40 | * feat: support MongoDB 4.2 on Linux #40 [gabrie-allaigre](https://github.com/gabrie-allaigre) 41 | * feat: add `-l, --linux` flag for specifying Linux distro, `ubuntu1604` by default #40 [gabrie-allaigre](https://github.com/gabrie-allaigre) 42 | 43 | 0.5.5 / 2019-09-14 44 | ================== 45 | * fix: use mongodb driver 3.3.x for MongoDB 4.2 support 46 | 47 | 0.5.4 / 2019-09-14 48 | ================== 49 | * fix: correct download path #38 #37 [ProtonGustave](https://github.com/ProtonGustave) 50 | 51 | 0.5.3 / 2019-09-11 52 | ================== 53 | * fix: make --help check more robust #32 [jordonbiondo](https://github.com/jordonbiondo) 54 | 55 | 0.5.2 / 2019-03-14 56 | ================== 57 | * fix: correct dbPath on windows #26 58 | 59 | 0.5.1 / 2019-03-14 60 | ================== 61 | * fix: support absolute paths as args to --dbpath #26 [fiorillo](https://github.com/fiorillo) 62 | 63 | 0.5.0 / 2019-03-13 64 | ================== 65 | * BREAKING CHANGE: use MongoDB 4.0.6 by default 66 | * fix: clean error message when address is already in use #21 67 | * fix: print readable error if --mongod not found #25 68 | * fix: use custom --help to avoid limitations in commanders help output #24 69 | * docs: from `--dbPath` to `--dbpath` #23 [isghe](https://github.com/isghe) 70 | 71 | 0.4.0 / 2018-11-26 72 | ================== 73 | * feat: add --host option to override default mongodb ip binding #18 #16 [chaiwa-berian](https://github.com/chaiwa-berian) 74 | 75 | 0.3.3 / 2018-11-22 76 | ================== 77 | * docs: notes on connection string to support Windows users #16 [chaiwa-berian](https://github.com/chaiwa-berian) 78 | 79 | 0.3.2 / 2018-11-19 80 | ================== 81 | * fix: correct dbpaths and hostname on Windows #15 #8 [chaiwa-berian](https://github.com/chaiwa-berian) 82 | 83 | 0.3.1 / 2018-11-17 84 | ================== 85 | * fix: correct default dbpath on Windows #14 #13 [chaiwa-berian](https://github.com/chaiwa-berian) 86 | 87 | 0.3.0 / 2018-11-04 88 | ================== 89 | * feat: add --dbPath option to specify a path for run-rs to use as a data director #12 [fruschitaly](https://github.com/fruschitaly) 90 | * feat: add the ability to specify the starting port #11 [lineus](https://github.com/lineus) 91 | 92 | 0.2.2 / 2018-10-04 93 | ================== 94 | * feat: add -n, --number option to specify number of mongods to start #9 95 | 96 | 0.2.1 / 2018-09-08 97 | ================== 98 | * fix: add --mongod option to support using a pre-installed version of mongodb #6 99 | 100 | 0.2.0 / 2018-09-03 101 | ================== 102 | * feat: add windows 10 support #5 #2 [Fonger](https://github.com/Fonger) 103 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # run-rs 2 | 3 | Zero-config MongoDB runner. Starts a replica set with no non-Node dependencies, not even MongoDB. 4 | 5 | 6 | 7 | ## Usage 8 | 9 | To install: 10 | 11 | ``` 12 | npm install run-rs -g 13 | ``` 14 | 15 | With run-rs, starting a 3 node [replica set](https://docs.mongodb.com/manual/tutorial/deploy-replica-set/) running MongoDB 3.6 is a one-liner. 16 | 17 | ``` 18 | run-rs 19 | ``` 20 | 21 | To use a different version, use the `-v` flag. For example, this will start a 3 node replica set using MongoDB 4.0.0. 22 | 23 | ``` 24 | run-rs -v 4.0.0 25 | ``` 26 | 27 | On linux, for 4.2.0 version, by default download `ubuntu1604`, change with command 28 | 29 | ``` 30 | run-rs -l ubuntu1804 31 | ``` 32 | 33 | ## Clearing the Database 34 | 35 | Run-rs clears the database every time it starts by default. To override this behavior, use the `--keep` (`-k`) flag. 36 | 37 | ``` 38 | run-rs --keep 39 | ``` 40 | 41 | ## OS Support 42 | 43 | Run-rs supports Linux, OSX, and Windows 10 (via [git bash](https://git-scm.com/downloads) or powershell). 44 | 45 | ## Shell Option 46 | 47 | Use the `--shell` flag to start a MongoDB shell connected to your replica 48 | set once the replica set is running. 49 | 50 | ``` 51 | $ run-rs --shell 52 | Purging database... 53 | Running '/home/node/lib/node_modules/run-rs/3.6.5/mongod' 54 | Starting replica set... 55 | Started replica set on "mongodb://localhost:27017,localhost:27018,localhost:27019" 56 | Connecting shell /home/node/lib/node_modules/run-rs/3.6.5/mongo 57 | rs:PRIMARY> 58 | ``` 59 | 60 | ## Notes on Connecting 61 | 62 | Use `replicaSet=rs` in your connection string. 63 | 64 | **For Windows Users:** Do NOT use `localhost` or `127.0.0.1` for the host name in your connection string, use *computer name* instead. See example connection string below: 65 | 66 | ``` 67 | mongodb://sk-zm-los-bdb:27017,sk-zm-los-bdb:27018,sk-zm-los-bdb:27019/dbname?replicaSet=rs 68 | ``` 69 | *where* `sk-zm-los-bdb` is the *hostname* or the *name of your computer*, `dbname` is the name of your *database*, and *rs* is the name of your replica set. 70 | 71 | ## Reusing a Pre-installed MongoDB Version 72 | 73 | By default, run-rs will download whatever version of MongoDB you've specified. If you already have MongoDB installed, you can use the `--mongod` option: 74 | 75 | ``` 76 | run-rs --mongod 77 | ``` 78 | 79 | The above command will just run whatever `mongod` is on your PATH. If you want to run a specific `mongod` server, you can do this: 80 | 81 | ``` 82 | run-rs --mongod /home/user/path/to/mongod 83 | ``` 84 | 85 | ## Specify the data directory 86 | 87 | By default, run-rs will store data files in a directory named 'data'. To specify a dbPath for run-rs to use as a data directory, use the `--dbpath` option. 88 | 89 | ``` 90 | run-rs --dbpath /path/to/data/directory 91 | ``` 92 | 93 | ## IP Binding 94 | 95 | Use the `--host` option to ensure that `run-rs` allows MongoDB to listen for connections on configured IP addresses or hostnames other than `localhost` and `127.0.0.1`. See examples below: 96 | 97 | ``` 98 | run-rs --host 198.51.100.1 99 | ```` 100 | **OR** 101 | ``` 102 | run-rs --host example-associated-hostname 103 | ``` 104 | **Note:** *Before you bind to other ip addresses, consider [enabling access control](https://docs.mongodb.com/manual/administration/security-checklist/#checklist-auth) and other security measures listed in [Security Checklist](https://docs.mongodb.com/manual/administration/security-checklist/) to prevent unauthorized access.* 105 | 106 | ## Ports 107 | 108 | By default, run-rs will start MongoDB servers on ports 27017, 27018, and 27019. 109 | You can override this default using the `--portStart` option. 110 | For example, the below command will start MongoDB servers on ports 27000, 27001, and 27002. 111 | 112 | ``` 113 | run-rs --portStart 27000 114 | ``` 115 | 116 | ## Running in Production 117 | 118 | Do **not** use run-rs for running your production database. Run-rs is designed 119 | for local development and testing, and is not intended for production use. 120 | If you want to run MongoDB in production and don't want to manage a replica 121 | set yourself, use [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). 122 | -------------------------------------------------------------------------------- /src/topologyManagerPatch.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Server = require('mongodb-topology-manager').Server; 4 | const clone = require('mongodb-topology-manager/lib/utils').clone; 5 | const co = require('co'); 6 | const f = require('util').format; 7 | const spawn = require('child_process').spawn; 8 | const waitForAvailable = require('mongodb-topology-manager/lib/utils').waitForAvailable; 9 | 10 | Server.prototype.start = function() { 11 | var self = this; 12 | 13 | return new Promise(function(resolve, reject) { 14 | co(function*() { 15 | // Get the version numbers 16 | var result = yield self.discover(); 17 | var version = result.version; 18 | 19 | // All errors found during validation 20 | var errors = []; 21 | 22 | // Ensure basic parameters 23 | if (!self.options.dbpath) { 24 | errors.push(new Error('dbpath is required')); 25 | } 26 | 27 | // Do we have any errors 28 | if (errors.length > 0) return reject(errors); 29 | 30 | // Figure out what special options we need to pass into the boot script 31 | // Removing any non-compatible parameters etc. 32 | if (version[0] === 3 && version[1] >= 0 && version[1] <= 2) { 33 | // do nothing 34 | } else if (version[0] === 3 && version[1] >= 2) { 35 | // do nothing 36 | } else if (version[0] === 2 && version[1] <= 6) { 37 | // do nothing 38 | } 39 | 40 | // Merge in all the options 41 | var options = clone(self.options); 42 | 43 | // Build command options list 44 | var commandOptions = []; 45 | 46 | // Do we have a 2.2 server, then we don't support setParameter 47 | if (version[0] === 2 && version[1] === 2) { 48 | delete options['setParameter']; 49 | } 50 | 51 | // Go over all the options 52 | for (var name in options) { 53 | if (options[name] == null) { 54 | commandOptions.push(f('--%s', name)); 55 | } else if (Array.isArray(options[name])) { 56 | // We have an array of a specific option f.ex --setParameter 57 | for (var i = 0; i < options[name].length; i++) { 58 | var o = options[name][i]; 59 | 60 | if (o == null) { 61 | commandOptions.push(f('--%s', name)); 62 | } else { 63 | commandOptions.push(f('--%s=%s', name, options[name][i])); 64 | } 65 | } 66 | } else { 67 | commandOptions.push(f('--%s=%s', name, options[name])); 68 | } 69 | } 70 | 71 | // Command line 72 | var commandLine = f('%s %s', self.binary, commandOptions.join(' ')); 73 | // Emit start event 74 | self.emit('state', { 75 | event: 'start', 76 | topology: 'server', 77 | cmd: commandLine, 78 | options: self.options 79 | }); 80 | 81 | if (self.logger.isInfo()) { 82 | self.logger.info(f('started mongod with [%s]', commandLine)); 83 | } 84 | 85 | // Spawn a mongod process 86 | self.process = spawn(self.binary, commandOptions); 87 | 88 | // Variables receiving data 89 | var stdout = ''; 90 | var stderr = ''; 91 | 92 | // Get the stdout 93 | self.process.stdout.on('data', function(data) { 94 | stdout += data.toString(); 95 | self.emit('state', { 96 | event: 'stdout', 97 | topology: 'server', 98 | stdout: data.toString(), 99 | options: self.options 100 | }); 101 | 102 | // 103 | // Only emit event at start 104 | if (self.state === 'stopped') { 105 | // Hack for MongoDB 4.4 re: gh-53 106 | if ( 107 | stdout.indexOf('aiting for connections') !== -1 || 108 | stdout.indexOf('connection accepted') !== -1 109 | ) { 110 | waitForAvailable(self.options.bind_ip, self.options.port, err => { 111 | if (err) return reject(err); 112 | 113 | // Mark state as running 114 | self.state = 'running'; 115 | 116 | // Emit start event 117 | self.emit('state', { 118 | event: 'running', 119 | topology: 'server', 120 | cmd: commandLine, 121 | options: self.options 122 | }); 123 | 124 | // Resolve 125 | resolve(); 126 | }); 127 | } 128 | } 129 | }); 130 | 131 | // Get the stderr 132 | self.process.stderr.on('data', function(data) { 133 | stderr += data; 134 | }); 135 | 136 | // Got an error 137 | self.process.on('error', function(err) { 138 | self.emit('state', { 139 | event: 'sterr', 140 | topology: 'server', 141 | stdout: stdout, 142 | stedrr: stderr.toString(), 143 | options: self.options 144 | }); 145 | reject(new Error({ error: err, stdout: stdout, stderr: stderr })); 146 | }); 147 | 148 | // Process terminated 149 | self.process.on('close', function(code) { 150 | if ((self.state === 'stopped' && stdout === '') || code !== 0) { 151 | return reject( 152 | new Error(f('failed to start mongod with options %s\n%s', commandOptions, stdout)) 153 | ); 154 | } 155 | 156 | self.state = 'stopped'; 157 | }); 158 | }).catch(reject); 159 | }); 160 | }; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const ReplSet = require('mongodb-topology-manager').ReplSet; 6 | const chalk = require('chalk'); 7 | const co = require('co'); 8 | const commander = require('commander'); 9 | const download = require('./src/download'); 10 | const execSync = require('child_process').execSync; 11 | const fs = require('fs'); 12 | const moment = require('moment'); 13 | const mongodb = require('mongodb'); 14 | const options = require('./src/options'); 15 | const prettyjson = require('prettyjson'); 16 | const printHelp = require('./src/printHelp'); 17 | const spawn = require('child_process').spawn; 18 | const os = require('os'); 19 | 20 | require('./src/topologyManagerPatch'); 21 | 22 | const ports = []; 23 | const isWin = process.platform === 'win32'; 24 | let hostname = ''; 25 | 26 | for (const o of options) { 27 | commander.option(o.option, o.description); 28 | } 29 | 30 | commander.parse(process.argv); 31 | 32 | co(run).catch(error => console.error(chalk.red(error.stack))); 33 | 34 | function* run() { 35 | if (commander.rawArgs.indexOf('--help') > 0) { 36 | printHelp(); 37 | return; 38 | } 39 | 40 | const options = {}; 41 | const rcfile = isWin ? `${process.cwd()}\\.run-rs.rc` : `${process.cwd()}/.run-rs.rc`; 42 | if (fs.existsSync(rcfile)) { 43 | Object.assign(options, JSON.parse(fs.readFileSync(rcfile, 'utf8'))); 44 | } 45 | const version = typeof commander.version === 'string' ? 46 | commander.version : 47 | options.version || '4.0.12'; 48 | 49 | const n = parseInt(commander.number, 10) || 3; 50 | const startingPort = parseInt(commander.portStart, 10) || 27017; 51 | 52 | for (let i = 0; i < n; ++i) { 53 | ports.push(startingPort + i); 54 | } 55 | 56 | if (commander.host) { 57 | hostname = `${commander.host}`; 58 | } 59 | else { 60 | hostname = isWin ? os.hostname() : 'localhost'; 61 | } 62 | let mongod; 63 | let mongo; 64 | if (commander.mongod) { 65 | mongod = typeof commander.mongod === 'string' ? commander.mongod : 'mongod'; 66 | mongo = typeof commander.mongod === 'string' ? 67 | commander.mongod.replace(/mongod$/i, 'mongo') : 68 | 'mongo'; 69 | 70 | try { 71 | const where = isWin ? 'where' : 'command -v'; 72 | execSync(`${where} ${mongod}`); 73 | } catch (err) { 74 | throw new Error(`No mongod process found at ${mongod}, check your --mongod option`, err); 75 | } 76 | } else { 77 | mongod = isWin ? `${__dirname}\\${version}\\mongod.exe` : `${__dirname}/${version}/mongod`; 78 | mongo = isWin ? `${__dirname}\\${version}\\mongo.exe` : `${__dirname}/${version}/mongo`; 79 | 80 | if (!fs.existsSync(mongod)) { 81 | console.log(`Downloading MongoDB ${version}`); 82 | const path = download(version, commander.linux || 'ubuntu1604').path; 83 | console.log(`Copied MongoDB ${version} to '${path}'`); 84 | } 85 | } 86 | 87 | let dbPath; 88 | if (typeof commander.dbpath === 'string') { 89 | dbPath = `${commander.dbpath}` ; 90 | } 91 | else { 92 | dbPath = isWin ? `${process.cwd()}\\data` : `${process.cwd()}/data`; 93 | } 94 | 95 | if (!fs.existsSync(`${dbPath}`)) { 96 | execSync(isWin ? `md ${dbPath}` : `mkdir -p ${dbPath}`); 97 | } 98 | if (commander.keep) { 99 | console.log(chalk.blue('Skipping purge')); 100 | } else { 101 | console.log(chalk.blue('Purging database...')); 102 | execSync(isWin ? `del /S /Q ${dbPath}\\*` : `rm -rf ${dbPath}/*`); 103 | } 104 | 105 | ports.forEach((port) => { 106 | const portDBPath = isWin ? `${dbPath}\\${port}` : `${dbPath}/${port}`; 107 | if (!fs.existsSync(portDBPath)) { 108 | execSync(isWin ? `md ${dbPath}\\${port}` : `mkdir -p ${dbPath}/${port}`); 109 | } 110 | }); 111 | 112 | console.log(`Running '${mongod}'`, ports); 113 | const rs = new ReplSet(mongod, 114 | ports.map(port => { 115 | const options = { 116 | port: port, 117 | dbpath: isWin ? `${dbPath}\\${port}` : `${dbPath}/${port}`, 118 | bind_ip: hostname 119 | }; 120 | if (commander.bind_ip_all) { 121 | options.bind_ip_all = null; 122 | } 123 | return { options }; 124 | }), { replSet: 'rs' }); 125 | 126 | if (commander.keep) { 127 | console.log(chalk.blue('Restarting replica set...')); 128 | for (const manager of rs.managers) { 129 | yield manager.start(); 130 | } 131 | const result = yield rs.managers[0].executeCommand('admin.$cmd', { 132 | replSetGetStatus: 1 133 | }, null, { ignoreError: true }); 134 | 135 | if (result.set) { 136 | // There's already a replica set config, so don't initiate 137 | yield rs.waitForPrimary(); 138 | } else { 139 | // First time starting up, need to create a replica set config 140 | for (const manager of rs.managers) { 141 | yield manager.stop(); 142 | } 143 | yield startRS(rs); 144 | } 145 | } else { 146 | console.log(chalk.blue('Starting replica set...')); 147 | yield startRS(rs); 148 | } 149 | 150 | const hosts = ports.map(port => `${hostname}:${port}`); 151 | console.log(chalk.green(`Started replica set on "mongodb://${hosts.join(',')}?replicaSet=rs"`)); 152 | 153 | if (commander.shell) { 154 | console.log(chalk.blue(`Running mongo shell: ${mongo}`)); 155 | const shellDefaultHost = (hosts[0].split(':'))[0]; 156 | const shellDefaultPort = (hosts[0].split(':'))[1]; 157 | spawn(mongo, 158 | isWin ? ['--quiet','--port', shellDefaultPort, '--host', shellDefaultHost] : ['--quiet'], 159 | { stdio: 'inherit' } 160 | ); 161 | } else if (!commander.quiet) { 162 | const client = yield mongodb.MongoClient.connect(`mongodb://${hosts[0]}/test`, { 163 | useNewUrlParser: true, 164 | useUnifiedTopology: true 165 | }); 166 | 167 | const oplog = client.db('local').collection('oplog.rs').find({ ts: { $gte: new mongodb.Timestamp() } }, { 168 | tailable: true, 169 | awaitData: true, 170 | oplogReplay: true, 171 | noCursorTimeout: true, 172 | numberOfRetries: Number.MAX_VALUE 173 | }).stream(); 174 | 175 | console.log(chalk.green('Connected to oplog')); 176 | 177 | oplog.on('end', () => { 178 | console.log(moment().format('YYYY-MM-DD HH:mm:ss'), chalk.red('MongoDB oplog finished')); 179 | }); 180 | oplog.on('data', data => { 181 | if (['n'].includes(data.op)) { 182 | return; 183 | } 184 | if (data.ns.startsWith('admin.') || data.ns.startsWith('config.')) { 185 | return; 186 | } 187 | const ops = { 188 | c: 'createCollection', 189 | d: 'delete', 190 | i: 'insert', 191 | u: 'update' 192 | }; 193 | const op = ops[data.op] || data.op; 194 | 195 | let o = prettyjson.render(JSON.parse(JSON.stringify(data.o))); 196 | if ('o2' in data) { 197 | o = `${prettyjson.render(JSON.parse(JSON.stringify(data.o2)))} ${o}`; 198 | } 199 | console.log(chalk.blue(moment().format('YYYY-MM-DD HH:mm:ss')), data.ns, op); 200 | console.log(o); 201 | }); 202 | oplog.on('error', err => { 203 | console.log(chalk.red(moment().format('YYYY-MM-DD HH:mm:ss')), chalk.red(`Oplog error: ${err.stack}`)); 204 | }); 205 | } 206 | } 207 | 208 | function startRS(rs) { 209 | return co(function*() { 210 | try { 211 | yield rs.start(); 212 | } catch (err) { 213 | if (Array.isArray(err)) { 214 | err = err[0]; 215 | } 216 | if (err.message.includes('SocketException: Address already in use')) { 217 | const match = err.message.match(/port: (\d+)/); 218 | if (match != null) { 219 | throw new Error(`Could not start mongod on port ${match[1]} because it is already in use`); 220 | } 221 | } 222 | throw err; 223 | } 224 | }); 225 | } 226 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------