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

打印 上一主题 下一主题

主题 1016|帖子 1016|积分 3058

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的环境中。



3. SAM程序结构


  • 开始使用SAM

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

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

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



    • 进行实际代码的实验

      • 实验环境
        这里照旧使用非常给力的工具CloudShell。

      • 构建代码

        • 创建代码的父路径
          1. mkdir demo-sam
          2. cd demo-sam
          复制代码
        • 使用sam生成股票实例代码(这个代码是sam自带的)

          之后进行一些runtime的相干设定。

          到这里,代码就会被生成出来,而且cloudformation的template文件都是yaml格式的。



    • 将cloudshell环境中的代码通过S3取到本地

      • 创建传输文件的S3 bucket
        由于cloudshell不是很轻易和本地传输文件,所以使用S3 bucket。

      • 将SAM代码打包,copy到S3 bucket
        1. tar zcvf demo-sam.tar.gz demo-sam/
        2. aws s3 cp demo-sam.tar.gz s3://finlay-cloudshell/
        复制代码

      • 将SAM init生成的实例程序代码,下载到本地

        本地文件夹如下所示。

      • 将SAM init生成的实例程序代码使用vscode打开(这里单纯的可以更加轻易编辑代码)

        • template文件
          1. AWSTemplateFormatVersion: '2010-09-09'
          2. Transform: AWS::Serverless-2016-10-31
          3. Description: |
          4.   demo-sam
          5.   Sample SAM Template for demo-sam
          6. Resources:
          7.   StockTradingStateMachine:
          8.     Type: AWS::Serverless::StateMachine # More info about State Machine Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-statemachine.html
          9.     Properties:
          10.       DefinitionSubstitutions:
          11.         StockCheckerFunctionArn: !GetAtt StockCheckerFunction.Arn
          12.         StockSellerFunctionArn: !GetAtt StockSellerFunction.Arn
          13.         StockBuyerFunctionArn: !GetAtt StockBuyerFunction.Arn
          14.         DDBPutItem: !Sub arn:${AWS::Partition}:states:::dynamodb:putItem
          15.         DDBTable: !Ref TransactionTable
          16.       Events:
          17.         HourlyTradingSchedule:
          18.           Type: Schedule # More info about Schedule Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-statemachine-schedule.html
          19.           Properties:
          20.             Description: Schedule to run the stock trading state machine every hour
          21.             Enabled: false # This schedule is disabled by default to avoid incurring charges.
          22.             Schedule: rate(1 hour)
          23.       Policies:
          24.         # Find out more about SAM policy templates: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-templates.html
          25.         - LambdaInvokePolicy:
          26.             FunctionName: !Ref StockCheckerFunction
          27.         - LambdaInvokePolicy:
          28.             FunctionName: !Ref StockSellerFunction
          29.         - LambdaInvokePolicy:
          30.             FunctionName: !Ref StockBuyerFunction
          31.         - DynamoDBWritePolicy:
          32.             TableName: !Ref TransactionTable
          33.       DefinitionUri: statemachine/stock_trader.asl.json
          34.   StockCheckerFunction:
          35.     Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html
          36.     Properties:
          37.       CodeUri: functions/stock_checker/
          38.       Handler: app.lambda_handler
          39.       Runtime: python3.9
          40.       Architectures:
          41.         - x86_64
          42.   StockSellerFunction:
          43.     Type: AWS::Serverless::Function
          44.     Properties:
          45.       CodeUri: functions/stock_seller/
          46.       Handler: app.lambda_handler
          47.       Runtime: python3.9
          48.       Architectures:
          49.         - x86_64
          50.   StockBuyerFunction:
          51.     Type: AWS::Serverless::Function
          52.     Properties:
          53.       CodeUri: functions/stock_buyer/
          54.       Handler: app.lambda_handler
          55.       Runtime: python3.9
          56.       Architectures:
          57.         - x86_64
          58.   TransactionTable:
          59.     Type: AWS::Serverless::SimpleTable # More info about SimpleTable Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-simpletable.html
          60.     Properties:
          61.       PrimaryKey:
          62.         Name: Id
          63.         Type: String
          64.       ProvisionedThroughput:
          65.         ReadCapacityUnits: 1
          66.         WriteCapacityUnits: 1
          67.   ApplicationResourceGroup:
          68.     Type: AWS::ResourceGroups::Group
          69.     Properties:
          70.       Name: !Sub ApplicationInsights-SAM-${AWS::StackName}
          71.       ResourceQuery:
          72.         Type: CLOUDFORMATION_STACK_1_0
          73.   ApplicationInsightsMonitoring:
          74.     Type: AWS::ApplicationInsights::Application
          75.     Properties:
          76.       ResourceGroupName: !Ref ApplicationResourceGroup
          77.       AutoConfigurationEnabled: 'true'
          78. Outputs:
          79.   # StockTradingStateMachineHourlyTradingSchedule is an implicit Schedule event rule created out of Events key under Serverless::StateMachine
          80.   # Find out more about other implicit resources you can reference within SAM
          81.   # https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-generated-resources.html
          82.   StockTradingStateMachineArn:
          83.     Description: Stock Trading State machine ARN
          84.     Value: !Ref StockTradingStateMachine
          85.   StockTradingStateMachineRoleArn:
          86.     Description: IAM Role created for Stock Trading State machine based on the
          87.       specified SAM Policy Templates
          88.     Value: !GetAtt StockTradingStateMachineRole.Arn
          复制代码
          使用vscode打开template文件,可以看到AWS service的图形化结构。

        • stock_checker文件 随机产生stock的价格
          1. from random import randint
          2. def lambda_handler(event, context):
          3.     """Sample Lambda function which mocks the operation of checking the current price
          4.     of a stock.
          5.     For demonstration purposes this Lambda function simply returns
          6.     a random integer between 0 and 100 as the stock price.
          7.     Parameters
          8.     ----------
          9.     event: dict, required
          10.         Input event to the Lambda function
          11.     context: object, required
          12.         Lambda Context runtime methods and attributes
          13.     Returns
          14.     ------
          15.         dict: Object containing the current price of the stock
          16.     """
          17.     # Check current price of the stock
          18.     stock_price = randint(
          19.         0, 100
          20.     )  # Current stock price is mocked as a random integer between 0 and 100
          21.     return {"stock_price": stock_price}
          复制代码
        • stock_buyer文件 假如价格低,选择买进
          1. from datetime import datetime
          2. from random import randint
          3. from uuid import uuid4
          4. def lambda_handler(event, context):
          5.     """Sample Lambda function which mocks the operation of buying a random number
          6.     of shares for a stock.
          7.     For demonstration purposes, this Lambda function does not actually perform any
          8.     actual transactions. It simply returns a mocked result.
          9.     Parameters
          10.     ----------
          11.     event: dict, required
          12.         Input event to the Lambda function
          13.     context: object, required
          14.         Lambda Context runtime methods and attributes
          15.     Returns
          16.     ------
          17.         dict: Object containing details of the stock buying transaction
          18.     """
          19.     # Get the price of the stock provided as input
          20.     stock_price = event["stock_price"]
          21.     # Mocked result of a stock buying transaction
          22.     transaction_result = {
          23.         "id": str(uuid4()),  # Unique ID for the transaction
          24.         "price": str(stock_price),  # Price of each share
          25.         "type": "buy",  # Type of transaction (buy/sell)
          26.         "qty": str(
          27.             randint(1, 10)
          28.         ),  # Number of shares bought/sold (We are mocking this as a random integer between 1 and 10)
          29.         "timestamp": datetime.now().isoformat(),  # Timestamp of the when the transaction was completed
          30.     }
          31.     return transaction_result
          复制代码
        • stock_seller文件 假如价格高,选择抛出
          1. from datetime import datetime
          2. from random import randint
          3. from uuid import uuid4
          4. def lambda_handler(event, context):
          5.     """Sample Lambda function which mocks the operation of selling a random number
          6.     of shares for a stock.
          7.     For demonstration purposes, this Lambda function does not actually perform any
          8.     actual transactions. It simply returns a mocked result.
          9.     Parameters
          10.     ----------
          11.     event: dict, required
          12.         Input event to the Lambda function
          13.     context: object, required
          14.         Lambda Context runtime methods and attributes
          15.     Returns
          16.     ------
          17.         dict: Object containing details of the stock selling transaction
          18.     """
          19.     # Get the price of the stock provided as input
          20.     stock_price = event["stock_price"]
          21.     # Mocked result of a stock selling transaction
          22.     transaction_result = {
          23.         "id": str(uuid4()),  # Unique ID for the transaction
          24.         "price": str(stock_price),  # Price of each share
          25.         "type": "sell",  # Type of transaction (buy/sell)
          26.         "qty": str(
          27.             randint(1, 10)
          28.         ),  # Number of shares bought/sold (We are mocking this as a random integer between 1 and 10)
          29.         "timestamp": datetime.now().isoformat(),  # Timestamp of the when the transaction was completed
          30.     }
          31.     return transaction_result
          复制代码
        • step functions文件 将上面的lambda函数穿插起来,形成一个工作流程编排
          1. {
          2.     "Comment": "A state machine that does mock stock trading.",
          3.     "StartAt": "Check Stock Value",
          4.     "States": {
          5.         "Check Stock Value": {
          6.             "Type": "Task",
          7.             "Resource": "${StockCheckerFunctionArn}",
          8.             "Retry": [
          9.                 {
          10.                     "ErrorEquals": [
          11.                         "States.TaskFailed"
          12.                     ],
          13.                     "IntervalSeconds": 15,
          14.                     "MaxAttempts": 5,
          15.                     "BackoffRate": 1.5
          16.                 }
          17.             ],
          18.             "Next": "Buy or Sell?"
          19.         },
          20.         "Buy or Sell?": {
          21.             "Type": "Choice",
          22.             "Choices": [
          23.                 {
          24.                     "Variable": "$.stock_price",
          25.                     "NumericLessThanEquals": 50,
          26.                     "Next": "Buy Stock"
          27.                 }
          28.             ],
          29.             "Default": "Sell Stock"
          30.         },
          31.         "Sell Stock": {
          32.             "Type": "Task",
          33.             "Resource": "${StockSellerFunctionArn}",
          34.             "Retry": [
          35.                 {
          36.                     "ErrorEquals": [
          37.                         "States.TaskFailed"
          38.                     ],
          39.                     "IntervalSeconds": 2,
          40.                     "MaxAttempts": 3,
          41.                     "BackoffRate": 1
          42.                 }
          43.             ],
          44.             "Next": "Record Transaction"
          45.         },
          46.         "Buy Stock": {
          47.             "Type": "Task",
          48.             "Resource": "${StockBuyerFunctionArn}",
          49.             "Retry": [
          50.                 {
          51.                     "ErrorEquals": [
          52.                         "States.TaskFailed"
          53.                     ],
          54.                     "IntervalSeconds": 2,
          55.                     "MaxAttempts": 3,
          56.                     "BackoffRate": 1
          57.                 }
          58.             ],
          59.             "Next": "Record Transaction"
          60.         },
          61.         "Record Transaction": {
          62.             "Type": "Task",
          63.             "Resource": "${DDBPutItem}",
          64.             "Parameters": {
          65.                 "TableName": "${DDBTable}",
          66.                 "Item": {
          67.                     "Id": {
          68.                         "S.$": "$.id"
          69.                     },
          70.                     "Type": {
          71.                         "S.$": "$.type"
          72.                     },
          73.                     "Price": {
          74.                         "N.$": "$.price"
          75.                     },
          76.                     "Quantity": {
          77.                         "N.$": "$.qty"
          78.                     },
          79.                     "Timestamp": {
          80.                         "S.$": "$.timestamp"
          81.                     }
          82.                 }
          83.             },
          84.             "Retry": [
          85.                 {
          86.                     "ErrorEquals": [
          87.                         "States.TaskFailed"
          88.                     ],
          89.                     "IntervalSeconds": 20,
          90.                     "MaxAttempts": 5,
          91.                     "BackoffRate": 10
          92.                 }
          93.             ],
          94.             "End": true
          95.         }
          96.     }
          97. }
          复制代码
        查抄vscode的sam预览功能


    • 回到cloudshell执行sam build和sam deploy摆设到AWS
      1. sam build
      2. sam deploy
      复制代码
      可以看到,本质上这个sam application照旧使用Cloudformation进行摆设。

      检察Cloudformation进一步验证了想定结果。


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


  • 打开默认的aws eventbridge的规则设置
    默认是禁用的,编辑这里,打开禁用。

  • 检察执行结果
    可以看出,已经成功执行一次

    股票价格为2,执行了buy stock lambda


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

篮之新喜

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表