如何进行与Python进程相关的内存泄漏故障排除?

2024-04-29 07:01:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python机器人,可以交易加密货币(不能共享源代码,它不是我的)。我从另一个开发人员那里得到了这个机器人,他把它弄得一团糟,我能把它修好很多

最近,我接到一个投诉,说机器人正在泄漏内存,大约每天98 MB

我已经解决了一点,这是我发现的:

  1. 脚本中有一个主循环,它只是检查何时购买或出售加密的一些条件。我添加了objgraph.show_growth(),以查看在循环的末尾和开头分配了多少对象

    while True:
        print("MEM PROFILING START: " + datetime.now().strftime("%d/%m/%Y %H:%M:%S"), flush=True)
        objgraph.show_growth()
        print("MEM PROFILING END: " + datetime.now().strftime("%d/%m/%Y %H:%M:%S"), flush=True)
    
        # ... some logic
    
        print("MEM PROFILING START: " + datetime.now().strftime("%d/%m/%Y %H:%M:%S"), flush=True)
        objgraph.show_growth()
        print("MEM PROFILING END: " + datetime.now().strftime("%d/%m/%Y %H:%M:%S"), flush=True)
    

    令我惊讶的是,在机器人启动后,它分配了一堆东西,但是没有更多的分配,但是内存消耗仍然在增长

  2. 我尝试的另一件事是将内存差异从一个时间点转储到另一个时间点(ref:https://unix.stackexchange.com/a/399115/63883):dump memory ./dump_diff3.dump 0x0f3da000 0x0f43e000我看到在常驻集中保存了一堆证书信息: enter image description here

我想这可能意味着一些python库出现了漏洞。我更新了请求库和所有依赖项,但是泄漏仍然存在,并且仍然保存了一堆证书信息

问题:下一步要尝试什么?我的想法是升级OpenSSL库和python包装器(列出以下版本)-但我对其他一些故障排除技术和解决方案感兴趣:

root@688213:~# dpkg -l '*openssl*'
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                               Version                Architecture           Description
+++-==================================-======================-======================-=========================================================================
ii  libgnutls-openssl27:amd64          3.4.10-4ubuntu1.5      amd64                  GNU TLS library - OpenSSL wrapper
ii  openssl                            1.0.2g-1ubuntu4.15     amd64                  Secure Sockets Layer toolkit - cryptographic utility
ii  openssl-blacklist                  0.5-3                  all                    Blacklists for  OpenSSL RSA keys and tools
un  python-openssl-doc                 <none>                 <none>                 (no description available)
ii  python3-openssl                    17.3.0-1~0+ubuntu16.04 all                    Python 3 wrapper around the OpenSSL library
un  python3-openssl-dbg                <none>                 <none>                 (no description available)

Tags: 内存objgraphnonetruedatetime机器人memnow