简体   繁体   English

测试时出现超时错误 Azure function app

[英]Timeout errors when testing Azure function app

Using Azure functions in a python runtime env.在 python 运行时环境中使用 Azure 函数。 to take latitude/longitude tuples from a snowflake database and return the respective countries.从雪花数据库中获取纬度/经度元组并返回各自的国家。 We also want to convert any non-english country names into English.我们还想将任何非英语国家/地区名称转换为英语。

We initially found that although the script would show output in the terminal while testing on azure, it would soon return a 503 error (although the script continues to run at this point).我们最初发现,虽然脚本在测试 azure 时会在终端显示 output,但很快就会返回 503 错误(尽管此时脚本继续运行)。 If we cancelled the script it would show as a success in the monitor screen of azure portal, however leaving the script to run to completion would result in the script failing.如果我们取消脚本,它将在 azure 门户的监控屏幕中显示为成功,但是让脚本运行完成将导致脚本失败。 We decided (partially based on this post) this was due to the runtime exceeding the maximum http response time allowed.我们决定(部分基于这篇文章)这是由于运行时超过了允许的最大响应时间 http。 To combat this we tried a number of solutions.为了解决这个问题,我们尝试了多种解决方案。

First we extended the function timeout value in the function.json file:首先我们扩展function.json文件中的function超时值:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  },
  "functionTimeout": "00:10:00"
}

We then modified our script to use a queue trigger by adding the output然后我们通过添加 output 修改脚本以使用队列触发器

def main(req: func.HttpRequest, msg: func.Out[func.QueueMessage]) ->func.HttpResponse:

to the main .py script.到主.py脚本。 We also then modified the function.json file to然后我们也将function.json文件修改为

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "processing",
      "connection": "QueueConnectionString"
    }
  ]
}

and the local.settings.json file tolocal.settings.json文件到

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "{AzureWebJobsStorage}",
    "QueueConnectionString": "<Connection String for Storage Account>",
    "STORAGE_CONTAINER_NAME": "testdocs",
    "STORAGE_TABLE_NAME": "status"
  }
}

We also then added a check to see if the country name was already in English.然后我们还添加了检查以查看国家/地区名称是否已经是英文。 The intention here was to cut down on calls to the translate function.这里的目的是减少对translate function 的呼叫。

After each of these changes we redeployed to the functions app and tested again.在这些更改中的每一项之后,我们都重新部署到功能应用程序并再次测试。 Same result.同样的结果。 The function will run, and print output to terminal, however after a few seconds it will show a 503 error and eventually fail. function 将运行,并将 output 打印到终端,但几秒钟后它将显示 503 错误并最终失败。

I can show a code sample but cannot provide the tables unfortunately.我可以展示代码示例,但遗憾的是无法提供表格。

from snowflake import connector
import pandas as pd
import pyarrow
from geopy.geocoders import Nominatim
from deep_translator import GoogleTranslator
from pprint import pprint
import langdetect
import logging
import azure.functions as func

def main(req: func.HttpRequest, msg: func.Out[func.QueueMessage]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # Connecting string to Snowflake
    conn = connector.connect(
                            user='<USER>',
                            password='<PASSWORD>',
                            account='<ACCOUNT>',
                            warehouse='<WH>',
                            database='<DB>',
                            schema='<SCH>'
                            )

    # Creating objects for Snowflake, Geolocation, Translate
    cur = conn.cursor()
    geolocator = Nominatim(user_agent="geoapiExercises")
    translator = GoogleTranslator(target='en')

    # Fetching weblog data to get the current latlong list
    fetchsql = "SELECT PAGELATLONG FROM <TABLE_NAME> WHERE PAGELATLONG IS NOT NULL GROUP BY PAGELATLONG;"
    logging.info(fetchsql)
    cur.execute(fetchsql)
    
    df = pd.DataFrame(cur.fetchall(), columns = ['PageLatLong'])
    logging.info('created data frame')

    # Creating and Inserting the mapping into final table
    for index, row in df.iterrows():
        latlong = row['PageLatLong']
        location = geolocator.reverse(row['PageLatLong']).raw['address']
        logging.info('got addresses')

        city = str(location.get('state_district'))
        country = str(location.get('country'))
        countrycd = str(location.get('country_code'))
        logging.info('got countries')
        
        # detect language of country
        res = langdetect.detect_langs(country)
        lang = str(res[0]).split(':')[0] 
        conf = str(res[0]).split(':')[0] 
        if lang != 'en' and conf > 0.99:
            country = translator.translate(country)
            logging.info('translated non-english country names')
        
        insertstmt = "INSERT INTO <RESULTS_TABLE> VALUES('"+latlong+"','"+city+"','"+country+"','"+countrycd+"')"
        logging.info(insertstmt)
        try:
            cur.execute(insertstmt)
        except Exception:
            pass
    return func.HttpResponse("success")

If anyone had an idea what may be causing this issue I'd appreciate any suggestions.如果有人知道可能导致此问题的原因,我将不胜感激任何建议。

Thanks.谢谢。

To resolve timeout errors, you can try following ways:要解决超时错误,您可以尝试以下方法:

  1. As suggested by MayankBargali-MSFT , You can try to define the retry policies and for Trigger like HTTP and timer, don't resume on a new instance.正如MayankBargali-MSFT所建议的,您可以尝试定义重试策略,对于 HTTP 和计时器之类的触发器,不要在新实例上恢复。 This means that the max retry count is a best effort, and in some rare cases an execution could be retried more than the maximum, or for triggers like HTTP and timer be retried less than the maximum.这意味着最大重试次数是最大努力,在极少数情况下,执行的重试次数可能会超过最大值,或者对于 HTTP 之类的触发器和计时器,重试次数可能会少于最大值。 You can navigate to Diagnose and solve problems to see if it helps you to know the root cause of 503 error as there can be multiple reasons for this error您可以导航到“ Diagnose and solve problems ”以查看它是否可以帮助您了解 503 错误的根本原因,因为此错误可能有多种原因

  2. As suggested by ryanchill , 503 issue is the result of high memory consumption which exceeded the limits of the consumption plan.正如ryanchill所建议的那样,503 问题是 memory 高消耗的结果,超出了消耗计划的限制。 The best resolve for this issue is switching to a dedicated hosting plan which provides more resources.此问题的最佳解决方案是切换到提供更多资源的专用托管计划。 However, if that isn't an option, reducing the amount of data being retrieved should be explored.但是,如果这不是一种选择,则应探索减少检索的数据量。

References: https://learn.microsoft.com/en-us/answers/questions/539967/azure-function-app-503-service-unavailable-in-code.html , https://learn.microsoft.com/en-us/answers/questions/522216/503-service-unavailable-while-executing-an-azure-f.html , https://learn.microsoft.com/en-us/answers/questions/328952/azure-durable-functions-timeout-error-in-activity.html and https://learn.microsoft.com/en-us/answers/questions/250623/azure-function-not-running-successfully.html参考资料: https://learn.microsoft.com/en-us/answers/questions/539967/azure-function-app-503-service-unavailable-in-code.html,https ://learn.microsoft.com/ zh-cn/answers/questions/522216/503-service-unavailable-while-executing-an-azure-f.html , https://learn.microsoft.com/en-us/answers/questions/328952/azure-持久函数超时错误活动.html 和https://learn.microsoft.com/en-us/answers/questions/250623/azure-function-not-running-successfully.html

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

相关问题 Azure Function 超时事件,原因 - Azure Function timeout event, reasons 在本地测试 (Python) Google Cloud Function 时出现应用程序上下文错误 - Application context errors when locally testing a (Python) Google Cloud Function 在 .NET 中创建新的 Azure Function 应用程序后出错 6 - Errors after creating new Azure Function app in .NET 6 在 Azure Web App 中构建 Blazor 时出现引用完整性错误 - Referential integrity errors when building Blazor in Azure Web App Azure Function 30 分钟后超时 - Azure Function Timeout after 30 minutes Azure 逻辑应用表插入导致错误 - Azure logic app table insertions causing errors Azure Function 应用程序:在门户中为新的 function 应用程序加载 V3 时出错? - Azure Function App : Error when loading V3 in portal for fresh function app? 当 Azure 应用程序注册用于保护 Function 应用程序的授权时,必须验证令牌 - Must a token be verified when Azure App Registration is used for Authorization when securing a Function App 部署到 Azure Function App 时跨执行共享的字典值 - Dictionary values shared across executions when deployed to Azure Function App Azure Function 部署成功时应用运行旧代码 - Azure Function App running old code when deployments are successful
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM