decorators和类将失败注入aws lambda函数
chaos-lambda的Python项目详细描述
chaos_lambda是一个向AWS Lambda注入混沌的小型库。 它提供了简单的python装饰器来执行delay,exception和statuscode注入 以及一个将延迟添加到从函数调用的任何第三方依赖项的类。 这允许为您的无服务器应用程序进行小型混沌工程实验 在AWS Cloud中。
- 使用delay 支持延迟注入
- 使用exception_msg 支持异常注入
- 使用error_code 支持http错误状态代码注入
- 使用for ssm参数存储来控制使用isEnabled 的实验
- 支持使用rate添加失败率。(默认速率=1)
- 使用环境变量(CHAOS_PARAM)的每lambda函数注入控制
安装
pip install chaos-lambda
示例
# function.pyfromchaos_lambdaimport(inject_delay,inject_exception,inject_statuscode)os.environ['CHAOS_PARAM']='chaoslambda.config'@inject_exceptiondefhandler_with_exception(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_exception(exception_type=TypeError,exception_msg='foobar')defhandler_with_exception_arg(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_exception(exception_type=ValueError)defhandler_with_exception_arg_2(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_statuscodedefhandler_with_statuscode(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_statuscode(error_code=400)defhandler_with_statuscode_arg(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_delaydefhandler_with_delay(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_delay(delay=1000)defhandler_with_delay_arg(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}@inject_delay(delay=0)defhandler_with_delay_zero(event,context):return{'statusCode':200,'body':'Hello from Lambda!'}
当超出时,lambda函数(例如handler_with_exception('foo', 'bar'))将产生以下结果:
exception_msg from config I really failed seriously with a rate of 1 corrupting now Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../chaos_lambda.py", line 199, in wrapper raise Exception(exception_msg) Exception: I really failed seriously
配置
失败注入的配置存储在AWS SSM Parameter Store中,并在运行时由^{tt9}访问$ 功能:
{"isEnabled":true,"delay":400,"error_code":404,"exception_msg":"I really failed seriously","rate":1}
要使用AWS CLI将上述配置存储到ssm中,请执行以下操作:
aws ssm put-parameter --region eu-north-1 --name chaoslambda.config --type String --overwrite --value "{ "delay": 400, "isEnabled": true, "error_code": 404, "exception_msg": "I really failed seriously", "rate": 1 }"
aws lambda需要有IAM access to SSM。
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["ssm:DescribeParameters"],"Resource":"*"},{"Effect":"Allow","Action":["ssm:GetParameters","ssm:GetParameter"],"Resource":"arn:aws:ssm:eu-north-1:12345678910:parameter/chaoslambda.config"}]}
支持的装饰符:
chaos_lambda当前支持以下装饰符:
- @注入延迟-在aws lambda执行中添加延迟
- @注入异常-在aws lambda执行期间引发异常
- @注入状态代码-强制aws lambda返回特定的http错误代码
以及以下课程:
- sessionwithdelay启用对请求库进行子分类并调用具有延迟的依赖项