|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | + |
| 5 | +import boto3 |
| 6 | + |
| 7 | +# Initialize AWS Lambda client and logger |
| 8 | +lambda_client = boto3.client("lambda") |
| 9 | +logger = logging.getLogger() |
| 10 | +logger.setLevel(logging.INFO) |
| 11 | + |
| 12 | +# Get tag key and value from environment variables |
| 13 | +PREWARM_TAG_KEY = os.environ.get("PREWARM_TAG_KEY", "Prewarm") |
| 14 | +PREWARM_TAG_VALUE = os.environ.get("PREWARM_TAG_VALUE", "true") |
| 15 | + |
| 16 | + |
| 17 | +def get_prewarm_functions(): |
| 18 | + """ |
| 19 | + Fetch all Lambda functions and filter those with the specified tag key and value |
| 20 | + from environment variables. |
| 21 | +
|
| 22 | + Environment Variables: |
| 23 | + PREWARM_TAG_KEY: The tag key to check (e.g., "Project") |
| 24 | + PREWARM_TAG_VALUE: The expected value for the tag (e.g., "DemoProject") |
| 25 | +
|
| 26 | + Returns: |
| 27 | + list: A list of function names that require prewarming. |
| 28 | + """ |
| 29 | + try: |
| 30 | + |
| 31 | + logger.info( |
| 32 | + "Searching for functions with %s=%s", PREWARM_TAG_KEY, PREWARM_TAG_VALUE |
| 33 | + ) |
| 34 | + |
| 35 | + functions = [] |
| 36 | + next_marker = None # Marker for pagination |
| 37 | + |
| 38 | + # Iterate through all pages of Lambda functions |
| 39 | + while True: |
| 40 | + if next_marker: |
| 41 | + response = lambda_client.list_functions(Marker=next_marker) |
| 42 | + else: |
| 43 | + response = lambda_client.list_functions() |
| 44 | + |
| 45 | + # Check each function's tags to identify prewarm candidates |
| 46 | + for func in response["Functions"]: |
| 47 | + function_name = func["FunctionName"] |
| 48 | + function_arn = func["FunctionArn"] |
| 49 | + |
| 50 | + # Retrieve tags for the current function |
| 51 | + tags = lambda_client.list_tags(Resource=function_arn) |
| 52 | + |
| 53 | + # Check if the function has the specified tag and value |
| 54 | + if tags.get("Tags", {}).get(PREWARM_TAG_KEY) == PREWARM_TAG_VALUE: |
| 55 | + functions.append(function_name) |
| 56 | + logger.info( |
| 57 | + "Function %s matched criteria: %s=%s", |
| 58 | + function_name, |
| 59 | + PREWARM_TAG_KEY, |
| 60 | + PREWARM_TAG_VALUE, |
| 61 | + ) |
| 62 | + |
| 63 | + # Check if there are more pages |
| 64 | + next_marker = response.get("NextMarker") |
| 65 | + if not next_marker: |
| 66 | + break |
| 67 | + |
| 68 | + logger.info("Found %d functions to prewarm: %s", len(functions), functions) |
| 69 | + return functions |
| 70 | + |
| 71 | + except Exception as e: |
| 72 | + logger.error("Error while fetching functions: %s", e) |
| 73 | + raise |
| 74 | + |
| 75 | + |
| 76 | +def invoke_lambda(function_name): |
| 77 | + """ |
| 78 | + Trigger a specified Lambda function to keep it warm. |
| 79 | +
|
| 80 | + Args: |
| 81 | + function_name (str): The name of the Lambda function to prewarm. |
| 82 | + """ |
| 83 | + try: |
| 84 | + # Use Event invocation type to avoid blocking |
| 85 | + lambda_client.invoke( |
| 86 | + FunctionName=function_name, |
| 87 | + InvocationType="Event", # Asynchronous invocation to reduce latency |
| 88 | + Payload=json.dumps({"action": "PREWARM"}), # Send a custom prewarm signal |
| 89 | + ) |
| 90 | + logger.info("Successfully prewarmed %s", function_name) |
| 91 | + except Exception as e: |
| 92 | + logger.error("Failed to prewarm %s: %s", function_name, e) |
| 93 | + |
| 94 | + |
| 95 | +def lambda_handler(event, context): |
| 96 | + """ |
| 97 | + Entry point for the Lambda function. Retrieves the list of Lambda functions to prewarm |
| 98 | + and invokes them asynchronously. |
| 99 | +
|
| 100 | + Args: |
| 101 | + event (dict): AWS event data (not used in this implementation). |
| 102 | + context (object): AWS Lambda context object (not used in this implementation). |
| 103 | +
|
| 104 | + Returns: |
| 105 | + dict: A status object with the results of the prewarm operation. |
| 106 | + """ |
| 107 | + logger.info("Starting prewarmer...") |
| 108 | + try: |
| 109 | + # Step 1: Get the list of functions to prewarm |
| 110 | + prewarm_functions = get_prewarm_functions() |
| 111 | + |
| 112 | + # Step 2: Invoke each function asynchronously |
| 113 | + for function_name in prewarm_functions: |
| 114 | + invoke_lambda(function_name) |
| 115 | + |
| 116 | + logger.info("Prewarm process completed.") |
| 117 | + return {"status": "SUCCESS", "prewarmed_functions": prewarm_functions} |
| 118 | + except Exception as e: |
| 119 | + logger.error("Prewarmer encountered an error: %s", e) |
| 120 | + return {"status": "ERROR", "message": str(e)} |
0 commit comments