Skip to content

Instantly share code, notes, and snippets.

@zz85
Created March 13, 2018 08:26
Show Gist options
  • Save zz85/08b0bdd639c83f49df8891baca65b535 to your computer and use it in GitHub Desktop.
Save zz85/08b0bdd639c83f49df8891baca65b535 to your computer and use it in GitHub Desktop.
PM2 IPC
const express = require('express')
const app = express()
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(4444, () => console.log('Example app listening on port 4444!'))
process.on('message', function(packet) {
console.log('process message received', packet, process.env.pm_id, process.env.NODE_APP_INSTANCE)
process.send({
type : 'process:replies',
data : {
pong : 'pong',
from: process.env.pm_id
}
});
});
opts = {}
var pm2 = require('pm2');
pm2.connect(function (err, x) {
console.log('pm2 connected');
pm2.launchBus(function(err, bus) {
console.log('got bus');
bus.on('process:all', function(packet) {
console.log('on comomn bus msg', packet);
if (packet.process.pm_id !== process.env.pm_id) return;
});
});
});
app.get(opts.url || '/health', function (req, res) {
pm2.connect(function (err, x) {
// console.log('connect', x, err);
// if (err) { res.sendStatus(500); return; }
var count;
// pm2.launchBus(function(err, bus) {
// console.log('got bus');
// bus.on('process:replies', function(packet) {
// console.log('on bus msg', packet);
// // packet.data.success.should.eql(true);
// // packet.process.pm_id.should.eql(proc1.pm2_env.pm_id);
// // done();
// });
// count--;
// if (count === 0) pm2.disconnect();
// });
pm2.list(function (err, processes) {
console.log('processes', processes.length)
// console.log('pm2.list', processes, err);
// { pid, pm2_env: pm_id }
if (err) { res.sendStatus(500); return; }
var ok;
if (opts.optimistic) {
ok = processes.every((process) => { return process.pm2_env.status === 'online'; });
} else {
ok = processes.some((process) => { return process.pm2_env.status === 'online'; });
}
// res.sendStatus(ok ? 200 : 500);
res.send(`processes ${processes.length}`);
count = processes.length;
/*
processes.forEach(child => {
console.log('sending', child.pm2_env.pm_id);
pm2.sendDataToProcessId({
data : {
some : 'data',
hello : true,
time: new Date()
},
// type:'fail',
id: child.pm2_env.pm_id, // id of procces from "pm2 list" command or from pm2.list(errback) method
topic: 'process:msg'
}, function(err, res) {
// console.log('cab', err, res);
if (err) {
console.log('IPC fail', err, res);
}
});
}
)
*/
process.send({
type : 'process:all',
data : {
pong : 'pong',
from: process.env.pm_id,
id: 1234
},
meow: 321
});
// pm2.disconnect();
// res.send('processes' + JSON.stringify(process, null, '\t'));
// res.send('processes' + processes);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment