篮之新喜 发表于 2025-1-15 15:05:29

aws(学习条记第二十四课) 使用sam开辟step functions

aws(学习条记第二十四课)



[*] 使用sam开辟step functions
学习内容:



[*]生成sam的step functions实例程序
[*]什么是SAM amazon Serverless Application Model
[*]SAM程序结构
[*]SAM执行程序
1. 生成sam的step functions实例程序


[*]参照文档
这里参照AWS的官方文档SAM amazon Serverless Application Model
[*]什么是SAM amazon Serverless Application Model

[*]整体架构
SAM就是一个基于Cloudformation的应用程序框架,重要目的正如名字(Serverless Application Model),方便进行Serverless Application的开辟。
开辟的一般步调如下:

[*]开辟lambda等serverless application。
[*]利用step functions等serverless application。当然,此中可以调用lambda。
[*]之后利用上面的serverless application,进行Cloudformation的template定义。
[*]末了经过sam build和sam deploy摆设到AWS的环境中。
https://i-blog.csdnimg.cn/direct/e0dce68272cc4b2cb6837abf74967c33.png


3. SAM程序结构


[*]开始使用SAM

[*]这里使用SAM提供的实例程序进行训练

[*]HourlyTradingSchedule是一个AWS EventBridge的规则,这里定义了股票投资程序的调用周期。类似于linux的cron job。
[*]StockTradingStateMachine就是股票交易的StateMachine。
[*]股票交易的StateMachine里面包括三个lambda

[*]StockCheckerFunction这里随机产生股票的价格(进行简朴的股票市场的模仿)
[*]中心其实有一个choice state,进行判定。这里没有画出来
[*]之后根据判定,假如股票高过某个固定价格,那么进行StockBuyerFunction的调用
[*]假如股票高过某个固定价格,那么进行StockSellerFunction的调用
[*]末了,不管买照旧卖的操作,都进行TransactionTable的写入(使用DynamoDB记载交易)
https://i-blog.csdnimg.cn/direct/cc84136bf92f4c0f87de1ff17026d589.png


[*]进行实际代码的实验

[*]实验环境
这里照旧使用非常给力的工具CloudShell。
https://i-blog.csdnimg.cn/direct/b29984c6d43a4a00854b1073d76c8403.png
[*]构建代码

[*]创建代码的父路径mkdir demo-sam
cd demo-sam

[*]使用sam生成股票实例代码(这个代码是sam自带的)
https://i-blog.csdnimg.cn/direct/0f435a87535b4936b2529b67ba31eb62.png
之后进行一些runtime的相干设定。
https://i-blog.csdnimg.cn/direct/c33f3c5e27084857a95125e2a38ae594.png
到这里,代码就会被生成出来,而且cloudformation的template文件都是yaml格式的。
https://i-blog.csdnimg.cn/direct/9a34f777f5af49cd95cd0b944b56d30a.png


[*]将cloudshell环境中的代码通过S3取到本地

[*]创建传输文件的S3 bucket
由于cloudshell不是很轻易和本地传输文件,所以使用S3 bucket。
https://i-blog.csdnimg.cn/direct/a73ac09974734bc0b0c36a377c5dca94.png
[*]将SAM代码打包,copy到S3 buckettar zcvf demo-sam.tar.gz demo-sam/
aws s3 cp demo-sam.tar.gz s3://finlay-cloudshell/
https://i-blog.csdnimg.cn/direct/05d74f5ce83f410fad69b2a31e71ccdd.png
[*]将SAM init生成的实例程序代码,下载到本地
https://i-blog.csdnimg.cn/direct/cceb7b35353f4106b1439ea066e38044.png
本地文件夹如下所示。
https://i-blog.csdnimg.cn/direct/821bcc2bc9944b629e4ce5e579dd7851.png
[*]将SAM init生成的实例程序代码使用vscode打开(这里单纯的可以更加轻易编辑代码)

[*]template文件AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: |
demo-sam
Sample SAM Template for demo-sam

Resources:
StockTradingStateMachine:
    Type: AWS::Serverless::StateMachine # More info about State Machine Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-statemachine.html
    Properties:
      DefinitionSubstitutions:
      StockCheckerFunctionArn: !GetAtt StockCheckerFunction.Arn
      StockSellerFunctionArn: !GetAtt StockSellerFunction.Arn
      StockBuyerFunctionArn: !GetAtt StockBuyerFunction.Arn
      DDBPutItem: !Sub arn:${AWS::Partition}:states:::dynamodb:putItem
      DDBTable: !Ref TransactionTable
      Events:
      HourlyTradingSchedule:
          Type: Schedule # More info about Schedule Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-statemachine-schedule.html
          Properties:
            Description: Schedule to run the stock trading state machine every hour
            Enabled: false # This schedule is disabled by default to avoid incurring charges.
            Schedule: rate(1 hour)
      Policies:
      # Find out more about SAM policy templates: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-templates.html
      - LambdaInvokePolicy:
            FunctionName: !Ref StockCheckerFunction
      - LambdaInvokePolicy:
            FunctionName: !Ref StockSellerFunction
      - LambdaInvokePolicy:
            FunctionName: !Ref StockBuyerFunction
      - DynamoDBWritePolicy:
            TableName: !Ref TransactionTable
      DefinitionUri: statemachine/stock_trader.asl.json

StockCheckerFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html
    Properties:
      CodeUri: functions/stock_checker/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64

StockSellerFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/stock_seller/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64

StockBuyerFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/stock_buyer/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64

TransactionTable:
    Type: AWS::Serverless::SimpleTable # More info about SimpleTable Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-simpletable.html
    Properties:
      PrimaryKey:
      Name: Id
      Type: String
      ProvisionedThroughput:
      ReadCapacityUnits: 1
      WriteCapacityUnits: 1

ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name: !Sub ApplicationInsights-SAM-${AWS::StackName}
      ResourceQuery:
      Type: CLOUDFORMATION_STACK_1_0
ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName: !Ref ApplicationResourceGroup
      AutoConfigurationEnabled: 'true'
Outputs:
# StockTradingStateMachineHourlyTradingSchedule is an implicit Schedule event rule created out of Events key under Serverless::StateMachine
# Find out more about other implicit resources you can reference within SAM
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-generated-resources.html
StockTradingStateMachineArn:
    Description: Stock Trading State machine ARN
    Value: !Ref StockTradingStateMachine
StockTradingStateMachineRoleArn:
    Description: IAM Role created for Stock Trading State machine based on the
      specified SAM Policy Templates
    Value: !GetAtt StockTradingStateMachineRole.Arn
使用vscode打开template文件,可以看到AWS service的图形化结构。
https://i-blog.csdnimg.cn/direct/19ab52fa7c8040729a2d7d82ed205ea5.png
[*]stock_checker文件 随机产生stock的价格from random import randint


def lambda_handler(event, context):
    """Sample Lambda function which mocks the operation of checking the current price
    of a stock.

    For demonstration purposes this Lambda function simply returns
    a random integer between 0 and 100 as the stock price.

    Parameters
    ----------
    event: dict, required
      Input event to the Lambda function

    context: object, required
      Lambda Context runtime methods and attributes

    Returns
    ------
      dict: Object containing the current price of the stock
    """
    # Check current price of the stock
    stock_price = randint(
      0, 100
    )# Current stock price is mocked as a random integer between 0 and 100
    return {"stock_price": stock_price}

[*]stock_buyer文件 假如价格低,选择买进from datetime import datetime
from random import randint
from uuid import uuid4


def lambda_handler(event, context):
    """Sample Lambda function which mocks the operation of buying a random number
    of shares for a stock.

    For demonstration purposes, this Lambda function does not actually perform any
    actual transactions. It simply returns a mocked result.

    Parameters
    ----------
    event: dict, required
      Input event to the Lambda function

    context: object, required
      Lambda Context runtime methods and attributes

    Returns
    ------
      dict: Object containing details of the stock buying transaction
    """
    # Get the price of the stock provided as input
    stock_price = event["stock_price"]
    # Mocked result of a stock buying transaction
    transaction_result = {
      "id": str(uuid4()),# Unique ID for the transaction
      "price": str(stock_price),# Price of each share
      "type": "buy",# Type of transaction (buy/sell)
      "qty": str(
            randint(1, 10)
      ),# Number of shares bought/sold (We are mocking this as a random integer between 1 and 10)
      "timestamp": datetime.now().isoformat(),# Timestamp of the when the transaction was completed
    }
    return transaction_result

[*]stock_seller文件 假如价格高,选择抛出from datetime import datetime
from random import randint
from uuid import uuid4


def lambda_handler(event, context):
    """Sample Lambda function which mocks the operation of selling a random number
    of shares for a stock.

    For demonstration purposes, this Lambda function does not actually perform any
    actual transactions. It simply returns a mocked result.

    Parameters
    ----------
    event: dict, required
      Input event to the Lambda function

    context: object, required
      Lambda Context runtime methods and attributes

    Returns
    ------
      dict: Object containing details of the stock selling transaction
    """
    # Get the price of the stock provided as input
    stock_price = event["stock_price"]
    # Mocked result of a stock selling transaction
    transaction_result = {
      "id": str(uuid4()),# Unique ID for the transaction
      "price": str(stock_price),# Price of each share
      "type": "sell",# Type of transaction (buy/sell)
      "qty": str(
            randint(1, 10)
      ),# Number of shares bought/sold (We are mocking this as a random integer between 1 and 10)
      "timestamp": datetime.now().isoformat(),# Timestamp of the when the transaction was completed
    }
    return transaction_result

[*]step functions文件 将上面的lambda函数穿插起来,形成一个工作流程编排{
    "Comment": "A state machine that does mock stock trading.",
    "StartAt": "Check Stock Value",
    "States": {
      "Check Stock Value": {
            "Type": "Task",
            "Resource": "${StockCheckerFunctionArn}",
            "Retry": [
                {
                  "ErrorEquals": [
                        "States.TaskFailed"
                  ],
                  "IntervalSeconds": 15,
                  "MaxAttempts": 5,
                  "BackoffRate": 1.5
                }
            ],
            "Next": "Buy or Sell?"
      },
      "Buy or Sell?": {
            "Type": "Choice",
            "Choices": [
                {
                  "Variable": "$.stock_price",
                  "NumericLessThanEquals": 50,
                  "Next": "Buy Stock"
                }
            ],
            "Default": "Sell Stock"
      },
      "Sell Stock": {
            "Type": "Task",
            "Resource": "${StockSellerFunctionArn}",
            "Retry": [
                {
                  "ErrorEquals": [
                        "States.TaskFailed"
                  ],
                  "IntervalSeconds": 2,
                  "MaxAttempts": 3,
                  "BackoffRate": 1
                }
            ],
            "Next": "Record Transaction"
      },
      "Buy Stock": {
            "Type": "Task",
            "Resource": "${StockBuyerFunctionArn}",
            "Retry": [
                {
                  "ErrorEquals": [
                        "States.TaskFailed"
                  ],
                  "IntervalSeconds": 2,
                  "MaxAttempts": 3,
                  "BackoffRate": 1
                }
            ],
            "Next": "Record Transaction"
      },
      "Record Transaction": {
            "Type": "Task",
            "Resource": "${DDBPutItem}",
            "Parameters": {
                "TableName": "${DDBTable}",
                "Item": {
                  "Id": {
                        "S.$": "$.id"
                  },
                  "Type": {
                        "S.$": "$.type"
                  },
                  "Price": {
                        "N.$": "$.price"
                  },
                  "Quantity": {
                        "N.$": "$.qty"
                  },
                  "Timestamp": {
                        "S.$": "$.timestamp"
                  }
                }
            },
            "Retry": [
                {
                  "ErrorEquals": [
                        "States.TaskFailed"
                  ],
                  "IntervalSeconds": 20,
                  "MaxAttempts": 5,
                  "BackoffRate": 10
                }
            ],
            "End": true
      }
    }
}

查抄vscode的sam预览功能
https://i-blog.csdnimg.cn/direct/1d7e5c5bb81e4d1ab97e7727667a5ecb.png

[*]回到cloudshell执行sam build和sam deploy摆设到AWSsam build
sam deploy
可以看到,本质上这个sam application照旧使用Cloudformation进行摆设。
https://i-blog.csdnimg.cn/direct/53c2b08fcbe24037b7790ae7cb775d82.png
检察Cloudformation进一步验证了想定结果。https://i-blog.csdnimg.cn/direct/8234d2a8b7154e3a80d4b1f70a669a44.png

4. 执行sam的step functions实例程序


[*] 打开默认的aws eventbridge的规则设置
默认是禁用的,编辑这里,打开禁用。
https://i-blog.csdnimg.cn/direct/43f5c30539eb44f282bd90f1ad5826ed.png
[*] 检察执行结果
可以看出,已经成功执行一次
https://i-blog.csdnimg.cn/direct/bd1bdb4f318a48c7967f2508f275565a.png
股票价格为2,执行了buy stock lambda
https://i-blog.csdnimg.cn/direct/6a2a094e18284ecbbc0d5e265b115ba3.png

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: aws(学习条记第二十四课) 使用sam开辟step functions