SIGN IN SIGN UP
Unitech / pm2 UNCLAIMED

Node.js Production Process Manager with a built-in Load Balancer.

43017 0 95 JavaScript
2016-03-22 23:33:43 +01:00
/**
2026-02-08 15:04:58 +01:00
* Copyright 2013-present the PM2 project authors. All rights reserved.
2016-03-22 23:33:43 +01:00
* Use of this source code is governed by a license that
* can be found in the LICENSE file.
*
* This file wrap target application
* - redirect stdin, stderr to bus + log files
* - rename process
* - pid
2016-03-22 23:33:43 +01:00
*/
var p = require('path');
var cst = require('../constants');
var Utility = require('./Utility.js');
2020-01-13 14:52:59 +01:00
var ProcessUtils = require('./ProcessUtils');
2023-01-16 14:04:04 +10:00
var Url = require('url');
// Load all env-vars from master.
var pm2_env = JSON.parse(process.env.pm2_env);
for(var k in pm2_env) {
process.env[k] = pm2_env[k];
}
2026-02-08 15:04:58 +01:00
if (pm2_env.disable_source_map_support !== true &&
typeof process.setSourceMapsEnabled === 'function')
process.setSourceMapsEnabled(true);
// Rename process
process.title = process.env.PROCESS_TITLE || 'node ' + pm2_env.pm_exec_path;
delete process.env.pm2_env;
2013-10-15 13:11:05 +02:00
/**
* Main entrance to wrap the desired code
*/
2013-05-24 12:54:32 +08:00
(function ProcessContainer() {
2013-10-15 13:11:05 +02:00
var fs = require('fs');
2015-08-05 19:15:25 +02:00
2020-01-13 14:52:59 +01:00
ProcessUtils.injectModules()
2013-10-28 11:45:32 +08:00
var stdFile = pm2_env.pm_log_path;
var outFile = pm2_env.pm_out_log_path;
var errFile = pm2_env.pm_err_log_path;
var pidFile = pm2_env.pm_pid_path;
var script = pm2_env.pm_exec_path;
2013-10-28 11:45:32 +08:00
var original_send = process.send;
process.send = function() {
if (process.connected)
original_send.apply(this, arguments);
};
//send node version
if (process.versions && process.versions.node) {
process.send({
'node_version': process.versions.node
});
}
2013-08-20 14:22:25 +02:00
if (cst.MODIFY_REQUIRE)
require.main.filename = pm2_env.pm_exec_path;
2013-10-28 11:45:32 +08:00
2015-04-15 18:16:15 +02:00
// Resets global paths for require()
require('module')._initPaths();
try {
2020-04-22 21:39:32 +02:00
var pid = process.pid
if (typeof(pid) !== 'undefined')
fs.writeFileSync(pidFile, process.pid.toString());
} catch (e) {
console.error(e.stack || e);
}
2013-10-28 11:45:32 +08:00
// Add args to process if args specified on start
if (process.env.args != null)
process.argv = process.argv.concat(pm2_env.args);
2013-07-01 11:42:21 +08:00
// stdio, including: out, err and entire (both out and err if necessary).
var stds = {
out: outFile,
err: errFile
};
stdFile && (stds.std = stdFile);
// uid/gid management
if (pm2_env.uid || pm2_env.gid) {
try {
if (process.env.gid)
process.setgid(pm2_env.gid);
if (pm2_env.uid)
process.setuid(pm2_env.uid);
} catch(e) {
setTimeout(function() {
console.error('%s on call %s', e.message, e.syscall);
console.error('%s is not accessible', pm2_env.uid);
return process.exit(1);
}, 100);
}
}
exec(script, stds);
2013-05-23 15:44:38 +08:00
})();
2013-05-23 15:25:50 +08:00
2014-06-13 16:11:43 +02:00
/**
* Description
* @method exec
* @param {} script
* @param {} stds
2014-07-09 17:27:09 +02:00
* @return
2014-06-13 16:11:43 +02:00
*/
function exec(script, stds) {
2017-10-07 10:04:57 -04:00
if (p.extname(script) == '.ts' || p.extname(script) == '.tsx') {
try {
require('ts-node/register');
} catch (e) {
console.error('Failed to load Typescript interpreter:', e.message || e);
}
}
process.on('message', function (msg) {
if (msg.type === 'log:reload') {
for (var k in stds){
if (typeof stds[k] == 'object' && !isNaN(stds[k].fd)){
if (stds[k].destroy) stds[k].destroy();
else if (stds[k].end) stds[k].end();
else if (stds[k].close) stds[k].close();
2014-12-12 17:17:32 +01:00
stds[k] = stds[k]._file;
}
}
Utility.startLogging(stds, function (err) {
if (err)
return console.error('Failed to reload logs:', err.stack);
console.log('Reloading log...');
});
}
});
2020-04-13 12:21:41 +02:00
var dayjs = null;
if (pm2_env.log_date_format)
2020-04-13 12:21:41 +02:00
dayjs = require('dayjs');
Utility.startLogging(stds, function (err) {
if (err) {
process.send({
type : 'process:exception',
data : {
message: err.message,
syscall: 'ProcessContainer.startLogging'
}
});
2015-08-13 19:28:45 +02:00
throw err;
return;
}
process.stderr.write = (function(write) {
2016-03-11 14:58:50 +01:00
return function(string, encoding, cb) {
var log_data = null;
2017-02-02 15:41:01 +01:00
// Disable logs if specified
if (pm2_env.disable_logs === true) {
2017-07-20 14:24:06 +02:00
return cb ? cb() : false;
}
if (pm2_env.log_type && pm2_env.log_type === 'json') {
log_data = JSON.stringify({
message : string.toString(),
2020-04-13 12:21:41 +02:00
timestamp : pm2_env.log_date_format && dayjs ?
dayjs().format(pm2_env.log_date_format) : new Date().toISOString(),
type : 'err',
process_id : pm2_env.pm_id,
app_name : pm2_env.name
}) + '\n';
}
2020-04-13 12:21:41 +02:00
else if (pm2_env.log_date_format && dayjs)
log_data = `${dayjs().format(pm2_env.log_date_format)}: ${string.toString()}`;
else
log_data = string.toString();
2017-02-02 15:41:01 +01:00
process.send({
type : 'log:err',
topic : 'log:err',
2017-02-02 15:41:01 +01:00
data : log_data
});
if (Utility.checkPathIsNull(pm2_env.pm_err_log_path) &&
(!pm2_env.pm_log_path || Utility.checkPathIsNull(pm2_env.pm_log_path)))
return cb ? cb() : false;
stds.std && stds.std.write && stds.std.write(log_data, encoding);
stds.err && stds.err.write && stds.err.write(log_data, encoding, cb);
};
})(process.stderr.write);
process.stdout.write = (function(write) {
2016-03-11 14:58:50 +01:00
return function(string, encoding, cb) {
var log_data = null;
2017-02-02 15:41:01 +01:00
// Disable logs if specified
if (pm2_env.disable_logs === true) {
2017-07-20 14:24:06 +02:00
return cb ? cb() : false;
}
if (pm2_env.log_type && pm2_env.log_type === 'json') {
log_data = JSON.stringify({
message : string.toString(),
2020-04-13 12:21:41 +02:00
timestamp : pm2_env.log_date_format && dayjs ?
dayjs().format(pm2_env.log_date_format) : new Date().toISOString(),
type : 'out',
process_id : pm2_env.pm_id,
app_name : pm2_env.name
}) + '\n';
}
2020-04-13 12:21:41 +02:00
else if (pm2_env.log_date_format && dayjs)
log_data = `${dayjs().format(pm2_env.log_date_format)}: ${string.toString()}`;
else
log_data = string.toString();
2017-02-02 15:41:01 +01:00
process.send({
type : 'log:out',
data : log_data
});
if (Utility.checkPathIsNull(pm2_env.pm_out_log_path) &&
(!pm2_env.pm_log_path || Utility.checkPathIsNull(pm2_env.pm_log_path)))
return cb ? cb() : null;
stds.std && stds.std.write && stds.std.write(log_data, encoding);
stds.out && stds.out.write && stds.out.write(log_data, encoding, cb);
};
})(process.stdout.write);
2014-05-05 11:39:14 +02:00
2016-09-17 13:43:58 +02:00
function getUncaughtExceptionListener(listener) {
return function uncaughtListener(err) {
2016-09-29 11:27:21 +02:00
var error = err && err.stack ? err.stack : err;
if (listener === 'unhandledRejection') {
error = 'You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:\n' + error;
}
2016-09-29 11:27:21 +02:00
logError(['std', 'err'], error);
2016-09-29 10:46:29 +02:00
2016-09-17 13:43:58 +02:00
// Notify master that an uncaughtException has been catched
try {
2016-09-29 11:27:21 +02:00
if (err) {
var errObj = {};
2016-09-17 13:43:58 +02:00
2016-09-29 11:27:21 +02:00
Object.getOwnPropertyNames(err).forEach(function(key) {
errObj[key] = err[key];
});
}
2016-09-17 13:43:58 +02:00
process.send({
type : 'log:err',
topic : 'log:err',
2016-09-29 11:27:21 +02:00
data : '\n' + error + '\n'
2016-09-17 13:43:58 +02:00
});
process.send({
type : 'process:exception',
2016-09-29 11:27:21 +02:00
data : errObj !== undefined ? errObj : {message: 'No error but ' + listener + ' was caught!'}
2016-09-17 13:43:58 +02:00
});
} catch(e) {
logError(['std', 'err'], 'Channel is already closed can\'t broadcast error:\n' + e.stack);
}
2013-10-01 23:45:22 +02:00
2016-09-17 13:43:58 +02:00
if (!process.listeners(listener).filter(function (listener) {
return listener !== uncaughtListener;
}).length) {
if (listener == 'uncaughtException') {
process.emit('disconnect');
process.exit(cst.CODE_UNCAUGHTEXCEPTION);
}
2016-09-17 13:43:58 +02:00
}
}
2016-09-17 13:43:58 +02:00
}
2016-09-17 13:43:58 +02:00
process.on('uncaughtException', getUncaughtExceptionListener('uncaughtException'));
process.on('unhandledRejection', getUncaughtExceptionListener('unhandledRejection'));
// Change dir to fix process.cwd
process.chdir(pm2_env.pm_cwd || process.env.PWD || p.dirname(script));
2020-01-13 14:52:59 +01:00
if (ProcessUtils.isESModule(script) === true)
2023-01-16 14:04:04 +10:00
import(Url.pathToFileURL(process.env.pm_exec_path));
2024-11-12 13:54:46 +00:00
else {
if (cst.IS_BUN) {
require(script);
}
else {
require('module')._load(script, null, true);
}
}
2015-01-28 12:56:02 +08:00
function logError(types, error){
try {
types.forEach(function(type){
stds[type] && typeof stds[type].write == 'function' && stds[type].write(error + '\n');
});
} catch(e) { }
}
});
}