|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +from operator import contains |
| 4 | + |
| 5 | +import boto3 |
| 6 | +import json |
| 7 | +import time |
| 8 | +import os |
| 9 | +import uuid |
| 10 | +from botocore.exceptions import ClientError |
| 11 | + |
| 12 | +def parse_args(): |
| 13 | + parser = argparse.ArgumentParser(description='Deploy a function as AWS Lambda multiple times and benchmark') |
| 14 | + parser.add_argument('--path', required=True, help='Path to the function.zip file') |
| 15 | + parser.add_argument('--count', type=int, default=10, help='Number of functions to deploy (default: 10)') |
| 16 | + parser.add_argument('--function-name', default='test-function', help='Base name for the Lambda functions') |
| 17 | + parser.add_argument('--role-arn', required=True, help='ARN of the IAM role for Lambda execution') |
| 18 | + parser.add_argument('--region', default='us-east-1', help='AWS region (default: us-east-1)') |
| 19 | + parser.add_argument('--handler', default='SimpleLambda.lambda_handler', help='Lambda function handler') |
| 20 | + parser.add_argument('--runtime', default='python3.13', help='Lambda runtime (default: python3.13)') |
| 21 | + parser.add_argument('--environment', help='Environment') |
| 22 | + parser.add_argument('--layer', help="ARN of layer to include") |
| 23 | + return parser.parse_args() |
| 24 | + |
| 25 | +def delete_lambda_function(lambda_client, function_name): |
| 26 | + try: |
| 27 | + lambda_client.delete_function(FunctionName=function_name) |
| 28 | + print(f"Deleted Lambda function: {function_name}") |
| 29 | + except ClientError as e: |
| 30 | + if e.response['Error']['Code'] == 'ResourceNotFoundException': |
| 31 | + print(f"Lambda function not found: {function_name}") |
| 32 | + else: |
| 33 | + raise |
| 34 | + |
| 35 | +def create_lambda_function(lambda_client, function_name, environment, zip_path, role_arn, handler, runtime, layer): |
| 36 | + try: |
| 37 | + with open(zip_path, 'rb') as zip_file: |
| 38 | + zip_content = zip_file.read() |
| 39 | + |
| 40 | + response = lambda_client.create_function( |
| 41 | + FunctionName=function_name, |
| 42 | + Environment={ |
| 43 | + 'Variables': environment, |
| 44 | + }, |
| 45 | + Runtime=runtime, |
| 46 | + Role=role_arn, |
| 47 | + Handler=handler, |
| 48 | + Code={'ZipFile': zip_content}, |
| 49 | + Timeout=10, |
| 50 | + MemorySize=128, |
| 51 | + Layers=[layer] if layer else [], |
| 52 | + ) |
| 53 | + print(f"Created Lambda function: {function_name}") |
| 54 | + # Wait for function to be fully initialized |
| 55 | + time.sleep(5) |
| 56 | + return response['FunctionArn'] |
| 57 | + except ClientError as e: |
| 58 | + print(f"Error creating Lambda function {function_name}: {e}") |
| 59 | + return None |
| 60 | + |
| 61 | +def invoke_lambda_function(lambda_client, function_name, payload): |
| 62 | + try: |
| 63 | + start_time = time.time() |
| 64 | + response = lambda_client.invoke( |
| 65 | + FunctionName=function_name, |
| 66 | + InvocationType='RequestResponse', |
| 67 | + LogType='Tail', |
| 68 | + Payload=json.dumps(payload) |
| 69 | + ) |
| 70 | + duration = (time.time() - start_time) * 1000 # Convert to milliseconds |
| 71 | + |
| 72 | + # Get the Lambda execution duration from the response headers |
| 73 | + response_payload = json.loads(response['Payload'].read().decode('utf-8')) |
| 74 | + status_code = response['StatusCode'] |
| 75 | + execution_log = None |
| 76 | + if 'LogResult' in response: |
| 77 | + import base64 |
| 78 | + execution_log = base64.b64decode(response['LogResult']).decode('utf-8') |
| 79 | + |
| 80 | + # Try to extract the actual Lambda execution duration from logs |
| 81 | + lambda_init_duration = None |
| 82 | + if execution_log: |
| 83 | + for line in execution_log.split('\n'): |
| 84 | + if 'Init Duration:' in line: |
| 85 | + if 'Extension.Crash' in line: |
| 86 | + print(f"Exception crashed, full execution log: {execution_log}") |
| 87 | + raise Exception("Lambda extension has crashed") |
| 88 | + try: |
| 89 | + duration_part = line.split('Init Duration:')[1].split('ms')[0].strip() |
| 90 | + lambda_init_duration = float(duration_part) |
| 91 | + break |
| 92 | + except (IndexError, ValueError): |
| 93 | + pass |
| 94 | + if not lambda_init_duration: |
| 95 | + raise Exception("Could not extract the actual Lambda init duration from logs") |
| 96 | + |
| 97 | + print(f"Invoked {function_name}:") |
| 98 | + print(f" HTTP Status: {status_code}") |
| 99 | + print(f" Client-side duration: {duration:.2f} ms") |
| 100 | + |
| 101 | + if lambda_init_duration: |
| 102 | + print(f" Lambda-reported init duration: {lambda_init_duration:.2f} ms") |
| 103 | + |
| 104 | + return { |
| 105 | + 'function_name': function_name, |
| 106 | + 'status_code': status_code, |
| 107 | + 'client_duration_ms': duration, |
| 108 | + 'init_duration_ms': lambda_init_duration, |
| 109 | + 'response': response_payload |
| 110 | + } |
| 111 | + except ClientError as e: |
| 112 | + print(f"Error invoking Lambda function {function_name}: {e}") |
| 113 | + return None |
| 114 | + |
| 115 | +def main(): |
| 116 | + args = parse_args() |
| 117 | + |
| 118 | + environment = {} |
| 119 | + if args.environment: |
| 120 | + for val in args.environment.split(','): |
| 121 | + key, value = val.split('=') |
| 122 | + environment[key] = value |
| 123 | + |
| 124 | + # Validate the ZIP file exists |
| 125 | + if not os.path.isfile(args.path): |
| 126 | + print(f"Error: ZIP file not found at {args.path}") |
| 127 | + return |
| 128 | + |
| 129 | + # Create AWS clients |
| 130 | + lambda_client = boto3.client('lambda', region_name=args.region) |
| 131 | + |
| 132 | + # Deploy multiple Lambda functions |
| 133 | + functions = [] |
| 134 | + results = [] |
| 135 | + |
| 136 | + print(f"Deploying {args.count} Lambda functions...") |
| 137 | + for i in range(1, args.count + 1): |
| 138 | + function_name = f"{args.function_name}-{i}" |
| 139 | + # Try to delete it first |
| 140 | + delete_lambda_function(lambda_client, function_name) |
| 141 | + function_arn = create_lambda_function( |
| 142 | + lambda_client, |
| 143 | + function_name, |
| 144 | + environment, |
| 145 | + args.path, |
| 146 | + args.role_arn, |
| 147 | + args.handler, |
| 148 | + args.runtime, |
| 149 | + args.layer, |
| 150 | + ) |
| 151 | + if function_arn: |
| 152 | + functions.append(function_name) |
| 153 | + |
| 154 | + print(f"\nSuccessfully deployed {len(functions)} Lambda functions") |
| 155 | + |
| 156 | + # Invoke each function with a simple payload |
| 157 | + test_payload = { |
| 158 | + 'operation': "list_buckets", |
| 159 | + 'payload': { |
| 160 | + 'dog': "boxer", |
| 161 | + 'cat': "siamese", |
| 162 | + 'timestamp': int(time.time()), |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + print("\nInvoking each function and recording durations...") |
| 167 | + for function_name in functions: |
| 168 | + result = invoke_lambda_function(lambda_client, function_name, test_payload) |
| 169 | + if result: |
| 170 | + results.append(result) |
| 171 | + |
| 172 | + # Write results to file |
| 173 | + output_file = 'lambda_benchmark_results.json' |
| 174 | + with open(output_file, 'w') as f: |
| 175 | + json.dump(results, f, indent=2) |
| 176 | + |
| 177 | + print(f"\nResults have been saved to {output_file}") |
| 178 | + |
| 179 | + # Print summary |
| 180 | + print(f"\nSummary of lambda init durations (cold start) for {args.function_name}:") |
| 181 | + |
| 182 | + sorted_results = sorted(results, key=lambda x: x['init_duration_ms']) |
| 183 | + sorted_durations = list(map(lambda x: str(x['init_duration_ms']), sorted_results)) |
| 184 | + print(f"Durations: {", ".join(sorted_durations)}") |
| 185 | + |
| 186 | +if __name__ == "__main__": |
| 187 | + main() |
0 commit comments