简体   繁体   English

PM2 - 不正确的内存使用读取和 Node.js 应用程序可能的内存泄漏

[英]PM2 - Incorrect memory usage reading & possible memory leak with Node.js application

When my node js server is running via pm2, it has a higher memory usage reading than the actual memory heap in the application when inspected in DevTools.当我的节点 js 服务器通过 pm2 运行时,在 DevTools 中检查时,它的内存使用率读数高于应用程序中的实际内存堆。 More so, the value under memory in pm2 slowly increases over time, possibly indicating some kind of memory leak.更重要的是,pm2 中memory下的值随着时间的推移缓慢增加,可能表明某种内存泄漏。 This slow increase in memory usage also cannot be observed in DevTools.在 DevTools 中也无法观察到这种内存使用量的缓慢增加。

Any explanation and/or solutions to these two (seemingly) strange occurrences?对这两个(看似)奇怪的事件有什么解释和/或解决方案?

This is my DevTools这是我的开发者工具

在此处输入图片说明

This is pm2 list这是pm2 list

在此处输入图片说明

here is my javascript code这是我的javascript代码

var SSE = require('sse');
var https = require('https');
var fs = require('fs');
var url = require('url');
var mysql = require('mysql');
var schedule = require('node-schedule');

var options = {
    key: fs.readFileSync('pathto/ssl.key'),
    cert: fs.readFileSync('pathto/ssl.crt'),
    ca: fs.readFileSync('pathto/ssl.ca-bundle')
};


var pool = mysql.createPool({
    connectionLimit: 100,
    host: "host",
    user: "user",
    password: "pass",
    database: "db"
});

async function connectandrun() {
    try {

        var server = https.createServer(options, function(req, res) {
            var queryData = url.parse(req.url, true).query;
            res.writeHead(200, {
                'Content-Type': 'text/event-stream',
                'Access-Control-Allow-Origin': '*',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
                'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
                'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
            });

            if (queryData.connectionid) {
                var connecitonid = queryData.connectionid;
            } else {
                var connecitonid = "";
            }

            var myconection = "myconnecction" + connecitonid;
            var uuserjson = {};
            uuserjson[myconection] = {
                Data: {
                    Element: null
                }
            };

            schedule.scheduleJob('*/3 * * * * *', function() {
                var runninginstance = main(uuserjson, queryData, myconection, res).catch(console.error);
                runninginstance = null;
            });

            res.on("close", function() {
                res.end();
                uuserjson[myconection] = null;
                myconection = null;
                connecitonid = null;
            });
        });

        server.listen(3000, '0.0.0.0', function() {
            var sse = new SSE(server);
            sse.on('connection', function(client) {
                client.send('hi there!');
            });
        });

    } finally {}
}

connectandrun().catch(console.error);

async function main(uuserjson, queryData, myconection, res) {


    pool.getConnection(function(err, con) {
        if (err) {
            console.log(err);
        } else {
            con.query("MYSQL QUERY",
                function(err, result, fields) {
                    if (err) throw err;
                    if (result.length != 0) {
                        uuserjson[myconection] = {
                            Data: {
                                Element: result[0]
                            }
                        };

                        if (result[0]) {
                            res.write("retry: 30000\n\n" + "event: blanks\ndata: " + result[0] + "\n\n");
                        }
                    }

                    con.release();
                });
        }
    });

}

After teaming up with OP on this, it has been confirmed there is some sort of memory leak in PM2 .在与 OP 合作后,已确认PM2存在某种内存泄漏。

Please see the below 'write-up' on our findings:请参阅以下有关我们调查结果的“文章”:


The Issue:问题:

  • Slowly over time PM2 uses more and more RAM随着时间的推移, PM2使用越来越多的 RAM
    • This points to some sort of memory leak这指向某种内存泄漏

Evidence & Rumors:证据与谣言:

  • When running the application without PM2 , just using node myserver.js , there is no evidence of RAM slowly increasing over time在没有PM2的情况下运行应用程序时,仅使用node myserver.js ,没有证据表明 RAM 随着时间的推移缓慢增加
    • RAM remains flat RAM保持平稳
    • The application that was used to test this theory is a small web app, in order to minimize the chance that the code contains a memory leak, and that the leak is in fact coming from PM2用于测试该理论的应用程序是一个小型 Web 应用程序,以尽量减少代码包含内存泄漏的机会,而泄漏实际上来自PM2
  • There have been 'rumors' and evidence of memory leaks in PM2 for quite some time now - going back as far as 4 years (this answer was written in December 2019)很长一段时间以来,一直有“谣言”和PM2内存泄漏的证据——可以追溯到 4 年前(这个答案写于 2019 年 12 月)
  • Someone describing why they stopped using PM2 有人描述了他们停止使用PM2
    • See last comment查看最后一条评论
  • Thread where others are describing similar issues 其他人描述类似问题的主题
    • That do not occur when PM2 is NOT used使用PM2时不会发生这种情况
  • Bug filed on PM2 GitHub with a confirmed memory leakPM2 GitHub 上提交的错误已确认内存泄漏
    • This bug was filed this year [2019] and at the time of this writing has comments as recent as October, where someone describes how this is still an issue这个错误是在今年 [2019] 年提交的,在撰写本文时,最近在 10 月份就有评论,有人描述了这仍然是一个问题

PM2 Alternatives You Should Consider:您应该考虑的 PM2 替代品:

  • Phusion Passenger seems like a strong candidate for replacing PM2 Phusion Passenger似乎是替代PM2的有力候选人
  • Forever
    • Does not seem like it is actively being maintained (in some of the issues filed on their GitHub people recommend using other apps)似乎没有得到积极维护(在他们 GitHub 上提交的一些问题中,人们建议使用其他应用程序)
  • Nodemon
    • Not really 'apples to apples' with PM2 , but hey, variety is the spice of life PM2并不是真正的“苹果对苹果”,但是嘿,多样性是生活的调味品
  • Naught
    • Does not appear to be actively maintained and is kind of 'small' in terms of stars似乎没有得到积极维护,并且在星级方面有点“小”
  • Native Node.js cluster原生Node.js集群

PM2 Workarounds/Band-Aids: (!not recommended to rely on these in Production!) PM2解决方法/创可贴:( !不建议在生产中依赖这些!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM