Injecting Chaos to AWS Lambda functions using Lambda Layers

Adrian Hornsby
Jan 4, 2019 · 10 min read
Image for post
Image for post

“As far as the laws of mathematics refer to reality, they are not certain, and as far as they are certain, they do not refer to reality.” -Albert Einstein


UPDATE — October 2019



Why latency injection?

“Failures are a given, and everything will eventually fail over time.”


Before we get started

{ 
"delay": 300,
"isEnabled": true
}
Image for post
Image for post
from ssm_cache import SSMParameter
param = SSMParameter('chaoslambda.config')
def get_config():
param = SSMParameter('chaoslambda.config')
try:
value = json.loads(param.value)
delay = value["delay"]
isEnabled = value["isEnabled"]
if isEnabled and delay >= 0:
return delay
elif isEnabled and delay <= 0:
return -1
else:
return 0
except InvalidParameterError as e:
print("{} is not SSM".format(e))
return 0
except KeyError as e:
print("{} is not a valid Key in SSM configuration".format(e))
return 0
{
"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:<ACCOUNT_ID>:parameter/chaoslambda.config"
}
]
}
import os
region = os.environ["AWS_REGION"]
tablename = os.environ["tablename"]
dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table(tablename)

Latency injections using Python.

1 — Using a Python decorator

from __future__ import division, unicode_literals
import time
import random
def delayit(func):
def latency(*args, **kw):
delay = get_config()
start = time.time()
# if delay exist and bigger than 0, delaying with that value
if delay > 0:
time.sleep(delay / 1000.0)
# if delay is negative make random delays
elif delay < 0:
# add latency approx 50% of the time
if random.random() > 0.5:
# random sleep time between 1 and 10 seconds
time.sleep(random.randint(1, 10))
result = func(*args, **kw)
end = time.time()
print('Added {1:.2f}ms to {0:s}'.format(
func.__name__,
(end - start) * 1000
))
return result
return latency
from chaos_lib import delayit@delayit
def dummy():
pass
def lambda_handler(event, context):
dummy()
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}

2 — Subclassing the requests library

class SessionWithDelay(requests.Session):
def __init__(self, delay=None, *args, **kwargs):
super(SessionWithDelay, self).__init__(*args, **kwargs)
self.delay = delay
def request(self, method, url, **kwargs):
print('Added {1.2f}ms of delay to {0:s}'.format(
method, self.delay))
time.sleep(self.delay / 1000.0)
return super(SessionWithDelay, self).request(method, url, **kwargs)
from chaos_lib import SessionWithDelaydef dummy():
session = SessionWithDelay(delay=300)
session.get('https://stackoverflow.com/')
pass
def lambda_handler(event, context):
dummy()
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}

Building the ZIP package for the Lambda Layer

$ git clone git@github.com:adhorn/LatencyInjectionLayer.git
$ git checkout tags/v0.1-alpha
$ docker run -v $PWD:/var/task -it lambci/lambda:build-python3.6 /bin/bash -c "pip install -r python/requirements.txt -t ./python/.vendor"
Image for post
Image for post
$ zip -r chaos_lib.zip ./python
Image for post
Image for post

Creating a Lambda Layer from the Chaos Library

Image for post
Image for post
Image for post
Image for post
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"ssm:DescribeParameters",
"logs:CreateLogGroup",
"logs:PutLogEvents"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameters",
"ssm:GetParameter"
],
"Resource": "arn:aws:ssm:eu-north-1:<YOURACCOUNTID>:parameter/chaoslambda.config"
}
]
}
from chaos_lib import delayit
from chaos_lib import SessionWithDelay

def dummy2():
session = SessionWithDelay(delay=300)
session.get('https://stackoverflow.com/')
pass

@delayit

def dummy():
pass

def lambda_handler(event, context):
dummy()
dummy2()
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}
Image for post
Image for post
from chaos_lib import delayit
from chaos_lib import SessionWithDelay
Image for post
Image for post
Yes, I am on version 5 already :-)
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Wrapping up.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store