-
-
Notifications
You must be signed in to change notification settings - Fork 144
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Upload recording feature #787
Open
KIRA009
wants to merge
13
commits into
OpenAdaptAI:main
Choose a base branch
from
KIRA009:feature/upload-recording
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
cc75fdf
feat: Add script to deploy uploader code to a lambda
KIRA009 68a973f
feat: Add upload recording button in dashboard
KIRA009 dbf76be
chore: Fix flake8 lint errors
KIRA009 7fee87d
feat: Upload recording to user id specific folders
KIRA009 cd33510
chore: Replace package with module and remove unwanted code
KIRA009 23238a0
chore: Move recording uploader to separate admin folder
KIRA009 3554bb4
docs: Update README.md with details on how to deploy the recording up…
KIRA009 489d28b
lint: Fix linting
KIRA009 da83b18
feat: Add upload button to recordings page
KIRA009 f673cb8
fix: Linting
KIRA009 8e4bf17
feat: Add ability to delete uploaded recordings, switched off by default
KIRA009 99ea0f3
feat: Add retries to s3 uploads
KIRA009 4a5b80e
lint: Fix flake8 linting
KIRA009 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
# recording-uploader | ||
|
||
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. | ||
|
||
- uploader - Code for the application's Lambda function. | ||
- 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. | ||
|
||
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. | ||
The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. | ||
|
||
* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) | ||
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) | ||
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) | ||
|
||
## Deploy the application | ||
|
||
There is a `deploy` script that creates the s3 bucket and deploys the application using the SAM CLI (included as part of the dev dependencies of this project). The bucket name is hardcoded in the script. The SAM CLI is set up to run in `guided` mode, which will prompt the user every time before deploying, in case the user wants to change the default values. | ||
|
||
|
||
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 --use-container` command. | ||
|
||
```bash | ||
recording-uploader$ sam build --use-container | ||
``` | ||
|
||
The SAM CLI installs dependencies defined in `uploader/requirements.txt`, creates a deployment package, and saves it in the `.aws-sam/build` folder. | ||
|
||
Run functions locally and invoke them with the `sam local invoke` command. | ||
|
||
```bash | ||
recording-uploader$ sam local invoke RecordingUploadFunction | ||
``` | ||
|
||
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 | ||
recording-uploader$ sam local start-api | ||
recording-uploader$ 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: | ||
RecordingUpload: | ||
Type: Api | ||
Properties: | ||
Path: /upload | ||
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 | ||
recording-uploader$ sam logs -n RecordingUploadFunction --stack-name "recording-uploader" --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). | ||
|
||
## 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 "recording-uploader" | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
"""Init file for the recording_uploader package.""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
"""Entrypoint to deploy the uploader to AWS Lambda.""" | ||
|
||
import pathlib | ||
import subprocess | ||
|
||
from loguru import logger | ||
import boto3 | ||
import fire | ||
|
||
CURRENT_DIR = pathlib.Path(__file__).parent | ||
|
||
|
||
def main(region_name: str = "us-east-1", guided: bool = True) -> None: | ||
"""Deploy the uploader to AWS Lambda. | ||
|
||
Args: | ||
region_name (str): The AWS region to deploy the Lambda function to. | ||
guided (bool): Whether to use the guided SAM deployment. | ||
""" | ||
s3 = boto3.client( | ||
"s3", | ||
region_name=region_name, | ||
endpoint_url=f"https://s3.{region_name}.amazonaws.com", | ||
) | ||
bucket = "openadapt" | ||
|
||
s3.create_bucket( | ||
ACL="private", | ||
Bucket=bucket, | ||
) | ||
|
||
# deploy the code to AWS Lambda | ||
commands = ["sam", "deploy"] | ||
if guided: | ||
commands.append("--guided") | ||
subprocess.run(commands, cwd=CURRENT_DIR, check=True) | ||
logger.info("Lambda function deployed successfully.") | ||
|
||
|
||
if __name__ == "__main__": | ||
fire.Fire(main) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# 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] | ||
[default.global.parameters] | ||
stack_name = "recording-uploader" | ||
|
||
[default.build.parameters] | ||
cached = true | ||
parallel = true | ||
|
||
[default.validate.parameters] | ||
lint = true | ||
|
||
[default.deploy.parameters] | ||
capabilities = "CAPABILITY_IAM" | ||
confirm_changeset = false | ||
resolve_s3 = true | ||
s3_prefix = "recording-uploader" | ||
region = "us-east-1" | ||
image_repositories = [] | ||
|
||
[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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
AWSTemplateFormatVersion: '2010-09-09' | ||
Transform: AWS::Serverless-2016-10-31 | ||
Description: > | ||
recording-uploader | ||
|
||
Sample SAM Template for recording-uploader | ||
|
||
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst | ||
Globals: | ||
Function: | ||
Timeout: 3 | ||
|
||
Resources: | ||
RecordingUploadFunction: | ||
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: | ||
CodeUri: uploader/ | ||
Handler: app.lambda_handler | ||
Runtime: python3.10 | ||
Architectures: | ||
- x86_64 | ||
Events: | ||
RecordingUpload: | ||
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: /upload | ||
Method: post | ||
Policies: | ||
- Statement: | ||
- Sid: S3PutObjectPolicy | ||
Effect: Allow | ||
Action: | ||
- s3:PutObject | ||
Resource: !Sub "arn:aws:s3:::openadapt/*" | ||
|
||
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 | ||
RecordingUploadApi: | ||
Description: "API Gateway endpoint URL for Prod stage for Recording Upload function" | ||
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/upload/" | ||
RecordingUploadFunction: | ||
Description: "Recording Upload Lambda Function ARN" | ||
Value: !GetAtt RecordingUploadFunction.Arn | ||
RecordingUploadFunctionIamRole: | ||
Description: "Implicit IAM Role created for Recording Upload function" | ||
Value: !GetAtt RecordingUploadFunctionRole.Arn |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
"""Init file for the uploader module.""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
"""Lambda function for generating a presigned URL for uploading a recording to S3.""" | ||
|
||
from typing import Any | ||
from uuid import uuid4 | ||
import json | ||
|
||
from botocore.client import Config | ||
import boto3 | ||
|
||
DEFAULT_REGION_NAME = "us-east-1" | ||
DEFAULT_BUCKET = "openadapt" | ||
ONE_HOUR_IN_SECONDS = 3600 | ||
|
||
|
||
def lambda_handler(event: dict, context: Any) -> dict: | ||
"""Main entry point for the lambda function.""" | ||
try: | ||
user_id = json.loads(event["body"])["user_id"] | ||
except Exception as e: | ||
print(e) | ||
return { | ||
"statusCode": 400, | ||
"body": json.dumps({"error": "Missing 'user_id' in request body."}), | ||
} | ||
return { | ||
"statusCode": 200, | ||
"body": json.dumps(get_presigned_url(user_id)), | ||
} | ||
|
||
|
||
def get_presigned_url( | ||
user_id: str, bucket: str = DEFAULT_BUCKET, region_name: str = DEFAULT_REGION_NAME | ||
) -> dict: | ||
"""Generate a presigned URL for uploading a recording to S3. | ||
|
||
Args: | ||
bucket (str): The S3 bucket to upload the recording to. | ||
region_name (str): The AWS region the bucket is in. | ||
|
||
Returns: | ||
dict: A dictionary containing the presigned URL. | ||
""" | ||
s3 = boto3.client( | ||
"s3", | ||
config=Config(signature_version="s3v4"), | ||
region_name=region_name, | ||
endpoint_url=f"https://s3.{region_name}.amazonaws.com", | ||
) | ||
key = f"recordings/{user_id}/{uuid4()}.zip" | ||
|
||
presigned_url = s3.generate_presigned_url( | ||
ClientMethod="put_object", | ||
Params={ | ||
"Bucket": bucket, | ||
"Key": key, | ||
}, | ||
ExpiresIn=ONE_HOUR_IN_SECONDS, | ||
) | ||
|
||
return {"url": presigned_url} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
boto3==1.34.84 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about loading the AWS credentials from
config.py
?