Files
NodeBB/loader.js

242 lines
5.9 KiB
JavaScript
Raw Normal View History

2014-12-02 17:40:48 -05:00
'use strict';
2021-02-04 00:06:15 -07:00
const nconf = require('nconf');
const fs = require('fs');
const url = require('url');
const path = require('path');
2021-02-06 14:10:15 -07:00
const { fork } = require('child_process');
2021-02-04 00:06:15 -07:00
const logrotate = require('logrotate-stream');
const { mkdirp } = require('mkdirp');
2017-04-12 15:22:58 -06:00
2021-02-04 00:06:15 -07:00
const file = require('./src/file');
const pkg = require('./package.json');
2021-02-04 00:06:15 -07:00
const pathToConfig = path.resolve(__dirname, process.env.CONFIG || 'config.json');
nconf.argv().env().file({
file: pathToConfig,
});
2021-02-04 00:06:15 -07:00
const pidFilePath = path.join(__dirname, 'pidfile');
2021-02-04 00:06:15 -07:00
const outputLogFilePath = path.join(__dirname, nconf.get('logFile') || 'logs/output.log');
2021-02-04 00:06:15 -07:00
const logDir = path.dirname(outputLogFilePath);
if (!fs.existsSync(logDir)) {
mkdirp.sync(path.dirname(outputLogFilePath));
}
2024-12-24 10:21:35 -05:00
const output = logrotate({ file: outputLogFilePath, size: '10m', keep: 3, compress: true });
2021-02-04 00:06:15 -07:00
const silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false;
let numProcs;
const workers = [];
const Loader = {};
2021-02-04 00:06:15 -07:00
const appPath = path.join(__dirname, 'app.js');
2021-10-18 17:31:14 -04:00
Loader.init = function () {
2014-09-30 21:48:39 -04:00
if (silent) {
console.log = (...args) => {
2021-02-03 23:59:08 -07:00
output.write(`${args.join(' ')}\n`);
2014-09-30 21:48:39 -04:00
};
}
process.on('SIGHUP', Loader.restart);
2014-11-17 14:47:36 -05:00
process.on('SIGTERM', Loader.stop);
};
2021-10-18 17:31:14 -04:00
Loader.displayStartupMessages = function () {
2014-10-22 13:47:05 -04:00
console.log('');
2021-11-15 18:27:22 -05:00
console.log(`NodeBB v${pkg.version} Copyright (C) 2013-${(new Date()).getFullYear()} 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('');
};
Loader.addWorkerEvents = function (worker) {
2021-02-04 00:01:39 -07:00
worker.on('exit', (code, signal) => {
2021-02-03 23:59:08 -07: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
2021-02-04 00:01:39 -07:00
worker.on('message', (message) => {
if (message && typeof message === 'object' && message.action) {
switch (message.action) {
2020-06-03 11:46:44 -04:00
case 'restart':
console.log('[cluster] Restarting...');
Loader.restart();
break;
case 'pubsub':
2021-02-04 00:01:39 -07:00
workers.forEach((w) => {
w.send(message);
2020-06-03 11:46:44 -04:00
});
break;
case 'socket.io':
2021-02-04 00:01:39 -07:00
workers.forEach((w) => {
2020-06-03 11:46:44 -04:00
if (w !== worker) {
w.send(message);
}
});
break;
}
}
});
};
2014-09-03 15:23:40 -04:00
2021-10-18 17:31:14 -04:00
Loader.start = function () {
numProcs = getPorts().length;
2021-02-03 23:59:08 -07:00
console.log(`Clustering enabled: Spinning up ${numProcs} process(es).\n`);
2021-02-04 00:06:15 -07:00
for (let x = 0; x < numProcs; x += 1) {
forkWorker(x, x === 0);
}
2014-10-08 12:07:33 -04:00
};
2014-09-03 15:23:40 -04:00
function forkWorker(index, isPrimary) {
2021-02-04 00:06:15 -07:00
const ports = getPorts();
const args = [];
const execArgv = [];
if (nconf.get('max-memory')) {
execArgv.push(`--max-old-space-size=${nconf.get('max-memory')}`);
}
if (nconf.get('expose-gc')) {
execArgv.push('--expose-gc');
}
2025-07-30 09:37:36 -04:00
if (nconf.get('expose-gc')) {
args.push('--expose-gc');
}
if (!ports[index]) {
2021-02-03 23:59:08 -07:00
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;
2018-05-15 11:05:23 -04:00
process.env.isCluster = nconf.get('isCluster') || ports.length > 1;
2014-12-03 17:10:25 -05:00
process.env.port = ports[index];
2021-02-04 00:06:15 -07:00
const worker = fork(appPath, args, {
silent: silent,
2017-02-17 19:31:21 -07:00
env: process.env,
execArgv: execArgv,
});
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) {
2021-02-04 00:06:15 -07:00
const 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() {
2021-02-04 00:06:15 -07:00
const _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();
}
2021-02-04 00:06:15 -07:00
const urlObject = url.parse(_url);
let 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 });
2021-02-04 00:01:39 -07:00
fs.readFile(pathToConfig, { encoding: 'utf-8' }, (err, configFile) => {
if (err) {
console.error('Error reading config');
throw err;
}
2021-02-04 00:06:15 -07:00
const 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.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() {
2021-02-04 00:01:39 -07:00
workers.forEach((worker) => {
worker.suicide = true;
worker.kill();
2014-12-02 16:49:49 -05:00
});
}
2021-02-04 00:01:39 -07:00
fs.open(pathToConfig, 'r', (err) => {
if (err) {
// No config detected, kickstart web installer
fork('app');
return;
}
if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) {
if (file.existsSync(pidFilePath)) {
let pid = 0;
try {
pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' });
if (pid) {
process.kill(pid, 0);
console.info(`Process "${pid}" from pidfile already running, exiting`);
process.exit();
} else {
console.info(`Invalid pid "${pid}" from pidfile, deleting pidfile`);
fs.unlinkSync(pidFilePath);
}
} catch (err) {
if (err.code === 'ESRCH') {
console.info(`Process "${pid}" from pidfile not found, deleting pidfile`);
fs.unlinkSync(pidFilePath);
} else {
console.error(err.stack);
throw err;
}
}
}
require('daemon')({
stdout: process.stdout,
stderr: process.stderr,
cwd: process.cwd(),
});
fs.writeFileSync(pidFilePath, String(process.pid));
}
2021-10-18 17:31:14 -04:00
try {
Loader.init();
Loader.displayStartupMessages();
Loader.start();
} catch (err) {
console.error('[loader] Error during startup');
throw err;
}
});