AWS Lambda

Lambda Function

Questions:

  • what type of code can I run as a Lambda function?
  • How does AWS Lambda execute my code?
  • How does AWS Lambda know the amount of memory and CPU requirements needed to run my Lambda code?

A Lambda function consists of

  • code and any associated dependencies.

  • configuration information associated with it

  • Configuration includes:

    • Compute resources that you need
    • Maximum execution time (timeout)
    • IAM role (execution role)
    • Handler name
  • Invocation Type:

    • synchronous and asynchronous invocation of a Lambda function

    • You can control the invocation type only when you invoke a Lambda function (referred to as on-demand invocation). The following examples illustrate on-demand invocations:

      • Your custom application invokes a Lambda function.
      • You manually invoke a Lambda function (for example, using the AWS CLI) for testing purposes.
    • However, when you are using AWS services as event sources, the invocation type is predetermined for each of these services. For example, Amazon S3 always invokes a Lambda function asynchronously and Amazon Cognito always invokes a Lambda function synchronously.

    • Lambda console use RequestResponse invocation type (sync). Another type is event invocation type (async).

Asynchronous invocation – The Lambda function is executed and if the function fails (for reasons such as timeout, code error or out of memory), AWS Lambda tries to execute the function up to three times.
Synchronous invocation – The Lambda function is executed once, and errors are returned to the caller. If the Lambda function fails, AWS Lambda does not try to execute the function again.

  • Container Model
    • When a Lambda function is invoked, AWS Lambda launches a container (that is, an execution environment) based on the configuration settings you provided.
    • After a Lambda function is executed, AWS Lambda maintains the container for some time in anticipation of another Lambda function invocation.
      • Any declarations in your Lambda function code (outside the handler
        code, see [Programming Model] remains initialized, providing additional optimization when the function is invoked again.
      • Each container provides some disk space in the /tmp
        directory. The directory content remains when the container is frozen
      • Background processes or callbacks initiated by your Lambda function that did not complete when the function ended resume if AWS Lambda chooses to reuse the container. You should make sure any background processes or callbacks (in case of Node.js) in your code are complete before the code exits.
  • When you write your Lambda function code, do not assume that AWS Lambda always reuses the container because AWS Lambda may choose not to reuse the container.

Event Source Mapping

The configuration is referred to as event source mapping, which maps an event source to a Lambda function. It enables automatic invocation of your Lambda function when events occur.

An event source can be:

  • AWS service: Where you maintain the event source mapping and how the Lambda function is invoked depends on whether or not you're using a stream-based event source.
  • Custom Application

Question:

  • where do I keep the event mapping information?
  • Do I keep it within the event source or within AWS Lambda?

Event Source Mapping for AWS Services

  • Except for the stream-based AWS services (Amazon Kinesis Streams and DynamoDB streams), other supported AWS services publish events and can also invoke your Lambda function (referred to as the push model).
  • you need to grant the event source the necessary permissions using a resource-based policy (referred to as the Lambda function policy).

Event Source Mapping for AWS Stream-based Services

  • The Amazon Kinesis Streams and DynamoDB streams are the stream-based services that you can preconfigure to with AWS Lambda. After you do the necessary event source mapping, AWS Lambda polls the streams and invokes your Lambda function.
  • AWS Lambda needs your permission to poll the stream and read records. You grant these permissions via the execution role, using the permissions policy associated with role that you specify when you create your Lambda function.

Event Source Mapping for Custom Applications

  • In this case, there is no preconfiguration required—you don't have to set up an event source mapping. Instead, the event source uses the AWS Lambda Invoke
    API.

Building and Managing AWS Lambda-Based Applications

Question:
Authoring code for your Lambda function – What languages are supported? Is there a programming model that I need to follow? How do I package my code and dependencies for uploading to AWS Lambda? What tools are available?

Uploading code and creating Lambda functions – How do I upload my code package to AWS Lambda? How do I tell AWS Lambda where to begin executing my code? How do I specify compute requirements like memory and timeout?

Monitoring and troubleshooting – For my Lambda function that is in production, what metrics are available? If there are any failures, how do I get logs or troubleshoot issues?

There is a pattern to writing Lambda function code. For example,

  • how you write the handler method of your Lambda function
  • how you pass events to the handler,
  • what statements you can use in your code to generate logs in CloudWatch Logs,
  • how to interact with AWS Lambda runtime and obtain information such as the time remaining before timeout, and
  • how to handle exceptions.
  • Creating a Deployment Package
  • Uploading a Deployment Package
  • Testing a Lambda Function
  • Using AWS CloudFormation

Programming Model

Handler

def handler_name(event, context): 
    ...
    return some_value
  • Rules about return value:
    Optionally, the handler can return a value. What happens to the returned value depends on the invocation type you use when invoking the Lambda function:
    • If you use the RequestResponse invocation type (synchronous execution), AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON). For example, AWS Lambda console uses the RequestResponse invocation type, so when you invoke the function using the console, the console will display the returned value.
    • If the handler does not return anything, AWS Lambda returns null.
    • If you use the Event invocation type (asynchronous execution), the value is discarded.
    • Note: return is different from log (via print, or Logger module)
aws lambda create-function \\
--region us-west-2 \\
--function-name HelloPython \\
--zip-file fileb://deployment-package.zip \\
--role arn:aws:iam::account-id:role/lambda_basic_execution  \\
--handler hello_python.my_handler \\
--runtime python2.7 \\
--timeout 15 \\
--memory-size 512

Note:

  • function-name is just name for Lambda function (for example, use it as display name in Lambda console), no need to be same as the actual python script (e.g. HelloPython vs hello_python.py)
  • deployment package name (zip-file) also has no relation with function-name or python script name or handler name (e.g. deployment-package.zip vs hello_python.py vs HelloPython vs my_handler).

Context Object

  • The handler code in this example simply prints some of the runtime information. Each print statement creates a log entry in CloudWatch. If you invoke the function using the Lambda console, the console displays the logs.
from __future__ import print_function

import time
def get_my_log_stream(event, context):       
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:",context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    time.sleep(1) 
    print("Time remaining (MS):", context.get_remaining_time_in_millis())
Logging

Log is written into CloudWatch

The following Python statements generate log entries:

  • print statements.
  • Logger functions in the logging module (for example, logging.Logger.info
    andlogging.Logger.error).
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def my_logging_handler(event, context):
    logger.info('got event{}'.format(event))
    logger.error('something went wrong')
    return 'Hello World!'  

Exception handling

Creating a Deployment Package (Python)

  • Simple scenario – If your custom code requires only the AWS SDK library, then you can use the inline editor in the AWS Lambda console.
  • Advanced scenario – If you are writing code that uses other resources, such as a graphics library for image processing, or you want to use the AWS CLI instead of the console, you need to first create the Lambda function deployment package, and then use the console or the CLI to upload the package.

Versioning and Aliases

Aliases enable you to abstract the process of promoting new Lambda function versions into production from the mapping of the Lambda function version and its event source.

For example, suppose Amazon S3 is the event source that invokes your Lambda function when new objects are created in a bucket. When Amazon S3 is your event source, you store the event source mapping information in the bucket notification configuration. In the configuration you can identify the Lambda function ARN that Amazon S3 can invoke, but, in this case, each time you publish a new version of your Lambda function you need to update the notification configuration so that Amazon S3 invokes the correct version. Instead of specifying the function ARN, you can specify an alias ARN in the notification configuration (for example, PROD alias ARN). As you promote new versions of your Lambda function into production, you only need to update the PROD alias to point to the latest stable version, and you don't need to update the notification configuration in Amazon S3.

The same applies when you need to roll back to a previous version of your Lambda function. In this scenario, you just update the PROD alias to point to a different function version, and there is no need to update event source mappings.

Versioning

When you create a Lambda function, there is only one version. It is the $LATEST
version.

There are two ARNs associated with this initial version:

  • Qualified ARN – The function ARN with the version suffix.
arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST
  • Unqualified ARN. You can use this ARN in all relevant operations however you cannot use it to create an alias. The unqualified ARN has its own resource policies.
arn:aws:lambda:aws-region:acct-id:function:helloworld

You can use either the qualified or unqualified ARN in your event source mapping to invoke this $LATEST version.

The following is an example response of a CreateFunction API call:

{
    "CodeSize": 287,
    "Description": "test function.",
    "FunctionArn": "arn:aws:lambda:aws-region:acct-id:function:helloworld",
    "FunctionName": "helloworld",
    "Handler": "helloworld.handler",
    "LastModified": "2015-07-16T00:34:31.322+0000",
    "MemorySize": 128,
    "Role": "arn:aws:iam::acct-id:role/lambda_basic_execution",
    "Runtime": "nodejs4.3",
    "Timeout": 3,
    "CodeSHA256": "OjRFuuHKizEE8tHFIMsI+iHR6BPAfJ5S0rW31Mh6jKg=",
    "Version": "$LATEST" 
}

You can publish a version using any of the following methods:

  • Publish a version explicitly – Use the PublishVersion API to explicitly publish a version.
  • Publish a version at the time you create or update a Lambda function – Use the CreateFunction or UpdateFunctionCode requests to also publish a version by adding the optional publish parameter in the request:

Lambda-S3 tutorial

http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html
In this section, you do the following:

  • Create a Lambda function deployment package using the sample code provided.
  • Create an IAM role (execution role). At the time you upload the deployment package, you need to specify an IAM role (execution role) that Lambda can assume to execute the function on your behalf.
  • Create the Lambda function by uploading the deployment package, and then test it by invoking it manually using sample Amazon S3 event data.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,529评论 5 475
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,015评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,409评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,385评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,387评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,466评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,880评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,528评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,727评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,528评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,602评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,302评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,873评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,890评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,132评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,777评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,310评论 2 342

推荐阅读更多精彩内容