我正在使用PM2来管理基于Node.js的微服务平台。我们想要一个仪表板,从那里我们可以看到微服务状态,例如如果有任何服务占用过多的CPU或内存,我使用了PM2的api并编写了以下代码。
function getMicroService(){
pm2.connect(function(err) {
if(!err){
// Get all processes running
logger.info('core_module','Connecting to PM2 Daemon for Micro Services List');
var dataArr = {};
var microServices = [];
var counter = 0;
var curDateTime = helperLib.getDateTimeISO();
pm2.list(function(err, process_list) {
if(process_list.length > 0){
process_list.forEach(function(process){
delete process.pm2_env;
process.lastChecked = curDateTime;
microServices.push(process);
counter++;
})
}
if(counter == process_list.length){
dataArr.event = 'microServices';
dataArr.data = microServices;
publishStats(dataArr);
}
});
}else{
logger.error('core_module','on Line 245: '+err)
}
})
}
上述功能每15秒调用一次,并在仪表板上显示数据。但我注意到这项服务开始占用过多的CPU超过100%而PM2整个守护进程服务脱机并停止响应。无法发出任何命令,例如pm2停止所有等等。我不得不手动终止进程,然后再次启动服务。我从日志文件中提取的错误是
{"message":"core_module Threw Exception: ","stack":"Error: EMFILE: too many open files, open '/root/.pm2/pm2.log'\n at Object.fs.openSync (fs.js:584:18)\n at module.exports.Client.launchDaemon (/etc/node/node_modules/pm2/lib/Client.js:207:14)\n at /etc/node/node_modules/pm2/lib/Client.js:102:10\n at /etc/node/node_modules/pm2/lib/Client.js:294:14\n at _combinedTickCallback (internal/process/next_tick.js:73:7)\n at process._tickDomainCallback (internal/process/next_tick.js:128:9)","errno":-24,"code":"EMFILE","syscall":"open","path":"/root/.pm2/pm2.log","__error_callsites":[{},{},{},{},{},{}],"level":"error","timestamp":"2017-10-20T00:49:26.826Z"}
如果上述代码是正确的,请有人帮忙吗?每15秒调用一次是一种很好的方法,或者我该如何优化它。我应该在函数末尾调用pm2.disconnect()。
请告知。
此致 哈比卜
答案 0 :(得分:0)
您需要在最后调用pm.disconnect()
,否则您最终会打开所有已创建的连接。它在pm2 api documentation:
If your script does not exit by itself, make sure you called pm2.disconnect() at the end.