embark/lib/core/processes/processWrapper.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-08-16 14:01:48 +00:00
process.on('uncaughtException', function(e){
process.send({error: e.stack});
});
2018-07-27 21:33:50 +00:00
const constants = require('../../constants');
const Events = require('./eventsWrapper');
2018-05-15 19:56:15 +00:00
class ProcessWrapper {
2018-05-16 15:58:18 +00:00
/**
* Class from which process extend. Should not be instantiated alone.
* Manages the log interception so that all console.* get sent back to the parent process
2018-05-16 16:03:39 +00:00
* Also creates an Events instance. To use it, just do `this.events.[on|request]`
2018-05-16 15:58:18 +00:00
*
* @param {Options} options pingParent: true by default
2018-05-16 15:58:18 +00:00
*/
2018-09-14 09:30:20 +00:00
constructor(options = {}) {
this.options = Object.assign({pingParent: true}, options);
2018-05-15 19:56:15 +00:00
this.interceptLogs();
this.events = new Events();
2018-09-14 09:30:20 +00:00
if(this.options.pingParent) {
this.pingParent();
}
2018-06-05 16:09:57 +00:00
}
// Ping parent to see if it is still alive. Otherwise, let's die
pingParent() {
const self = this;
self.retries = 0;
function error() {
if (self.retries > 2) {
self.kill();
process.exit();
}
self.retries++;
}
setInterval(() => {
try {
let result = self.send({action: 'ping'});
if (!result) {
return error();
}
2018-06-13 18:09:59 +00:00
self.retries = 0;
2018-06-05 16:09:57 +00:00
} catch (e) {
error();
}
}, 500);
2018-05-15 19:56:15 +00:00
}
interceptLogs() {
const context = {};
context.console = console;
2018-05-16 15:58:18 +00:00
context.console.log = this._log.bind(this, 'log');
context.console.warn = this._log.bind(this, 'warn');
2018-05-24 20:34:27 +00:00
context.console.error = this._log.bind(this, 'error');
2018-05-16 15:58:18 +00:00
context.console.info = this._log.bind(this, 'info');
context.console.debug = this._log.bind(this, 'debug');
context.console.trace = this._log.bind(this, 'trace');
context.console.dir = this._log.bind(this, 'dir');
2018-05-15 19:56:15 +00:00
}
2018-05-16 15:58:18 +00:00
_log(type, ...messages) {
const isHardSource = messages.some(message => {
2018-07-20 01:47:59 +00:00
return (typeof message === 'string' && message.indexOf('hardsource') > -1);
2018-05-16 15:58:18 +00:00
});
if (isHardSource) {
2018-05-15 19:56:15 +00:00
return;
}
this.send({result: constants.process.log, message: messages, type});
2018-05-15 19:56:15 +00:00
}
2018-05-22 18:13:56 +00:00
send() {
if (!process.connected) {
return false;
}
2018-06-13 18:00:21 +00:00
return process.send(...arguments);
2018-05-22 18:13:56 +00:00
}
2018-06-05 16:09:57 +00:00
kill() {
// Should be implemented by derived class
console.log('Process killed');
}
2018-05-15 19:56:15 +00:00
}
process.on('exit', () => {
process.exit(0);
});
module.exports = ProcessWrapper;