From 71eed8884dc8eed95b51d0ca3a81c2b680077fd0 Mon Sep 17 00:00:00 2001 From: Thomas Schaffter Date: Tue, 3 Dec 2024 03:33:26 +0000 Subject: [PATCH 1/4] add generated code --- apps/sandbox/lambda-python/.gitignore | 244 ++++++++++++++++++ apps/sandbox/lambda-python/README.md | 115 +++++++++ apps/sandbox/lambda-python/__init__.py | 0 apps/sandbox/lambda-python/events/event.json | 62 +++++ .../lambda-python/hello_world/Dockerfile | 8 + .../lambda-python/hello_world/__init__.py | 0 apps/sandbox/lambda-python/hello_world/app.py | 33 +++ .../hello_world/requirements.txt | 1 + apps/sandbox/lambda-python/samconfig.toml | 30 +++ apps/sandbox/lambda-python/template.yaml | 43 +++ apps/sandbox/lambda-python/tests/__init__.py | 0 .../lambda-python/tests/unit/__init__.py | 0 .../lambda-python/tests/unit/test_handler.py | 72 ++++++ 13 files changed, 608 insertions(+) create mode 100644 apps/sandbox/lambda-python/.gitignore create mode 100644 apps/sandbox/lambda-python/README.md create mode 100644 apps/sandbox/lambda-python/__init__.py create mode 100644 apps/sandbox/lambda-python/events/event.json create mode 100644 apps/sandbox/lambda-python/hello_world/Dockerfile create mode 100644 apps/sandbox/lambda-python/hello_world/__init__.py create mode 100644 apps/sandbox/lambda-python/hello_world/app.py create mode 100644 apps/sandbox/lambda-python/hello_world/requirements.txt create mode 100644 apps/sandbox/lambda-python/samconfig.toml create mode 100644 apps/sandbox/lambda-python/template.yaml create mode 100644 apps/sandbox/lambda-python/tests/__init__.py create mode 100644 apps/sandbox/lambda-python/tests/unit/__init__.py create mode 100644 apps/sandbox/lambda-python/tests/unit/test_handler.py diff --git a/apps/sandbox/lambda-python/.gitignore b/apps/sandbox/lambda-python/.gitignore new file mode 100644 index 0000000000..4808264dbf --- /dev/null +++ b/apps/sandbox/lambda-python/.gitignore @@ -0,0 +1,244 @@ + +# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Ruby plugin and RubyMine +/.rakeTasks + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Build folder + +*/build/* + +# End of https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode \ No newline at end of file diff --git a/apps/sandbox/lambda-python/README.md b/apps/sandbox/lambda-python/README.md new file mode 100644 index 0000000000..5441a109b6 --- /dev/null +++ b/apps/sandbox/lambda-python/README.md @@ -0,0 +1,115 @@ +# lambda-python + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- hello_world - Code for the application's Lambda function and Project Dockerfile. +- events - Invocation events that you can use to invoke the function. +- tests - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. + +To use the SAM CLI, you need the following tools. + +- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +You may need the following for local testing. + +- [Python 3 installed](https://www.python.org/downloads/) + +To build and deploy your application for the first time, run the following in your shell: + +```bash +sam build +sam deploy --guided +``` + +The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts: + +- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +- **AWS Region**: The AWS region you want to deploy your app to. +- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +lambda-python$ sam build +``` + +The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `hello_world/requirements.txt` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +lambda-python$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +lambda-python$ sam local start-api +lambda-python$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml +Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application + +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +lambda-python$ sam logs -n HelloWorldFunction --stack-name "lambda-python" --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `tests` folder in this project. Use PIP to install the [pytest](https://docs.pytest.org/en/latest/) and run unit tests from your local machine. + +```bash +lambda-python$ pip install pytest pytest-mock --user +lambda-python$ python -m pytest tests/ -v +``` + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +sam delete --stack-name "lambda-python" +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/apps/sandbox/lambda-python/__init__.py b/apps/sandbox/lambda-python/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apps/sandbox/lambda-python/events/event.json b/apps/sandbox/lambda-python/events/event.json new file mode 100644 index 0000000000..a6197dea6c --- /dev/null +++ b/apps/sandbox/lambda-python/events/event.json @@ -0,0 +1,62 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/hello", + "path": "/hello", + "httpMethod": "GET", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/hello", + "resourcePath": "/hello", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } +} diff --git a/apps/sandbox/lambda-python/hello_world/Dockerfile b/apps/sandbox/lambda-python/hello_world/Dockerfile new file mode 100644 index 0000000000..c37d94fac2 --- /dev/null +++ b/apps/sandbox/lambda-python/hello_world/Dockerfile @@ -0,0 +1,8 @@ +FROM public.ecr.aws/lambda/python:3.13 + +COPY app.py requirements.txt ./ + +RUN python3.13 -m pip install -r requirements.txt -t . + +# Command can be overwritten by providing a different command in the template directly. +CMD ["app.lambda_handler"] diff --git a/apps/sandbox/lambda-python/hello_world/__init__.py b/apps/sandbox/lambda-python/hello_world/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apps/sandbox/lambda-python/hello_world/app.py b/apps/sandbox/lambda-python/hello_world/app.py new file mode 100644 index 0000000000..a04e2594c8 --- /dev/null +++ b/apps/sandbox/lambda-python/hello_world/app.py @@ -0,0 +1,33 @@ +import json + + +def lambda_handler(event, context): + """Sample pure Lambda function + + Parameters + ---------- + event: dict, required + API Gateway Lambda Proxy Input Format + + Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format + + context: object, required + Lambda Context runtime methods and attributes + + Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html + + Returns + ------ + API Gateway Lambda Proxy Output Format: dict + + Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html + """ + + return { + "statusCode": 200, + "body": json.dumps( + { + "message": "hello world", + } + ), + } diff --git a/apps/sandbox/lambda-python/hello_world/requirements.txt b/apps/sandbox/lambda-python/hello_world/requirements.txt new file mode 100644 index 0000000000..663bd1f6a2 --- /dev/null +++ b/apps/sandbox/lambda-python/hello_world/requirements.txt @@ -0,0 +1 @@ +requests \ No newline at end of file diff --git a/apps/sandbox/lambda-python/samconfig.toml b/apps/sandbox/lambda-python/samconfig.toml new file mode 100644 index 0000000000..876f8787d8 --- /dev/null +++ b/apps/sandbox/lambda-python/samconfig.toml @@ -0,0 +1,30 @@ +# More information about the configuration file can be found here: +# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html +version = 0.1 + +[default.global.parameters] +stack_name = "lambda-python" + +[default.build.parameters] +parallel = true + +[default.validate.parameters] +lint = true + +[default.deploy.parameters] +capabilities = "CAPABILITY_IAM" +confirm_changeset = true +resolve_s3 = true +resolve_image_repos = true + +[default.package.parameters] +resolve_s3 = true + +[default.sync.parameters] +watch = true + +[default.local_start_api.parameters] +warm_containers = "EAGER" + +[default.local_start_lambda.parameters] +warm_containers = "EAGER" diff --git a/apps/sandbox/lambda-python/template.yaml b/apps/sandbox/lambda-python/template.yaml new file mode 100644 index 0000000000..fd43c1fe39 --- /dev/null +++ b/apps/sandbox/lambda-python/template.yaml @@ -0,0 +1,43 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + python3.13 + + Sample SAM Template for lambda-python + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 3 + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + PackageType: Image + Architectures: + - x86_64 + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + Metadata: + Dockerfile: Dockerfile + DockerContext: ./hello_world + DockerTag: python3.13-v1 + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: 'API Gateway endpoint URL for Prod stage for Hello World function' + Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/' + HelloWorldFunction: + Description: 'Hello World Lambda Function ARN' + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: 'Implicit IAM Role created for Hello World function' + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/apps/sandbox/lambda-python/tests/__init__.py b/apps/sandbox/lambda-python/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apps/sandbox/lambda-python/tests/unit/__init__.py b/apps/sandbox/lambda-python/tests/unit/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apps/sandbox/lambda-python/tests/unit/test_handler.py b/apps/sandbox/lambda-python/tests/unit/test_handler.py new file mode 100644 index 0000000000..8787d38ed0 --- /dev/null +++ b/apps/sandbox/lambda-python/tests/unit/test_handler.py @@ -0,0 +1,72 @@ +import json + +import pytest + +from hello_world import app + + +@pytest.fixture() +def apigw_event(): + """Generates API GW Event""" + + return { + "body": '{ "test": "body"}', + "resource": "/{proxy+}", + "requestContext": { + "resourceId": "123456", + "apiId": "1234567890", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "accountId": "123456789012", + "identity": { + "apiKey": "", + "userArn": "", + "cognitoAuthenticationType": "", + "caller": "", + "userAgent": "Custom User Agent String", + "user": "", + "cognitoIdentityPoolId": "", + "cognitoIdentityId": "", + "cognitoAuthenticationProvider": "", + "sourceIp": "127.0.0.1", + "accountId": "", + }, + "stage": "prod", + }, + "queryStringParameters": {"foo": "bar"}, + "headers": { + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "Accept-Language": "en-US,en;q=0.8", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Mobile-Viewer": "false", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "CloudFront-Viewer-Country": "US", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Upgrade-Insecure-Requests": "1", + "X-Forwarded-Port": "443", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "X-Forwarded-Proto": "https", + "X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==", + "CloudFront-Is-Tablet-Viewer": "false", + "Cache-Control": "max-age=0", + "User-Agent": "Custom User Agent String", + "CloudFront-Forwarded-Proto": "https", + "Accept-Encoding": "gzip, deflate, sdch", + }, + "pathParameters": {"proxy": "/examplepath"}, + "httpMethod": "POST", + "stageVariables": {"baz": "qux"}, + "path": "/examplepath", + } + + +def test_lambda_handler(apigw_event, mocker): + + ret = app.lambda_handler(apigw_event, "") + data = json.loads(ret["body"]) + + assert ret["statusCode"] == 200 + assert "message" in ret["body"] + assert data["message"] == "hello world" From 3dbe07adb0d163ddfdbe5e8de6fbf89658c7bb66 Mon Sep 17 00:00:00 2001 From: Thomas Schaffter Date: Tue, 3 Dec 2024 03:41:56 +0000 Subject: [PATCH 2/4] Create Nx project --- apps/sandbox/lambda-nodejs/project.json | 2 +- .../sandbox/lambda-python/.aws-sam/build.toml | 12 +++++++ .../{hello_world => }/Dockerfile | 2 +- apps/sandbox/lambda-python/project.json | 34 +++++++++++++++++++ .../{hello_world => }/requirements.txt | 0 apps/sandbox/lambda-python/template.yaml | 2 +- 6 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 apps/sandbox/lambda-python/.aws-sam/build.toml rename apps/sandbox/lambda-python/{hello_world => }/Dockerfile (82%) create mode 100644 apps/sandbox/lambda-python/project.json rename apps/sandbox/lambda-python/{hello_world => }/requirements.txt (100%) diff --git a/apps/sandbox/lambda-nodejs/project.json b/apps/sandbox/lambda-nodejs/project.json index deb76abd7e..ffb505e0d1 100644 --- a/apps/sandbox/lambda-nodejs/project.json +++ b/apps/sandbox/lambda-nodejs/project.json @@ -1,7 +1,7 @@ { "name": "sandbox-lambda-nodejs", "$schema": "../../../node_modules/nx/schemas/project-schema.json", - "projectType": "library", + "projectType": "application", "targets": { "build": { "executor": "nx:run-commands", diff --git a/apps/sandbox/lambda-python/.aws-sam/build.toml b/apps/sandbox/lambda-python/.aws-sam/build.toml new file mode 100644 index 0000000000..b4461decb7 --- /dev/null +++ b/apps/sandbox/lambda-python/.aws-sam/build.toml @@ -0,0 +1,12 @@ +# This file is auto generated by SAM CLI build command + +[function_build_definitions.a4887bcd-4b8c-43ca-a4d1-9fe4d156fee4] +packagetype = "Image" +functions = ["HelloWorldFunction"] + +[function_build_definitions.a4887bcd-4b8c-43ca-a4d1-9fe4d156fee4.metadata] +Dockerfile = "Dockerfile" +DockerContext = "/workspaces/sage-monorepo/apps/sandbox/lambda-python" +DockerTag = "python3.13-v1" + +[layer_build_definitions] diff --git a/apps/sandbox/lambda-python/hello_world/Dockerfile b/apps/sandbox/lambda-python/Dockerfile similarity index 82% rename from apps/sandbox/lambda-python/hello_world/Dockerfile rename to apps/sandbox/lambda-python/Dockerfile index c37d94fac2..2fb911ce25 100644 --- a/apps/sandbox/lambda-python/hello_world/Dockerfile +++ b/apps/sandbox/lambda-python/Dockerfile @@ -1,6 +1,6 @@ FROM public.ecr.aws/lambda/python:3.13 -COPY app.py requirements.txt ./ +COPY hello_world/app.py requirements.txt ./ RUN python3.13 -m pip install -r requirements.txt -t . diff --git a/apps/sandbox/lambda-python/project.json b/apps/sandbox/lambda-python/project.json new file mode 100644 index 0000000000..43a8a0e8c7 --- /dev/null +++ b/apps/sandbox/lambda-python/project.json @@ -0,0 +1,34 @@ +{ + "name": "sandbox-lambda-python", + "$schema": "../../../node_modules/nx/schemas/project-schema.json", + "projectType": "application", + "targets": { + "build": { + "executor": "nx:run-commands", + "options": { + "command": "sam build", + "cwd": "{projectRoot}" + } + }, + "serve": { + "executor": "nx:run-commands", + "options": { + "command": "docker/sandbox/serve.sh {projectName}" + } + }, + "serve-detach": { + "executor": "nx:run-commands", + "options": { + "command": "docker/sandbox/serve-detach.sh {projectName}" + } + }, + "invoke": { + "executor": "nx:run-commands", + "options": { + "command": "curl -X POST 'http://localhost:9000/2015-03-31/functions/function/invocations' --data @{args.event}", + "cwd": "{projectRoot}" + } + } + }, + "tags": ["language:python"] +} diff --git a/apps/sandbox/lambda-python/hello_world/requirements.txt b/apps/sandbox/lambda-python/requirements.txt similarity index 100% rename from apps/sandbox/lambda-python/hello_world/requirements.txt rename to apps/sandbox/lambda-python/requirements.txt diff --git a/apps/sandbox/lambda-python/template.yaml b/apps/sandbox/lambda-python/template.yaml index fd43c1fe39..e04fd5b8cd 100644 --- a/apps/sandbox/lambda-python/template.yaml +++ b/apps/sandbox/lambda-python/template.yaml @@ -25,7 +25,7 @@ Resources: Method: get Metadata: Dockerfile: Dockerfile - DockerContext: ./hello_world + DockerContext: . DockerTag: python3.13-v1 Outputs: From 348a9f8e06788e02f7ea3db3c486ca923001a857 Mon Sep 17 00:00:00 2001 From: Thomas Schaffter Date: Tue, 3 Dec 2024 03:44:36 +0000 Subject: [PATCH 3/4] Add docker compose file --- docker/sandbox/serve-detach.sh | 1 + docker/sandbox/serve.sh | 1 + docker/sandbox/services/lambda-python.yml | 9 +++++++++ 3 files changed, 11 insertions(+) create mode 100644 docker/sandbox/services/lambda-python.yml diff --git a/docker/sandbox/serve-detach.sh b/docker/sandbox/serve-detach.sh index a6bfcfd5ff..67c2cd9e5d 100755 --- a/docker/sandbox/serve-detach.sh +++ b/docker/sandbox/serve-detach.sh @@ -3,6 +3,7 @@ args=( # List of services in alphanumeric order --file docker/sandbox/services/lambda-nodejs.yml + --file docker/sandbox/services/lambda-python.yml --file docker/sandbox/networks.yml --file docker/sandbox/volumes.yml diff --git a/docker/sandbox/serve.sh b/docker/sandbox/serve.sh index d74c8d4460..4b0c3c0e4e 100755 --- a/docker/sandbox/serve.sh +++ b/docker/sandbox/serve.sh @@ -3,6 +3,7 @@ args=( # List of services in alphanumeric order --file docker/sandbox/services/lambda-nodejs.yml + --file docker/sandbox/services/lambda-python.yml --file docker/sandbox/networks.yml --file docker/sandbox/volumes.yml diff --git a/docker/sandbox/services/lambda-python.yml b/docker/sandbox/services/lambda-python.yml new file mode 100644 index 0000000000..8acfd3b569 --- /dev/null +++ b/docker/sandbox/services/lambda-python.yml @@ -0,0 +1,9 @@ +services: + sandbox-lambda-python: + image: ghcr.io/sage-bionetworks/sandbox-lambda-python:${SANDBOX_VERSION:-local} + container_name: sandbox-lambda-python + restart: always + networks: + - sandbox + ports: + - '9000:8080' From 5ff181194ceec4a318a7bebe6325543d96d441f5 Mon Sep 17 00:00:00 2001 From: Thomas Schaffter Date: Tue, 3 Dec 2024 03:54:37 +0000 Subject: [PATCH 4/4] fix hadolint warnings --- apps/sandbox/lambda-python/Dockerfile | 4 +- apps/sandbox/lambda-python/README.md | 120 ++++++-------------------- 2 files changed, 27 insertions(+), 97 deletions(-) diff --git a/apps/sandbox/lambda-python/Dockerfile b/apps/sandbox/lambda-python/Dockerfile index 2fb911ce25..c34df21937 100644 --- a/apps/sandbox/lambda-python/Dockerfile +++ b/apps/sandbox/lambda-python/Dockerfile @@ -1,8 +1,8 @@ FROM public.ecr.aws/lambda/python:3.13 -COPY hello_world/app.py requirements.txt ./ +COPY hello_world/app.py requirements.txt ${LAMBDA_TASK_ROOT}/ -RUN python3.13 -m pip install -r requirements.txt -t . +RUN python3.13 -m pip install --no-cache-dir -r requirements.txt -t . # Command can be overwritten by providing a different command in the template directly. CMD ["app.lambda_handler"] diff --git a/apps/sandbox/lambda-python/README.md b/apps/sandbox/lambda-python/README.md index 5441a109b6..83209fad3f 100644 --- a/apps/sandbox/lambda-python/README.md +++ b/apps/sandbox/lambda-python/README.md @@ -1,115 +1,45 @@ -# lambda-python +# Sandbox Lambda Python -This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. +## Build the project -- hello_world - Code for the application's Lambda function and Project Dockerfile. -- events - Invocation events that you can use to invoke the function. -- tests - Unit tests for the application code. -- template.yaml - A template that defines the application's AWS resources. - -The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. - -## Deploy the sample application - -The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. - -To use the SAM CLI, you need the following tools. - -- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -- Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) - -You may need the following for local testing. - -- [Python 3 installed](https://www.python.org/downloads/) - -To build and deploy your application for the first time, run the following in your shell: - -```bash -sam build -sam deploy --guided +```console +nx build sandbox-lambda-python ``` -The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts: - -- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. -- **AWS Region**: The AWS region you want to deploy your app to. -- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. -- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. -- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. - -You can find your API Gateway Endpoint URL in the output values displayed after deployment. - -## Use the SAM CLI to build and test locally +## Build the Docker image of the Lambda function -Build your application with the `sam build` command. - -```bash -lambda-python$ sam build +```console +nx build-image sandbox-lambda-python ``` -The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `hello_world/requirements.txt` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder. - -Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. +## Start the Lambda function locally with Docker Compose -Run functions locally and invoke them with the `sam local invoke` command. +Starts the Lambda function in the foreground, allowing you to view logs and interact with it +directly. -```bash -lambda-python$ sam local invoke HelloWorldFunction --event events/event.json +```console +nx serve sandbox-lambda-python ``` -The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. +Starts the Lambda function in detached mode, running it in the background. This is useful if you +want to continue using the terminal for other tasks while the function runs. -```bash -lambda-python$ sam local start-api -lambda-python$ curl http://localhost:3000/ +```console +nx serve-detach sandbox-lambda-python ``` -The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. +## Invoke the Lambda function locally -```yaml -Events: - HelloWorld: - Type: Api - Properties: - Path: /hello - Method: get -``` +To invoke the Lambda function after starting it locally, use the following command: -## Add a resource to your application - -The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. - -## Fetch, tail, and filter Lambda function logs - -To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. - -`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. - -```bash -lambda-python$ sam logs -n HelloWorldFunction --stack-name "lambda-python" --tail -``` - -You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). - -## Unit tests - -Tests are defined in the `tests` folder in this project. Use PIP to install the [pytest](https://docs.pytest.org/en/latest/) and run unit tests from your local machine. - -```bash -lambda-python$ pip install pytest pytest-mock --user -lambda-python$ python -m pytest tests/ -v +```console +nx run sandbox-lambda-python:invoke --event ``` -## Cleanup - -To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: +Replace `` with the path to your JSON file containing the event payload relative +to the location of the project folder. For example, if your event payload is stored in a file +located at `events/event.json` relative to the project folder: -```bash -sam delete --stack-name "lambda-python" +```console +nx run sandbox-lambda-python:invoke --event events/event.json ``` - -## Resources - -See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. - -Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)