在运行时获取当前重试尝试计数

在运行时获取当前重试尝试计数

本文介绍了AWS Lambda:在运行时获取当前重试尝试计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行特定任务的AWS Lambda( python3.7 运行时),并且其 MaximumRetryAttempts 设置为 1 (这意味着它可以失败一次,然后再尝试1次.)

I have an AWS Lambda (python3.7 runtime) that runs certain task, and its MaximumRetryAttempts is set to 1 (meaning it can fail once, then have 1 more try).

出于某种原因,我想在运行时知道这是第一次尝试还是第二次尝试.有什么方法可以实现?

For a reasons I won't get into, I want to know, at runtime, if this is the first attempt or the second. Is there any way to achieve that?

推荐答案

import json
import boto3
from datetime import datetime, timedelta
import time

aws_cloud_watch_logs_client = boto3.client('logs')
lambda_invocation_count_query = "fields @retry_count | filter @message like 'REPORT' AND @requestId = '{lambda_request_id}' | stats count(@message) as retry_count"
aws_cloud_watch_log_group = '/aws/lambda/mylambdaname' # Set aws cloudwatch log group name as per your setup

def lambda_handler(event, context):
    lambda_retry_counts=get_lambda_retry_count(context)
    print("lambda_retry_counts=",lambda_retry_counts)
    #TODO : your logic here


# refactor to reduce complexity, might extract method to cover single responsibility principle
def get_lambda_retry_count(context):
    print("context.aws_request_id=", context.aws_request_id)
    qry=lambda_invocation_count_query.format(lambda_request_id=context.aws_request_id)
    print(qry)
    start_query_response = aws_cloud_watch_logs_client.start_query(
    logGroupName=aws_cloud_watch_log_group,
    startTime=int((datetime.today() - timedelta(hours=1)).timestamp()), # Refactor as per your requirement
    endTime=int(datetime.now().timestamp()),
    queryString=qry,
    )

    query_id = start_query_response['queryId']

    response = None

    while response == None or response['status'] == 'Running':
        print('Waiting for cloud watch query to complete ...')
        time.sleep(10) # Refactor as per your requirement
        response = aws_cloud_watch_logs_client.get_query_results(
            queryId=query_id
        )

    if response['results']:
        return response['results'][0][0]['value'] # refactor for readability, maintenance
    else:
        return 0

或者,要查询aws云监视,您还可以将AWS系统参数存储与aws_request_id一起用作参数名称的一部分,以唯一地标识它.此外,将lambda重试计数保留为该参数的值.根据aws_request_id每次执行lambda时将其递增.如果达到阈值,则按照您的逻辑进行处理,并删除名称为aws_request_id且名称已达到阈值的AWS系统参数存储.摘要-您只需要一些存储即可保留aws_request_id和重试计数的映射.

Alternative, To query aws cloud watch, you can also use AWS System Parameter Store with aws_request_id as part of Parameter name to uniquely identify it. Furthermore, keep lambda retry count as value of this Parameter. Increment it per execution of lambda based on aws_request_id. If threshold reach then handle as per your logic and delete the AWS System Parameter Store with name having the aws_request_id for which threshold is reached. Summary- you just need some storage which keeps mapping of aws_request_id and retry count.

这篇关于AWS Lambda:在运行时获取当前重试尝试计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:42