繁体   English   中英

Python服务器应用泄漏内存

[英]Python server app leaking memory

我正在尝试诊断为什么我的Python服务器应用程序正在泄漏内存。 该应用程序请求使用Vips调整图像URL大小的请求,然后返回图像。 在每个请求之后,内存使用量将按原始图像的大小大致增长。

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()

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

外部C库可能是导致内存泄漏的原因吗? 如果是这样,如何进行调试。

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

我是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,它将将该数组保留在内存中。

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

您还可以处理很多其他事情,例如exif自动旋转,色彩管理,透明度,jpeg负载收缩等等,我敢肯定。 vipsthumbnail的来源可能是有用的参考:

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

暂无
暂无

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

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