From 110a21f052156deee8cf6ecc6659ef671b3af4b7 Mon Sep 17 00:00:00 2001 From: Mark Sailes Date: Fri, 1 Oct 2021 13:31:50 +0100 Subject: [PATCH 1/2] arm64 changes --- lambda-image-support/HelloWorldFunction/Dockerfile | 4 ++-- pom.xml | 2 +- src/main/java/com/myorg/CdkSamExampleStack.java | 12 ++++-------- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/lambda-image-support/HelloWorldFunction/Dockerfile b/lambda-image-support/HelloWorldFunction/Dockerfile index 4bab5d1..1875bf6 100644 --- a/lambda-image-support/HelloWorldFunction/Dockerfile +++ b/lambda-image-support/HelloWorldFunction/Dockerfile @@ -1,4 +1,4 @@ -FROM amd64/maven as build-image +FROM arm64v8/maven as build-image WORKDIR "/task" COPY src/ src/ @@ -7,7 +7,7 @@ COPY pom.xml ./ RUN mvn -q clean install RUN mvn dependency:copy-dependencies -DincludeScope=compile -FROM public.ecr.aws/lambda/java:11 +FROM public.ecr.aws/lambda/java:11-arm64 COPY --from=build-image /task/target/classes /var/task/ COPY --from=build-image /task/target/dependency /var/task/lib diff --git a/pom.xml b/pom.xml index dd3dbf6..0f3c86a 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ UTF-8 - 1.87.1 + 1.125.0 5.7.0 diff --git a/src/main/java/com/myorg/CdkSamExampleStack.java b/src/main/java/com/myorg/CdkSamExampleStack.java index 76ea872..800323a 100644 --- a/src/main/java/com/myorg/CdkSamExampleStack.java +++ b/src/main/java/com/myorg/CdkSamExampleStack.java @@ -7,16 +7,11 @@ import software.amazon.awscdk.services.iam.IManagedPolicy; import software.amazon.awscdk.services.iam.ManagedPolicy; import software.amazon.awscdk.services.iam.Role; -import software.amazon.awscdk.services.lambda.AssetImageCodeProps; -import software.amazon.awscdk.services.lambda.Code; -import software.amazon.awscdk.services.lambda.DockerImageCode; -import software.amazon.awscdk.services.lambda.DockerImageFunction; -import software.amazon.awscdk.services.lambda.DockerImageFunctionProps; -import software.amazon.awscdk.services.lambda.EcrImageCode; -import software.amazon.awscdk.services.lambda.Function; -import software.amazon.awscdk.services.lambda.FunctionProps; +import software.amazon.awscdk.services.lambda.*; import software.amazon.awscdk.services.lambda.Runtime; +import java.util.Collections; + public class CdkSamExampleStack extends Stack { public CdkSamExampleStack(final Construct scope, final String id) { this(scope, id, null); @@ -29,6 +24,7 @@ public CdkSamExampleStack(final Construct scope, final String id, final StackPro .code(DockerImageCode.fromImageAsset("./lambda-image-support/HelloWorldFunction")) .timeout(Duration.seconds(20)) .memorySize(1024) + .architectures(Collections.singletonList(Architecture.ARM_64)) .build()); } } From e43b004d3ce7249b51e23c47ba8f76f6ff772ef1 Mon Sep 17 00:00:00 2001 From: Mark Sailes Date: Fri, 1 Oct 2021 16:06:22 +0100 Subject: [PATCH 2/2] arm64 changes --- own-base-image/HelloWorldFunction/Dockerfile | 43 +++++++ own-base-image/HelloWorldFunction/pom.xml | 57 +++++++++ .../src/main/java/helloworld/App.java | 48 ++++++++ .../src/test/java/helloworld/AppTest.java | 22 ++++ own-base-image/README.md | 114 ++++++++++++++++++ own-base-image/events/event.json | 63 ++++++++++ own-base-image/template.yaml | 41 +++++++ src/main/java/com/myorg/CdkSamExampleApp.java | 2 +- .../java/com/myorg/CdkSamExampleStack.java | 2 +- 9 files changed, 390 insertions(+), 2 deletions(-) create mode 100644 own-base-image/HelloWorldFunction/Dockerfile create mode 100644 own-base-image/HelloWorldFunction/pom.xml create mode 100644 own-base-image/HelloWorldFunction/src/main/java/helloworld/App.java create mode 100644 own-base-image/HelloWorldFunction/src/test/java/helloworld/AppTest.java create mode 100644 own-base-image/README.md create mode 100644 own-base-image/events/event.json create mode 100644 own-base-image/template.yaml diff --git a/own-base-image/HelloWorldFunction/Dockerfile b/own-base-image/HelloWorldFunction/Dockerfile new file mode 100644 index 0000000..99841b9 --- /dev/null +++ b/own-base-image/HelloWorldFunction/Dockerfile @@ -0,0 +1,43 @@ +#FROM arm64v8/maven as build-image +# +#WORKDIR "/task" +#COPY src/ src/ +#COPY pom.xml ./ +# +#RUN mvn -q clean install +#RUN mvn dependency:copy-dependencies -DincludeScope=compile +# +#FROM public.ecr.aws/lambda/java:11-arm64 +# +#COPY --from=build-image /task/target/classes /var/task/ +#COPY --from=build-image /task/target/dependency /var/task/lib +## Command can be overwritten by providing a different command in the template directly. +#CMD ["helloworld.App::handleRequest"] + +# we'll use Amazon Linux 2 + Corretto 11 as our base +FROM arm64v8/amazoncorretto:11 as base + +# configure the build environment +FROM base as build +RUN yum install -y maven +WORKDIR /src + +# cache and copy dependencies +ADD pom.xml . +RUN mvn dependency:go-offline dependency:copy-dependencies + +# compile the function +ADD . . +RUN mvn package + +# copy the function artifact and dependencies onto a clean base +FROM base +WORKDIR /function + +COPY --from=build /src/target/dependency/*.jar ./ +COPY --from=build /src/target/*.jar ./ + +# configure the runtime startup as main +ENTRYPOINT [ "/usr/bin/java", "-cp", "./*", "com.amazonaws.services.lambda.runtime.api.client.AWSLambda" ] +# pass the name of the function handler as an argument to the runtime +CMD ["helloworld.App::handleRequest"] \ No newline at end of file diff --git a/own-base-image/HelloWorldFunction/pom.xml b/own-base-image/HelloWorldFunction/pom.xml new file mode 100644 index 0000000..f6b7b16 --- /dev/null +++ b/own-base-image/HelloWorldFunction/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + helloworld + HelloWorld + 1.0 + jar + A sample Hello World created for SAM CLI. + + 1.8 + 1.8 + + + + + com.amazonaws + aws-lambda-java-core + 1.2.1 + + + com.amazonaws + aws-lambda-java-events + 3.6.0 + + + com.amazonaws + aws-lambda-java-runtime-interface-client + 2.0.0 + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + + + package + + shade + + + + + + + diff --git a/own-base-image/HelloWorldFunction/src/main/java/helloworld/App.java b/own-base-image/HelloWorldFunction/src/main/java/helloworld/App.java new file mode 100644 index 0000000..0cbd0f8 --- /dev/null +++ b/own-base-image/HelloWorldFunction/src/main/java/helloworld/App.java @@ -0,0 +1,48 @@ +package helloworld; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; + +/** + * Handler for requests to Lambda function. + */ +public class App implements RequestHandler { + + public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { + Map headers = new HashMap<>(); + headers.put("Content-Type", "application/json"); + headers.put("X-Custom-Header", "application/json"); + + APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() + .withHeaders(headers); + try { + final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); + String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); + + return response + .withStatusCode(200) + .withBody(output); + } catch (IOException e) { + return response + .withBody("{}") + .withStatusCode(500); + } + } + + private String getPageContents(String address) throws IOException{ + URL url = new URL(address); + try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { + return br.lines().collect(Collectors.joining(System.lineSeparator())); + } + } +} diff --git a/own-base-image/HelloWorldFunction/src/test/java/helloworld/AppTest.java b/own-base-image/HelloWorldFunction/src/test/java/helloworld/AppTest.java new file mode 100644 index 0000000..b9d1e42 --- /dev/null +++ b/own-base-image/HelloWorldFunction/src/test/java/helloworld/AppTest.java @@ -0,0 +1,22 @@ +package helloworld; + +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class AppTest { + @Test + public void successfulResponse() { + App app = new App(); + APIGatewayProxyResponseEvent result = app.handleRequest(null, null); + assertEquals(result.getStatusCode().intValue(), 200); + assertEquals(result.getHeaders().get("Content-Type"), "application/json"); + String content = result.getBody(); + assertNotNull(content); + assertTrue(content.contains("\"message\"")); + assertTrue(content.contains("\"hello world\"")); + assertTrue(content.contains("\"location\"")); + } +} diff --git a/own-base-image/README.md b/own-base-image/README.md new file mode 100644 index 0000000..198bf04 --- /dev/null +++ b/own-base-image/README.md @@ -0,0 +1,114 @@ +# lamda-image-support + +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. + +- HelloWorldFunction/src/main - Code for the application's Lambda function and Project Dockerfile. +- events - Invocation events that you can use to invoke the function. +- HelloWorldFunction/src/test - 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. +* Java11 - [Install the Java 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html) +* Maven - [Install Maven](https://maven.apache.org/install.html) + +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 modified 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 +lamda-image-support$ sam build +``` + +The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `HelloWorldFunction/pom.xml` 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 +lamda-image-support$ 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 +lamda-image-support$ sam local start-api +lamda-image-support$ 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 +lamda-image-support$ sam logs -n HelloWorldFunction --stack-name lamda-image-support --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 `HelloWorldFunction/src/test` folder in this project. + +```bash +lamda-image-support$ cd HelloWorldFunction +HelloWorldFunction$ mvn test +``` + +## 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 +aws cloudformation delete-stack --stack-name lamda-image-support +``` + +## 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/own-base-image/events/event.json b/own-base-image/events/event.json new file mode 100644 index 0000000..3822fad --- /dev/null +++ b/own-base-image/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "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/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/own-base-image/template.yaml b/own-base-image/template.yaml new file mode 100644 index 0000000..d17edc5 --- /dev/null +++ b/own-base-image/template.yaml @@ -0,0 +1,41 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + lamda-image-support + + Sample SAM Template for lamda-image-support + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 20 + +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 + 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: + DockerTag: java11-maven-v1 + DockerContext: ./HelloWorldFunction + Dockerfile: Dockerfile + +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/src/main/java/com/myorg/CdkSamExampleApp.java b/src/main/java/com/myorg/CdkSamExampleApp.java index 30cbe5d..0ca5ef8 100644 --- a/src/main/java/com/myorg/CdkSamExampleApp.java +++ b/src/main/java/com/myorg/CdkSamExampleApp.java @@ -8,7 +8,7 @@ public class CdkSamExampleApp { public static void main(final String[] args) { App app = new App(); - new CdkSamExampleStack(app, "CdkSamExampleStack"); + new CdkSamExampleStack(app, "ArmContainerImageExample"); app.synth(); } diff --git a/src/main/java/com/myorg/CdkSamExampleStack.java b/src/main/java/com/myorg/CdkSamExampleStack.java index 800323a..7e9ad50 100644 --- a/src/main/java/com/myorg/CdkSamExampleStack.java +++ b/src/main/java/com/myorg/CdkSamExampleStack.java @@ -21,7 +21,7 @@ public CdkSamExampleStack(final Construct scope, final String id, final StackPro super(scope, id, props); new DockerImageFunction(this, "MyFunction", DockerImageFunctionProps.builder() - .code(DockerImageCode.fromImageAsset("./lambda-image-support/HelloWorldFunction")) + .code(DockerImageCode.fromImageAsset("./own-base-image/HelloWorldFunction")) .timeout(Duration.seconds(20)) .memorySize(1024) .architectures(Collections.singletonList(Architecture.ARM_64))