Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为了避免内存泄漏,我应该在python云函数中避免哪些事情? 一般问题_Python_Google Cloud Functions - Fatal编程技术网

为了避免内存泄漏,我应该在python云函数中避免哪些事情? 一般问题

为了避免内存泄漏,我应该在python云函数中避免哪些事情? 一般问题,python,google-cloud-functions,Python,Google Cloud Functions,我的python Cloud函数每秒引发大约0.05个内存错误-每秒调用大约150次。我感觉我的函数留下了内存残差,一旦实例处理了许多请求,就会导致实例崩溃。为了使函数实例在每次被调用时不会占用“更多的分配内存”,您应该做或不应该做什么?我被指给文档学习,因为这是写在内存中的,但我认为我没有写过任何东西 更多上下文 我函数的代码可以总结如下 全局上下文:在Google云存储上获取一个文件,其中包含已知的机器人程序用户代理列表。实例化一个错误报告客户端 如果用户代理识别bot,则返回200代码。

我的python Cloud函数每秒引发大约0.05个内存错误-每秒调用大约150次。我感觉我的函数留下了内存残差,一旦实例处理了许多请求,就会导致实例崩溃。为了使函数实例在每次被调用时不会占用“更多的分配内存”,您应该做或不应该做什么?我被指给文档学习,因为这是写在内存中的,但我认为我没有写过任何东西

更多上下文 我函数的代码可以总结如下

  • 全局上下文:在Google云存储上获取一个文件,其中包含已知的机器人程序用户代理列表。实例化一个错误报告客户端
  • 如果用户代理识别bot,则返回200代码。Else解析请求的参数,重命名它们,格式化它们,给请求的接收加上时间戳
  • 将生成的消息以JSON字符串形式发送到Pub/Sub
  • 返回一个200码
我相信我的实例正在逐渐消耗所有可用内存,因为我在Stackdriver中完成了以下图表:

这是我的云函数实例内存使用的热图,红色和黄色表示我的大多数函数实例都在使用这一范围的内存。由于似乎出现的循环,我将其解释为逐渐填满实例的内存,直到它们崩溃并生成新实例。如果我提高分配给函数的内存,这个循环将保持不变,它只会提高循环后的内存使用上限

编辑:代码摘录和更多上下文 这些请求包含有助于在电子商务网站上实施跟踪的参数。既然我复制了它,可能会有一个反模式,我在迭代时修改
表单['products']
,但我认为这与内存浪费无关

from json import dumps
from datetime import datetime
from pytz import timezone

from google.cloud import storage
from google.cloud import pubsub
from google.cloud import error_reporting

from unidecode import unidecode

# this is done in global context because I only want to load the BOTS_LIST at
# cold start
PROJECT_ID = '...'
TOPIC_NAME = '...'
BUCKET_NAME = '...'
BOTS_PATH = '.../bots.txt'
gcs_client = storage.Client()
cf_bucket = gcs_client.bucket(BUCKET_NAME)
bots_blob = cf_bucket.blob(BOTS_PATH)
BOTS_LIST = bots_blob.download_as_string().decode('utf-8').split('\r\n')
del cf_bucket
del gcs_client
del bots_blob

err_client = error_reporting.Client()


def detect_nb_products(parameters):
    '''
    Detects number of products in the fields of the request.
    '''
    # ...


def remove_accents(d):
    '''
    Takes a dictionary and recursively transforms its strings into ASCII
    encodable ones
    '''
    # ...


def safe_float_int(x):
    '''
    Custom converter to float / int
    '''
    # ...


def build_hit_id(d):
    '''concatenate specific parameters from a dictionary'''
    # ...


def cloud_function(request):
    """Actual Cloud Function"""
    try:
        time_received = datetime.now().timestamp()
        # filtering bots
        user_agent = request.headers.get('User-Agent')
        if all([bot not in user_agent for bot in BOTS_LIST]):
            form = request.form.to_dict()
            # setting the products field
            nb_prods = detect_nb_products(form.keys())
            if nb_prods:
                form['products'] = [{'product_name': form['product_name%d' % i],
                                     'product_price': form['product_price%d' % i],
                                     'product_id': form['product_id%d' % i],
                                     'product_quantity': form['product_quantity%d' % i]}
                                    for i in range(1, nb_prods + 1)]

            useful_fields = [] # list of keys I'll keep from the form
            unwanted = set(form.keys()) - set(useful_fields)
            for key in unwanted:
                del form[key]

            # float conversion
            if nb_prods:
                for prod in form['products']:
                    prod['product_price'] = safe_float_int(
                        prod['product_price'])

            # adding timestamp/hour/minute, user agent and date to the hit
            form['time'] = int(time_received)
            form['user_agent'] = user_agent
            dt = datetime.fromtimestamp(time_received)
            form['date'] = dt.strftime('%Y-%m-%d')

            remove_accents(form)

            friendly_names = {} # dict to translate the keys I originally
            # receive to human friendly ones
            new_form = {}
            for key in form.keys():
                if key in friendly_names.keys():
                    new_form[friendly_names[key]] = form[key]
                else:
                    new_form[key] = form[key]
            form = new_form
            del new_form

            # logging
            print(form)

            # setting up Pub/Sub
            publisher = pubsub.PublisherClient()
            topic_path = publisher.topic_path(PROJECT_ID, TOPIC_NAME)
            # sending
            hit_id = build_hit_id(form)
            message_future = publisher.publish(topic_path,
                                               dumps(form).encode('utf-8'),
                                               time=str(int(time_received * 1000)),
                                               hit_id=hit_id)
            print(message_future.result())

            return ('OK',
                    200,
                    {'Access-Control-Allow-Origin': '*'})
        else:
        # do nothing for bots
            return ('OK',
                    200,
                    {'Access-Control-Allow-Origin': '*'})
    except KeyError:
        err_client.report_exception()
        return ('err',
                200,
                {'Access-Control-Allow-Origin': '*'})

有一些事情你可以尝试(理论上的答案,我还没有玩过CFs):

  • 显式删除您在机器人程序处理路径上分配的临时变量,这些变量可能相互引用,从而防止内存垃圾收集器释放它们(请参阅):
    nb_prods
    不需要的
    表单
    新表单
    友好的名称
    ,例如

  • 如果不需要的总是相同的,则将其改为全局

  • 删除
    表单
    ,然后将其重新分配给
    新表单
    (旧的
    表单
    对象保留);另外,删除
    新表单
    实际上不会节省太多,因为对象仍然由
    表单
    引用。即改变:

        form = new_form
        del new_form
    
    进入

  • 在发布主题后返回之前,显式调用内存垃圾收集器。我不确定这是否适用于CFs,或者调用是否立即有效(例如,在GAE中不是,请参阅)。这也可能是过分的,可能会损害CF的性能,看看它是否/如何为您工作

    gc.collect()
    

您是否因为撞车而面临任何问题?云函数应该会自动生成新的实例。另外,您如何抓取文件并打开它?你要关闭文件吗?如果没有看到所有相关代码,就不可能说任何具体的内容。所能提供的只是删除临时文件,并且不在全局内存中的任何位置存储任何内容,除非它的大小由您完全控制。您是否使用tempfile.mkstemp?如果是这样,请看一下这个:。另外,看看这些最佳实践:刚刚添加了代码@Kannapan由于文件是从全局上下文中的连接获取的,所以我不认为我必须关闭任何东西?我并不是因为这个才有“问题”的,但我很好奇没有记忆错误的可能性,我不喜欢我的一些事件可能得不到处理的想法。
gc.collect()