【问题标题】:Python server app leaking memoryPython 服务器应用程序泄漏内存
【发布时间】:2015-11-03 08:55:34
【问题描述】:

我正在尝试诊断我的 Python 服务器应用程序泄漏内存的原因。该应用程序接受对图像 url 的请求,使用 Vips 调整其大小并返回图像。每次请求后,内存使用量大致增长原始图像的大小。

from fapws import base
import fapws._evwsgi as evwsgi
from gi.repository import Vips
import urllib2
import hmac
import hashlib
import base64
import StringIO
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket

def start():
    evwsgi.start('0.0.0.0', '80')
    evwsgi.set_base_module(base)

    def lfrThumbnail(environ, start_response):
        try:
            parameters = environ['PATH_INFO'].split('/')
            s3File = 'my s3 url' + parameters[0]
            width = float(parameters[1])
            height = float(parameters[2])
            hmacSignatureUser = parameters[3]

            hmacSignature = some hasing code...

            if not (hmacSignatureUser == hmacSignature):
                print hmacSignatureUser
                print hmacSignature
                print hmacSignatureUser == hmacSignature
                raise Exception

            bufferedImage = urllib2.urlopen(s3File).read()
            image = Vips.Image.new_from_buffer(bufferedImage, '')

            imageWidth = float(image.width)
            imageHeight = float(image.height)
            imageAspectRatio =  imageWidth / imageHeight
            if (width > imageWidth) or (height > imageHeight):
                image = image
            elif abs((imageAspectRatio / (width/height)) - 1) < 0.05:
                image = image.resize(width / imageWidth)
            else:
                scaleRatioWidth = width / imageWidth
                scaleRatioHeight = height / imageHeight
                maxScale = max(scaleRatioWidth, scaleRatioHeight)
                image = image.resize(maxScale)
                cropStartX = (image.width - width) / 2
                cropStartY = (image.height - height) / 2
                image = image.crop(cropStartX, cropStartY, width, height)

        except Exception, e:
            start_response('500 INTERNAL SERVER ERROR', [('Content-Type','text')])
            return ['Error generating thumbnail']

        start_response('200 OK', [
            ('Content-Type','image/jpeg'),
            ('Cache-Control: max-stale', '31536000')
        ])
        return [image.write_to_buffer('.jpg[Q=90]')]

    evwsgi.wsgi_cb(('/lfr/', lfrThumbnail))

    evwsgi.set_debug(0)
    evwsgi.run()

if __name__ == '__main__':
    start()

我尝试过使用 puppy 跟踪器,但图像打开/关闭操作后的每个差异都显示仅使用了几个字节。

外部 C 库是否会导致内存泄漏?如果是这样,如何调试它。

如果有什么相关的,我会在 docker 容器中运行 python 服务器

【问题讨论】:

    标签: python memory-leaks docker vips


    【解决方案1】:

    我是 libvips 维护者。听起来像是 vips 操作缓存:vips 将最后几个操作保存在内存中,并尽可能重用结果。在某些情况下,这可能是一个巨大的性能胜利。

    对于 Web 服务,您可能在其他地方进行缓存,因此您不会想要这个,或者您至少不会想要大缓存。你可以通过vips_cache_set_max()和朋友来控制缓存大小:

    http://www.vips.ecs.soton.ac.uk/supported/current/doc/html/libvips/VipsOperation.html#vips-cache-set-max

    在 Python 中是:

    Vips.cache_set_max(0)
    

    完全关闭缓存。您可以将缓存设置为通过内存使用、文件描述符使用或操作数来限制。

    您可以设置一些其他有用的东西来监视资源使用情况。 Vips.leak_set(True) 使 vips 在退出时报告泄漏的对象,并报告像素缓冲区内存使用的峰值。 Vips.cache_set_trace(True) 使它跟踪所有被调用的操作,并显示缓存命中。

    在您的代码中,我还将启用顺序模式。将access = Vips.Access.SEQUENTIAL 添加到您的new_from_buffer()。

    默认行为是打开图像以进行完全随机访问(因为 vips 不知道您最终会在图像上运行什么操作)。对于 JPG 之类的东西,这意味着 vips 会在打开时将图像解码为一个大型未压缩数组。如果图像小于 100mb,它会将这个数组保存在内存中。

    但是,对于简单的调整大小,您只需要从上到下访问像素,因此您可以在打开时提示顺序访问。在这种模式下,vips 只会从您的输入中一次解压缩几条扫描线,并且永远不会保留整个未压缩的图像。您应该会看到内存使用和延迟显着下降。

    您可以处理许多其他事情,例如 exif 自动旋转、颜色管理、透明度、jpeg 加载时收缩等等,我相信您知道。 vipsthumbnail 的来源可能是一个有用的参考:

    https://github.com/jcupitt/libvips/blob/master/tools/vipsthumbnail.c

    【讨论】:

    • 使用 Vips.leak_set(True),vips 只在服务器停止时报告内存使用峰值,这也是 Python 脚本退出的时候。我应该在处理请求后关闭 vip 吗?
    • 我会让 vips 继续运行,您将节省启动/关闭时间。峰值内存报告对于测试很方便,但在生产中不是很有用。 C API 有一个东西可以获取当前的峰值内存,但它没有暴露给 Python,我会添加这个。 libvips 有一个相当大的测试套件,全部用 Python 编写,其中一个测试是“整个测试套件是否完整且没有内存泄漏?”,所以希望你不应该在服务器中看到泄漏,它更像是一个仔细检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2016-03-28
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多