-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.js
482 lines (446 loc) · 13.4 KB
/
cluster.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
var async = require('async');
var cp = require('child_process');
var mkdirp = require('mkdirp');
var mongodb = require('mongodb');
var optimist = require('optimist');
var path = require('path');
var MongoClient = require('mongodb').MongoClient;
var ServerType = {
MONGOS: 1,
MONGOCFG: 2,
MONGOD: 3
};
var ServerLabels = {
1: 'mongos',
2: 'mongocfg',
3: 'mongod'
}
//wraps a mongo instance. can be many types.
var MongoServer = function(options) {
this.type = options.type;
this.port = options.port;
this.replSetName = options.replSetName;
this.rootDataDir = options.dataDir;
this.rootLogDir = options.logDir;
this.configPorts = options.configPorts || [];
};
MongoServer.prototype.start = function(callback) {
var executable = 'mongod';
var commandArgs = [];
if (this.type === ServerType.MONGOS) {
executable = 'mongos';
} else if (this.type === ServerType.MONGOCFG) {
commandArgs.push('--configsvr');
} else if (this.type === ServerType.MONGOD) {
if (!!this.replSetName) {
commandArgs.push('--replSet');
commandArgs.push(this.replSetName);
}
}
if (this.type !== ServerType.MONGOS) {
commandArgs.push('--dbpath');
commandArgs.push(this.dataDir);
} else {
commandArgs.push('--configdb');
commandArgs.push(this.configPorts.map(function(port) {
return '127.0.0.1:' + port;
}).join(','));
}
commandArgs.push('--port');
commandArgs.push(this.port);
commandArgs.push('--logpath');
commandArgs.push(
path.resolve(
this.rootLogDir,
ServerLabels[this.type] + '_' + this.port + '.log'
)
);
console.log('start command: ' + executable + ' ' + commandArgs.join(' '));
this.process = cp.spawn(executable, commandArgs);
this.process.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
this.process.stderr.on('data', function(data) {
console.log('stderr: ' + data);
});
this.process.on('close', function(code) {
console.log('child process exited ' + code);
});
callback();
};
MongoServer.prototype.createDirectories = function(callback) {
var dataDirParts = [ServerLabels[this.type]];
dataDirParts.push(this.port);
if (!!this.replSetName) {
dataDirParts.push(this.replSetName);
}
this.dataDir = path.resolve(this.rootDataDir, dataDirParts.join('_'));
mkdirp(this.dataDir, function(err) {
return callback(err);
});
};
function checkRequirements() {
try {
// TODO: check if mongod is installed, etc
} catch (e) {
return false;
}
return true;
}
function processOptions(argv) {
var options = {
port: 26000,
sharded: false,
replicated: false,
dataDir: path.resolve('./data'),
logDir: path.resolve('./logs')
};
if (argv.port) {
options.port = argv.port;
}
if (argv.sharded) {
options.sharded = true;
options.shardCount = 1;
options.configServerCount = 1;
if (argv.shardCount) {
options.shardCount = parseInt(argv.shardCount, 10);
}
if (argv.configServerCount) {
options.configServerCount = parseInt(argv.configServerCount, 10);
}
}
if (argv.replicated) {
options.replicated = true;
options.replMemberCount = 3;
options.replSetName = 'test';
if (argv.replMemberCount) {
options.replMemberCount = parseInt(argv.replMemberCount, 10);
}
if (argv.replSetName) {
options.replSetName = argv.replSetName;
}
}
if (argv.dataDir) {
options.dataDir = path.resolve(argv.dataDir);
}
if (argv.logDir) {
options.logDir = path.resolve(argv.logDir);
}
return options;
}
function start(options) {
console.log('starting cluster configuration: ', options);
var servers = [];
var replicaSets = {};
var port = options.port;
var startPort = port;
var shardCount = options.shardCount || 1;
// start non-mongos on port+1
if (options.sharded) {
port++;
}
for (var s = 0; s < shardCount; s++) {
if (options.replicated) {
// only a replica set
for (var i = 0; i < options.replMemberCount; i++) {
var replSetName = options.replSetName + (options.sharded ? s : '');
servers.push(new MongoServer({
dataDir: options.dataDir,
logDir: options.logDir,
type: ServerType.MONGOD,
replSetName: replSetName,
port: port
}));
if (!replicaSets[replSetName]) {
replicaSets[replSetName] = {
members: []
}
}
replicaSets[replSetName].members.push(port);
port++;
}
} else {
// single mongod
servers.push(new MongoServer({
dataDir: options.dataDir,
logDir: options.logDir,
type: ServerType.MONGOD,
port: port++,
}));
}
}
var launchGroupOne, launchGroupTwo;
if (options.sharded) {
// add config servers
var configPorts = [];
for (var c = 0; c < options.configServerCount; c++) {
configPorts.push(port);
servers.splice(0, 0, new MongoServer({
dataDir: options.dataDir,
logDir: options.logDir,
type: ServerType.MONGOCFG,
port: port++
}));
}
servers.splice(0, 0, new MongoServer({
dataDir: options.dataDir,
logDir: options.logDir,
type: ServerType.MONGOS,
port: startPort,
configPorts: configPorts
}));
launchGroupOne = servers.slice(1);
launchGroupTwo = servers.slice(0, 1);
} else {
launchGroupOne = servers;
launchGroupTwo = [];
}
async.waterfall([
function createDirectories(cb) {
// TODO: ensure permissions
mkdirp(path.resolve(options.logDir), function(err) {
if (err) { return cb(err); }
mkdirp(path.resolve(options.dataDir), function(err) {
if (err) { return cb(err); }
async.forEach(servers, function(server, cb) {
server.createDirectories(cb);
}, cb);
});
});
},
function launchOne(cb) {
async.forEach(launchGroupOne, function(server, cb) {
server.start(cb);
}, cb);
},
function waitForServers1(cb) {
console.log('waiting for group one servers to start..');
async.forEach(launchGroupOne, function(server, cb) {
var connected = false;
async.whilst(function() {
return !connected;
}, function(cb) {
if (server.type === ServerType.MONGOCFG) {
connected = true;
return cb();
}
MongoClient.connect('mongodb://127.0.0.1:' + server.port + '/admin',
function(err, db) {
if (db) {
db.close();
}
if (!err) {
connected = true;
console.log(server.port + ' started!');
cb();
} else {
setTimeout(function() {
console.log('waiting..', err);
return cb();
}, 1000);
}
});
}, function(err) {
cb();
});
}, cb);
},
function launchTwo(cb) {
if (launchGroupTwo.length === 0) {
return cb();
}
async.forEach(launchGroupTwo, function(server, cb) {
server.start(cb);
}, cb);
},
function waitForServers2(cb) {
if (launchGroupTwo.length === 0) {
return cb();
}
async.forEach(launchGroupTwo, function(server, cb) {
var connected = false;
async.whilst(function() {
return !connected;
}, function(cb) {
if (server.type === ServerType.MONGOCFG) {
connected = true;
return cb();
}
MongoClient.connect('mongodb://127.0.0.1:' + server.port + '/admin',
function(err, db) {
if (db) {
db.close();
}
if (!err) {
connected = true;
console.log(server.port + ' started!');
cb();
} else {
setTimeout(function() {
console.log('waiting..');
return cb();
}, 1000);
}
});
}, function(err) {
cb();
});
}, cb);
},
function configureServers(cb) {
async.forEach(Object.keys(replicaSets), function(replSetName, cb) {
var memberPort = replicaSets[replSetName].members[0];
MongoClient.connect('mongodb://127.0.0.1:' + memberPort + '/test',
function(err, db) {
if (err) { return cb(err); }
var setId = 0;
db.executeDbAdminCommand({
replSetInitiate: {
_id: replSetName,
members: replicaSets[replSetName].members.map(function(memberPort) {
return {
_id: setId++,
host: '127.0.0.1:' + memberPort
};
})
}
}, function(err, result) {
console.log('repl set initiate',
result.documents[result.numberReturned-1]);
if (db) {
db.close();
}
cb(err);
});
});
}, cb);
},
function waitForReplServers(cb) {
if (!options.replicated) { return cb(); }
console.log('waiting for repl sets to come online..');
async.forEach(Object.keys(replicaSets), function(replSetName, cb) {
var replActive = false;
async.whilst(function() {
return !replActive;
}, function(cb) {
var mongoServer = mongodb.Server('127.0.0.1',
replicaSets[replSetName].members[0], {});
var mongoClient = new mongodb.Db('test',
mongoServer, {safe: true});
mongoClient.open(function(err, db) {
if (err || !db) {
setTimeout(function() {
return cb();
}, 1000);
return;
}
db.executeDbAdminCommand({
replSetGetStatus: 1
}, function(err, result) {
if (db) { db.close(); }
if (err) {
setTimeout(function() {
return cb();
}, 1000);
return;
}
var replStatus = result.documents[result.numberReturned-1];
var masterFound = false;
(replStatus.members || []).forEach(function(member) {
if (member.stateStr === 'PRIMARY') {
masterFound = true;
}
});
if (masterFound) {
replActive = true;
return cb();
} else {
setTimeout(function() {
return cb();
}, 1000);
}
});
});
}, function(err) {
cb();
});
}, cb);
},
function configureShards(cb) {
if (!options.sharded) { return cb(); }
var shards = [];
if (options.replicated) {
// add each repl set as a shard
Object.keys(replicaSets).forEach(function(replSetName) {
shards.push(replSetName +
'/127.0.0.1:' +
replicaSets[replSetName].members[0]);
});
} else {
// each mongod process is a shard
servers.forEach(function(server) {
if (server.type === ServerType.MONGOD) {
shards.push('127.0.0.1:' + server.port);
}
});
}
MongoClient.connect('mongodb://127.0.0.1:' + startPort + '/admin',
function(err, db) {
if (err) { return cb(err); }
var shardNum = 0;
async.eachSeries(shards, function(shard, cb) {
db.executeDbAdminCommand({
addShard: shard,
name: options.replicated ? undefined : shardNum++
}, function(err, result) {
console.log('addShard ran', result.documents[result.numberReturned-1]);
cb(err);
});
}, cb);
});
}
], function(err) {
if (!err) {
console.log('cluster online. mongo 127.0.0.1:' + startPort + ' to connect');
} else {
console.log('cluster startup error', err);
}
});
}
function main() {
if (!checkRequirements()) {
console.log('cannot continue, requirements not met.');
return;
}
optimist.usage('MongoDB Development Cluster')
.describe('help', 'show this message')
.boolean('help')
.describe('port', 'port to connect to mongod/replica set/mongos')
.describe('dataDir', 'Root Data Directory')
.describe('logDir', 'Root Log Directory')
.default('dataDir', path.resolve('./data'))
.default('logDir', path.resolve('./logs'))
.boolean('sharded')
.default('sharded', false)
.describe('sharded', 'Sharded Cluster (starts mongos on port)')
.describe('shardCount', 'Number of shards in cluster (if sharded)')
.default('shardCount', 1)
.describe('configServerCount', 'Number of config servers (if sharded)')
.default('configServerCount', 1)
.boolean('replicated')
.default('replicated', false)
.describe('replicated', 'Start standalone replica set (per shard if --sharded)')
.describe('replMemberCount', 'Number of mongod instance in replica set (Up to 7)')
.default('replMemberCount', 3)
.describe('replSetName', 'Replica set name or prefix for sharded replicated configuration')
.default('replSetName', 'test');
if (optimist.argv.help) {
optimist.showHelp();
return;
}
var options = processOptions(optimist.argv);
start(options);
}
if (!module.parent) {
main();
}