Files
NodeBB/loader.js

253 lines
5.9 KiB
JavaScript
Raw Normal View History

2014-12-02 17:40:48 -05:00
'use strict';
2017-02-17 20:20:42 -07:00
var nconf = require('nconf');
var fs = require('fs');
var url = require('url');
var path = require('path');
var fork = require('child_process').fork;
var async = require('async');
var logrotate = require('logrotate-stream');
2017-04-12 15:22:58 -06:00
2017-02-17 20:20:42 -07:00
var file = require('./src/file');
var pkg = require('./package.json');
var pathToConfig = path.resolve(__dirname, process.env.CONFIG || 'config.json');
nconf.argv().env().file({
file: pathToConfig,
});
2017-02-18 12:47:58 -07:00
var pidFilePath = path.join(__dirname, 'pidfile');
var outputLogFilePath = path.join(__dirname, 'logs/output.log');
var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
2017-02-17 20:20:42 -07:00
var silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false;
var numProcs;
var workers = [];
var Loader = {
timesStarted: 0,
};
2017-04-12 15:22:58 -06:00
var appPath = path.join(__dirname, 'app.js');
Loader.init = function (callback) {
2014-09-30 21:48:39 -04:00
if (silent) {
console.log = function () {
2016-03-31 12:26:51 -04:00
var args = Array.prototype.slice.call(arguments);
output.write(args.join(' ') + '\n');
2014-09-30 21:48:39 -04:00
};
}
process.on('SIGHUP', Loader.restart);
process.on('SIGUSR2', Loader.reload);
2014-11-17 14:47:36 -05:00
process.on('SIGTERM', Loader.stop);
callback();
};
Loader.displayStartupMessages = function (callback) {
2014-10-22 13:47:05 -04:00
console.log('');
console.log('NodeBB v' + pkg.version + ' Copyright (C) 2013-2014 NodeBB Inc.');
console.log('This program comes with ABSOLUTELY NO WARRANTY.');
console.log('This is free software, and you are welcome to redistribute it under certain conditions.');
console.log('For the full license, please visit: http://www.gnu.org/copyleft/gpl.html');
console.log('');
callback();
};
Loader.addWorkerEvents = function (worker) {
worker.on('exit', function (code, signal) {
2014-09-03 15:23:40 -04:00
if (code !== 0) {
2016-10-13 11:42:29 +02:00
if (Loader.timesStarted < numProcs * 3) {
Loader.timesStarted += 1;
2014-09-04 00:01:08 -04:00
if (Loader.crashTimer) {
clearTimeout(Loader.crashTimer);
}
Loader.crashTimer = setTimeout(function () {
2014-09-04 00:01:08 -04:00
Loader.timesStarted = 0;
2014-12-03 23:16:50 -05:00
}, 10000);
2014-09-03 15:23:40 -04:00
} else {
2017-02-18 01:51:11 -07:00
console.log((numProcs * 3) + ' restarts in 10 seconds, most likely an error on startup. Halting.');
2014-09-03 15:23:40 -04:00
process.exit();
}
}
2014-09-03 15:23:40 -04:00
2016-10-13 11:42:29 +02:00
console.log('[cluster] Child Process (' + worker.pid + ') has exited (code: ' + code + ', signal: ' + signal + ')');
if (!(worker.suicide || code === 0)) {
2014-12-03 14:17:05 -05:00
console.log('[cluster] Spinning up another process...');
forkWorker(worker.index, worker.isPrimary);
}
2014-05-04 16:46:09 -04:00
});
2014-09-04 00:56:50 -04:00
worker.on('message', function (message) {
if (message && typeof message === 'object' && message.action) {
switch (message.action) {
2017-02-18 02:38:03 -07:00
case 'restart':
console.log('[cluster] Restarting...');
Loader.restart();
break;
2017-02-18 02:38:03 -07:00
case 'reload':
console.log('[cluster] Reloading...');
Loader.reload();
break;
}
}
});
};
2014-09-03 15:23:40 -04:00
Loader.start = function (callback) {
numProcs = getPorts().length;
console.log('Clustering enabled: Spinning up ' + numProcs + ' process(es).\n');
for (var x = 0; x < numProcs; x += 1) {
forkWorker(x, x === 0);
}
if (callback) {
callback();
}
2014-10-08 12:07:33 -04:00
};
2014-09-03 15:23:40 -04:00
function forkWorker(index, isPrimary) {
var ports = getPorts();
2016-11-16 12:20:44 -05:00
var args = [];
if (!ports[index]) {
return console.log('[cluster] invalid port for worker : ' + index + ' ports: ' + ports.length);
}
2014-11-27 14:09:01 -05:00
2014-12-03 17:10:25 -05:00
process.env.isPrimary = isPrimary;
process.env.isCluster = ports.length > 1;
2014-12-03 17:10:25 -05:00
process.env.port = ports[index];
2017-04-12 15:22:58 -06:00
var worker = fork(appPath, args, {
silent: silent,
2017-02-17 19:31:21 -07:00
env: process.env,
});
2014-11-27 14:09:01 -05:00
worker.index = index;
worker.isPrimary = isPrimary;
2014-11-27 14:09:01 -05:00
workers[index] = worker;
Loader.addWorkerEvents(worker);
2014-11-26 17:24:49 -05:00
if (silent) {
2017-02-18 12:47:58 -07:00
var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
worker.stdout.pipe(output);
worker.stderr.pipe(output);
2014-11-26 17:24:49 -05:00
}
}
function getPorts() {
var _url = nconf.get('url');
if (!_url) {
2015-04-27 21:42:04 -04:00
console.log('[cluster] url is undefined, please check your config.json');
process.exit();
}
var urlObject = url.parse(_url);
2017-10-25 10:48:12 -04:00
var port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567;
if (!Array.isArray(port)) {
port = [port];
}
return port;
}
Loader.restart = function () {
2014-12-02 16:49:49 -05:00
killWorkers();
2016-08-16 20:11:03 +03:00
nconf.remove('file');
nconf.use('file', { file: pathToConfig });
2017-02-18 12:30:49 -07:00
fs.readFile(pathToConfig, { encoding: 'utf-8' }, function (err, configFile) {
if (err) {
console.error('Error reading config');
throw err;
}
var conf = JSON.parse(configFile);
nconf.stores.env.readOnly = false;
nconf.set('url', conf.url);
nconf.stores.env.readOnly = true;
2017-08-03 20:52:09 -04:00
if (process.env.url !== conf.url) {
process.env.url = conf.url;
}
Loader.start();
});
};
Loader.reload = function () {
workers.forEach(function (worker) {
worker.send({
2017-02-17 19:31:21 -07:00
action: 'reload',
});
});
2014-09-04 17:41:00 -04:00
};
2014-09-03 15:23:40 -04:00
Loader.stop = function () {
2014-12-02 16:49:49 -05:00
killWorkers();
2014-11-17 14:47:36 -05:00
// Clean up the pidfile
if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) {
fs.unlinkSync(pidFilePath);
}
2014-11-17 14:47:36 -05:00
};
2014-12-02 16:49:49 -05:00
function killWorkers() {
workers.forEach(function (worker) {
worker.suicide = true;
worker.kill();
2014-12-02 16:49:49 -05:00
});
}
Loader.notifyWorkers = function (msg, worker_pid) {
worker_pid = parseInt(worker_pid, 10);
workers.forEach(function (worker) {
if (parseInt(worker.pid, 10) !== worker_pid) {
try {
worker.send(msg);
} catch (e) {
console.log('[cluster/notifyWorkers] Failed to reach pid ' + worker_pid);
}
2014-12-02 17:40:48 -05:00
}
});
};
2014-09-16 11:17:57 -04:00
fs.open(pathToConfig, 'r', function (err) {
if (!err) {
if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) {
2015-09-29 18:22:41 -04:00
if (file.existsSync(pidFilePath)) {
try {
var pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' });
process.kill(pid, 0);
process.exit();
} catch (e) {
fs.unlinkSync(pidFilePath);
}
}
require('daemon')({
stdout: process.stdout,
2017-02-17 19:31:21 -07:00
stderr: process.stderr,
2017-07-20 15:43:11 -04:00
cwd: process.cwd(),
});
fs.writeFileSync(pidFilePath, process.pid);
}
async.series([
Loader.init,
Loader.displayStartupMessages,
2017-02-17 19:31:21 -07:00
Loader.start,
], function (err) {
if (err) {
console.error('[loader] Error during startup');
throw err;
}
});
} else {
// No config detected, kickstart web installer
fork('app');
}
});