This repository has been archived by the owner on Dec 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
server.js
581 lines (494 loc) · 16.4 KB
/
server.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
'use strict';
const Promise = require('bluebird'),
co = require('co'),
f = require('util').format,
mkdirp = require('mkdirp'),
rimraf = require('rimraf'),
Logger = require('./logger'),
EventEmitter = require('events').EventEmitter,
CoreServer = require('mongodb-core').Server,
spawn = require('child_process').spawn,
clone = require('./utils').clone,
waitForAvailable = require('./utils').waitForAvailable,
createCommandOptions = require('./utils').createCommandOptions;
class Server extends EventEmitter {
constructor(binary, options, clientOptions) {
super();
options = options || {};
this.options = clone(options);
// Server state
this.state = 'stopped';
// Create logger instance
this.logger = Logger('Server', options);
// Unpack default runtime information
this.binary = binary || 'mongod';
// Current process
this.process = null;
// Current command
this.command = null;
// Credentials store
this.credentials = [];
// Additional internal client options
this.clientOptions = clientOptions || {};
// Default values for host and port if not set
this.options.bind_ip =
typeof this.options.bind_ip === 'string' ? this.options.bind_ip : 'localhost';
this.options.port = typeof this.options.port === 'number' ? this.options.port : 27017;
}
get config() {
return clone(this.options);
}
get host() {
return this.options.bind_ip;
}
get port() {
return this.options.port;
}
get name() {
return f('%s:%s', this.options.bind_ip, this.options.port);
}
discover() {
var self = this;
return new Promise(function(resolve, reject) {
var proc = spawn(self.binary, ['--version']);
// Do we have a valid proc
if (!proc || !proc.stdout || !proc.stderr) {
return reject(new Error(f('failed to start [%s --version]', self.binary)));
}
// Variables receiving data
var stdout = '';
var stderr = '';
// Get the stdout
proc.stdout.on('data', function(data) {
stdout += data;
});
// Get the stderr
proc.stderr.on('data', function(data) {
stderr += data;
});
// Got an error
proc.on('error', function(err) {
reject(err);
});
// Process terminated
proc.on('close', function() {
// Perform version match
var versionMatch = stdout.match(/[0-9]+\.[0-9]+\.[0-9]+/);
// Check if we have ssl
var sslMatch = stdout.match(/ssl/i) || stderr.match(/ssl/i);
// Resolve the server version
resolve({
version: versionMatch
.toString()
.split('.')
.map(function(x) {
return parseInt(x, 10);
}),
ssl: sslMatch != null
});
});
});
}
/**
* Obtain a client instance connected to the server using the given credentials
*
* The client instance must be destroyed after use by calling the destroy function.
*
* @param {object} [credentials] The credentials for authentication to server
* @param {string} [credentials.provider] Authentication mechanism to use (ex: mongocr, plain)
* @param {string} [credentials.db] Database to perform authentication against
* @param {string} [credentials.username] Username
* @param {string} [credentials.password] Password
* @param {object} [options] All options will be passed and handled to mongodb-core:ServerCore
*/
instance(credentials, options) {
var self = this;
options = options || {};
return new Promise(function(resolve, reject) {
// Create options for command from client options
var opt = createCommandOptions(self, options);
// Create an instance
var s = new CoreServer(opt);
s.on('error', function(err) {
reject(err);
});
s.on('close', function(err) {
reject(err);
});
s.on('timeout', function(err) {
reject(err);
});
s.on('connect', function(_server) {
// Do we have credentials
var authenticate = function(_server, _credentials, _callback) {
if (!_credentials) return _callback();
// Perform authentication using provided
// credentials for this command
_server.auth(
_credentials.provider,
_credentials.db,
_credentials.user,
_credentials.password,
_callback
);
};
// Perform any necessary authentication
authenticate(_server, credentials, function(err) {
if (err) return reject(err);
resolve(_server);
});
});
// Connect
s.connect();
});
}
/**
* Execute a command
*
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
* @param {object} command The command hash
* @param {object} [credentials] The credentials for authentication to server
* @param {string} [credentials.provider] Authentication mechanism to use (ex: mongocr, plain)
* @param {string} [credentials.db] Database to perform authentication against
* @param {string} [credentials.username] Username
* @param {string} [credentials.password] Password
* @param {object} [options] All options will be passed and handled to mongodb-core:ServerCore besides the one mentioned here
* @param {boolean} [options.ignoreError=false] Whether to ignore if an error occurs executing command
* @param {boolean} [options.reExecuteOnError=false] Whether to reexecute command if error occurs, will be ignored if options.ignoreError is true
*/
executeCommand(ns, command, credentials, options) {
var self = this;
options = options || {};
options = clone(options);
return new Promise(function(resolve, reject) {
// Create options for command from client options
var opt = createCommandOptions(self, options);
// Execute command
var executeCommand = function(_ns, _command, _credentials, _server) {
// Do we have credentials
var authenticate = function(_server, _credentials, _callback) {
if (!_credentials) return _callback();
// Perform authentication using provided
// credentials for this command
_server.auth(
_credentials.provider,
_credentials.db,
_credentials.user,
_credentials.password,
_callback
);
};
authenticate(_server, _credentials, function(err) {
if (err && options.ignoreError) return resolve({ ok: 1 });
// If we had an error return
if (err) {
_server.destroy();
return reject(err);
}
// Execute command
_server.command(_ns, _command, function(err, r) {
// Destroy the connection
_server.destroy();
// Return an error
if (err && options.ignoreError) return resolve({ ok: 1 });
if (err) return reject(err);
// Return the ismaster command
resolve(r.result);
});
});
};
// Create an instance
var s = new CoreServer(opt);
s.on('error', function(err) {
if (options.ignoreError) return resolve({ ok: 1 });
if (options.reExecuteOnError) {
options.reExecuteOnError = false;
return executeCommand(ns, command, credentials, s);
}
reject(err);
});
s.on('close', function(err) {
if (options.ignoreError) return resolve({ ok: 1 });
if (options.reExecuteOnError) {
options.reExecuteOnError = false;
return executeCommand(ns, command, credentials, s);
}
reject(err);
});
s.on('timeout', function(err) {
if (options.ignoreError) return resolve({ ok: 1 });
reject(err);
});
s.on('connect', function(_server) {
executeCommand(ns, command, credentials, _server);
});
// Connect
s.connect();
});
}
start() {
var self = this;
return new Promise(function(resolve, reject) {
co(function*() {
// Get the version numbers
var result = yield self.discover();
var version = result.version;
// All errors found during validation
var errors = [];
// Ensure basic parameters
if (!self.options.dbpath) {
errors.push(new Error('dbpath is required'));
}
// Do we have any errors
if (errors.length > 0) return reject(errors);
// Figure out what special options we need to pass into the boot script
// Removing any non-compatible parameters etc.
if (version[0] === 3 && version[1] >= 0 && version[1] <= 2) {
// do nothing
} else if (version[0] === 3 && version[1] >= 2) {
// do nothing
} else if (version[0] === 2 && version[1] <= 6) {
// do nothing
}
// Merge in all the options
var options = clone(self.options);
// Build command options list
var commandOptions = [];
// Do we have a 2.2 server, then we don't support setParameter
if (version[0] === 2 && version[1] === 2) {
delete options['setParameter'];
}
// Go over all the options
for (var name in options) {
if (options[name] == null) {
commandOptions.push(f('--%s', name));
} else if (Array.isArray(options[name])) {
// We have an array of a specific option f.ex --setParameter
for (var i = 0; i < options[name].length; i++) {
var o = options[name][i];
if (o == null) {
commandOptions.push(f('--%s', name));
} else {
commandOptions.push(f('--%s=%s', name, options[name][i]));
}
}
} else {
commandOptions.push(f('--%s=%s', name, options[name]));
}
}
// Command line
var commandLine = f('%s %s', self.binary, commandOptions.join(' '));
if (self.logger.isInfo()) {
self.logger.info(f('started mongod with [%s]', commandLine));
}
// Emit start event
self.emit('state', {
event: 'start',
topology: 'server',
cmd: commandLine,
options: self.options
});
// Spawn a mongod process
self.process = spawn(self.binary, commandOptions);
// Variables receiving data
var stdout = '';
var stderr = '';
// Get the stdout
self.process.stdout.on('data', function(data) {
stdout += data.toString();
self.emit('state', {
event: 'stdout',
topology: 'server',
stdout: data.toString(),
options: self.options
});
});
// Get the stderr
self.process.stderr.on('data', function(data) {
stderr += data;
});
// Got an error
self.process.on('error', function(err) {
self.emit('state', {
event: 'sterr',
topology: 'server',
stdout: stdout,
stedrr: stderr.toString(),
options: self.options
});
self.logger.error(
f('failed to start mongod instance [%s]\n%j\n%s', commandLine, err, stdout)
);
reject(new Error({ error: err, stdout: stdout, stderr: stderr }));
});
// Process terminated
self.process.on('close', function(code) {
if ((self.state === 'stopped' && stdout === '') || code !== 0) {
self.logger.error(
f('failed to start mongod instance [%s]\n%s', commandOptions, stdout)
);
return reject(
new Error(f('failed to start mongod with options %s\n%s', commandOptions, stdout))
);
}
self.state = 'stopped';
});
// Periodically attempt to connect to server and return if successful
// Error will be thrown if unable to connect after certain number of retries
yield waitForAvailable(self.options.bind_ip, self.options.port);
if (self.logger.isInfo()) {
self.logger.info(f('successfully started mongod instance [%s]', commandLine));
}
// Mark state as running
self.state = 'running';
// Emit start event
self.emit('state', {
event: 'running',
topology: 'server',
cmd: commandLine,
options: self.options
});
resolve();
}).catch(reject);
});
}
/**
* Retrieve document that describes the role of the mongod instance
*
* Equivalent to running db.isMaster() in mongo shell
*
* @see {@link https://docs.mongodb.com/manual/reference/command/isMaster/}
*
* @param {object} [options] All options will be passed and handled to mongodb-core:ServerCore
*/
ismaster(options) {
var self = this;
options = options || {};
return new Promise(function(resolve, reject) {
// Create options for command from client options
var opt = createCommandOptions(self, options);
// Create an instance
var s = new CoreServer(opt);
// Add listeners
s.on('error', function(err) {
reject(err);
});
s.on('close', function(err) {
reject(err);
});
s.on('timeout', function(err) {
reject(err);
});
s.on('connect', function(_server) {
_server.command(
'system.$cmd',
{
ismaster: true
},
function(err, r) {
// Destroy the connection
_server.destroy();
// Return an error
if (err) return reject(err);
// Return the ismaster command
resolve(r.result);
}
);
});
// Connect
s.connect();
});
}
/*
* Purge the db directory
*/
purge() {
var self = this;
return new Promise(function(resolve) {
try {
// Delete the dbpath
rimraf.sync(self.options.dbpath);
} catch (err) {
// do nothing
}
try {
// Re-Create the directory
mkdirp.sync(self.options.dbpath);
} catch (err) {
// do nothing
}
// Return
resolve();
});
}
stop(signal) {
var self = this;
signal = typeof signal === 'number' ? signals[signal] : signals['15'];
return new Promise(function(resolve, reject) {
// No process, just resolve
if (!self.process || self.state === 'stopped') {
// Set process to stopped
self.state = 'stopped';
// Return
return resolve();
}
// Wait for service to stop
// Remove error and close listeners because they are still attached from when the process was started
self.process.removeAllListeners('error');
self.process.removeAllListeners('close');
self.process.once('error', reject);
self.process.on('close', function() {
// Set process to stopped
self.state = 'stopped';
// Return
resolve();
});
// Terminate the process
self.process.kill(signal);
});
}
restart(purge) {
var self = this;
return new Promise(function(resolve, reject) {
co(function*() {
// Attempt to stop the server
yield self.stop();
// Do we wish to purge the directory ?
if (purge) yield self.purge();
// Start process
yield self.start();
resolve();
}).catch(reject);
});
}
}
module.exports = Server;
// SIGHUP 1 Term Hangup detected on controlling terminal
// or death of controlling process
// SIGINT 2 Term Interrupt from keyboard
// SIGQUIT 3 Core Quit from keyboard
// SIGILL 4 Core Illegal Instruction
// SIGABRT 6 Core Abort signal from abort(3)
// SIGFPE 8 Core Floating point exception
// SIGKILL 9 Term Kill signal
// SIGSEGV 11 Core Invalid memory reference
// SIGPIPE 13 Term Broken pipe: write to pipe with no readers
// SIGALRM 14 Term Timer signal from alarm(2)
// SIGTERM 15 Term Termination signal
// Signal map
var signals = {
1: 'SIGHUP',
2: 'SIGINT',
3: 'SIGQUIT',
4: 'SIGABRT',
6: 'SIGABRT',
8: 'SIGFPE',
9: 'SIGKILL',
11: 'SIGSEGV',
13: 'SIGPIPE',
14: 'SIGALRM',
15: 'SIGTERM',
17: 'SIGSTOP',
19: 'SIGSTOP',
23: 'SIGSTOP'
};