Upgrade to Pro — share decks privately, control downloads, hide ads and more …

try! Serverless App with Swift

try! Serverless App with Swift

Yu Tawata

March 19, 2019

More Decks by Yu Tawata

Other Decks in Technology


  1. Why Serverless App with Swift? • Custom Runtime for AWS

    Lambda • Can execute programs written in any programming languages. • Swift 5 • Easier to bridge to python, compared with Swift4
  2. What's AWS Lambda Custom Runtime? • bootstrap • execute programs

    using request params and return the results as responses #!/bin/sh set -euo pipefail # Initialization - load function handler source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).sh" # Processing while true do HEADERS="$(mktemp)" # Get an event EVENT_DATA=$(curl -sS -LD "$HEADERS" -X GET "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next") REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id "$HEADERS" | tr -d '[:space:]' | cut -d: -f2) # Execute the handler function from the script RESPONSE=$($(echo "$_HANDLER" | cut -d. -f2) "$EVENT_DATA") # Send the response curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response" -d "$RESPONSE" done
  3. How? 1. Create table on AWS Dynamo DB. 2. Create

    AWS Lambda function. 3. Create sample project using SPM. 4. Make executable file (Using Docker: Swift 5 on Ubuntu 16.04). 5. Deploy executable file and bootstrap to AWS Lambda.
  4. let boto3 = Python.import("boto3") let dynamodb = boto3.resource("dynamodb") let table

    = dynamodb.Table("swift-sample") print("\(table.scan())")
  5. Problems 1. Can't load shared libraries. 2. The environment variable

    PYTHON_LIBRARY isn’t set. 3. Can't find boto3 module.
  6. Use aws-lambda-swift Use aws-lambda-swift (Changed to use Swift 5). Deploy

    to shared libraries as a layer. And link dynamically when handling request in bootstrap. EXECUTABLE=$LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1)" /opt/swift-shared-libs/ld-linux-x86-64.so.2 --library-path /opt/swift-shared-libs/lib $EXECUTABLE
  7. Set env var and deploy boto3 1. Search python lib

    path and Set an environment variable. PYTHON_LIBRARY=/usr/lib64/libpython2.7.so.1.0 2. Deploy boto3 module as a layer. And set /opt/python as PYTHONPATH. $ docker run --privileged -it -v `pwd`:`pwd` -w `pwd` --rm amazonlinux $ yum install python2-pip $ pip install -t ./python boto3 $ zip -r boto3.zip python
  8. import AWSLambdaSwift struct Event: Codable { } struct Result: Codable

    { let result: String } func sample(event: Event, context: Context) -> Result { let boto3 = Python.import("boto3") let dynamodb = boto3.resource("dynamodb") let table = dynamodb.Table("swift-sample") return Result(result: "\(table.scan())") } let runtime = try Runtime() runtime.registerLambda("sample", handlerFunction: sample) try runtime.start()
  9. Reference • Custom AWS Lambda Runtimes • AWS Lambda Layers

    • Boto 3 - The AWS SDK for Python • aws-lambda-swift