Deploy a Micronaut application as a GraalVM Native Image to AWS Lambda

Learn how to distribute a Micronaut Java application built as a GraalVM Native image to AWS Lambda Custom Runtime

Authors: Sergio del Amo

Micronaut Version: 2.0.1

1 Getting Started

Please, read about Micronaut AWS Lambda Support to learn more about different Lambda runtime, Triggers and Handlers and how to integrate with a Micronaut application.

The biggest problem with Java applications and Lambda is how to mitigate Cold startups. Executing GraalVM Native images of a Micronaut function in a Lambda Custom runtime is a solution to this problem.

In this guide, we are going to deploy a Micronaut Application as a GraalVM Native image to a AWS Lambda custom runtime. If your Lambda integrates with API Gateway via a Lambda Proxy, a Micronaut function of type Application with the aws-lambda feature is a good fit. Specially, when you have multiple endpoints which you wish to delegate to a single Lambda.

1.1 What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

You will need also an AWS Account.

1.2 Solution

We recommend you to follow the instructions in the next sections and create the app step by step. However, you can go right to the completed example.

or

Then, cd into the complete folder which you will find in the root project of the downloaded/cloned project.

2 Writing the App

Create a Micronaut application with the aws-lambda and graalvm features using the CLI:

% mn create-app example.micronaut.complete --features aws-lambda,graalvm
launch

2.1 Code

The generated application contains a BookController. It responds to POST request to /.

src/main/java/example/micronaut/BookController.java
package example.micronaut;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;

import javax.validation.Valid;
import java.util.UUID;

@Controller (1)
public class BookController {

    @Post (2)
    public BookSaved save(@Valid @Body Book book) { (3)
        BookSaved bookSaved = new BookSaved();
        bookSaved.setName(book.getName());
        bookSaved.setIsbn(UUID.randomUUID().toString());
        return bookSaved;
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /
2 The @Post annotation is used to map HTTP request to / to the the save method.
3 Add the @Valid annotation to any method parameter’s object which requires validation.

The controller’s method parameter is a Book object:

src/main/java/example/micronaut/Book.java
package example.micronaut;
import edu.umd.cs.findbugs.annotations.NonNull;
import io.micronaut.core.annotation.Introspected;
import javax.validation.constraints.NotBlank;

@Introspected (1)
public class Book {

    @NotBlank (2)
    @NonNull (3)
    private String name;

    public Book() {
    }

    @NonNull
    public String getName() {
        return name;
    }

    public void setName(@NonNull String name) {
        this.name = name;
    }
}
1 Annotate the class with @Introspected to generate the Bean Metainformation at compile time.
2 name is required
3 Add a nullability annotation to help with Kotlin interoperability and help the IDE.

It returns a BookSaved object:

src/main/java/example/micronaut/BookSaved.java
package example.micronaut;
import edu.umd.cs.findbugs.annotations.NonNull;
import io.micronaut.core.annotation.Introspected;

import javax.validation.constraints.NotBlank;

@Introspected (1)
public class BookSaved {

    @NotBlank (2)
    @NonNull (3)
    private String name;

    @NotBlank (2)
    @NonNull (3)
    private String isbn;

    public BookSaved() {

    }

    @NonNull
    public String getName() {
        return name;
    }

    public void setName(@NonNull String name) {
        this.name = name;
    }

    @NonNull
    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(@NonNull String isbn) {
        this.isbn = isbn;
    }
}
1 Annotate the class with @Introspected to generate the Bean Metainformation at compile time.
2 name and isbn are required
3 Add a nullability annotation to help with Kotlin interoperability and help the IDE.

The generated tests illustrates how the code works when the lambda gets invoked:

src/test/java/example/micronaut/BookControllerTest.java
package example.micronaut;
import com.amazonaws.serverless.exceptions.ContainerInitializationException;
import com.amazonaws.serverless.proxy.internal.testutils.AwsProxyRequestBuilder;
import com.amazonaws.serverless.proxy.internal.testutils.MockLambdaContext;
import com.amazonaws.serverless.proxy.model.AwsProxyRequest;
import com.amazonaws.serverless.proxy.model.AwsProxyResponse;
import com.amazonaws.services.lambda.runtime.Context;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpMethod;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import io.micronaut.function.aws.proxy.MicronautLambdaHandler;

public class BookControllerTest {

    private static MicronautLambdaHandler handler;
    private static Context lambdaContext = new MockLambdaContext();
    private static ObjectMapper objectMapper;

    @BeforeAll
    public static void setupSpec() {
        try {
            handler = new MicronautLambdaHandler(); (1)
            objectMapper = handler.getApplicationContext().getBean(ObjectMapper.class);

        } catch (ContainerInitializationException e) {
            e.printStackTrace();
        }
    }

    @AfterAll
    public static void cleanupSpec() {
        handler.getApplicationContext().close(); (2)
    }

    @Test
    void testSaveBook() throws JsonProcessingException {
        Book book = new Book();
        book.setName("Building Microservices");
        String json = objectMapper.writeValueAsString(book);
        AwsProxyRequest request = new AwsProxyRequestBuilder("/", HttpMethod.POST.toString())
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .body(json)
                .build();
        AwsProxyResponse response = handler.handleRequest(request, lambdaContext); (3)
        Assertions.assertEquals(HttpStatus.OK.getCode(), response.getStatusCode());
        BookSaved bookSaved = objectMapper.readValue(response.getBody(), BookSaved.class);
        Assertions.assertEquals(bookSaved.getName(), book.getName());
        Assertions.assertNotNull(bookSaved.getIsbn());
    }
}
1 When you instantiate the Handler, the application context starts.
2 Remember to close your application context when you end your test. You can use your handler to obtain it.
3 You don’t invoke the controller directly. Instead, your handler receives a AWS Proxy Request event which it is routed transparently to your controller.

3 Lambda

3.1 Create Function

Create a Lambda Function. As a runtime, select Custom Runtime

create function

3.2 Upload Code

Micronaut’s eases the deployment of your functions as a Custom AWS Lambda runtime.

The main API you will interact with is AbstractMicronautLambdaRuntime. An abstract class which you can extend to create your custom runtime mainClass. That class includes the necessary code to perform the Processing Tasks described in the Custom Runtime documentation.

bootstrap

We deploy our custom runtime code as a ZIP file. At the root of the ZIP file you need a bootstrap file.

If there’s a file named bootstrap in your deployment package, Lambda executes that file.

The generated application contains a bootstrap bash script:

bootstrap
#!/bin/sh
set -euo pipefail
./complete -Xmx128m -Djava.library.path=$(pwd)

native-image.properties

To generate a GraalVM Native image of the application, we need a native-image.properties file.

src/main/resources/META-INF/native-image/example.micronaut/complete-application/native-image.properties
Args = -H:Name=complete \
       -H:Class=io.micronaut.function.aws.runtime.MicronautLambdaRuntime
  • The H:Class argument defines the main class of your app.

  • The H:Name argument defines the native image name. The Dockerfile references this name.

Dockerfile

The project includes a Dockerfile to generate a GraalVM Native image.

  • Uses the amazonlinux image

  • Builds the JAR of the function.

  • Install the necessary dependencies.

  • Downloads GraalVM community edition

  • Installs native-image utility.

  • With the native-image command and the JAR, generates a GraalVM native image

  • Bundles the native image of our function and the bootstrap file into a ZIP file.

Dockerfile
FROM gradle:6.3.0-jdk11 as builder
COPY --chown=gradle:gradle . /home/application
WORKDIR /home/application
RUN ./gradlew build --no-daemon
FROM amazonlinux:2018.03.0.20191014.0 as graalvm

ENV LANG=en_US.UTF-8

RUN yum install -y gcc gcc-c++ libc6-dev  zlib1g-dev curl bash zlib zlib-devel zip

ENV GRAAL_VERSION 20.1.0
ENV JDK_VERSION java11
ENV GRAAL_FILENAME graalvm-ce-${JDK_VERSION}-linux-amd64-${GRAAL_VERSION}.tar.gz

RUN curl -4 -L https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-${GRAAL_VERSION}/${GRAAL_FILENAME} -o /tmp/${GRAAL_FILENAME}

RUN tar -zxvf /tmp/${GRAAL_FILENAME} -C /tmp \
    && mv /tmp/graalvm-ce-${JDK_VERSION}-${GRAAL_VERSION} /usr/lib/graalvm

RUN rm -rf /tmp/*
CMD ["/usr/lib/graalvm/bin/native-image"]

FROM graalvm
COPY --from=builder /home/application/ /home/application/
WORKDIR /home/application
RUN /usr/lib/graalvm/bin/gu install native-image
RUN /usr/lib/graalvm/bin/native-image --no-server -cp build/libs/complete-*-all.jar
RUN chmod 777 bootstrap
RUN chmod 777 complete
RUN zip -j function.zip bootstrap complete
EXPOSE 8080
ENTRYPOINT ["/home/application/complete"]

The above file references the name used in the native-image.properties file.

deploy.sh

It includes a bash script to generate the ZIP file:

deploy.sh
#!/bin/bash
docker build . -t complete
mkdir -p build
docker run --rm --entrypoint cat complete  /home/application/function.zip > build/function.zip

Upload the file

Execute ./deploy.sh and once you have a ZIP file, upload it

upload function code

3.3 Handler

The handler used is the one created at MicronautLambdaRuntime.

Thus, you don’t need specify the handler in the AWS Lambda console.

However, I like to specify it in the console as well:

io.micronaut.function.aws.proxy.MicronautLambdaHandler

That value is exposed as an environment variable.

handler

3.4 Test

You can test it easily. As Event Template use apigateway-aws-proxy to get you started:

test event

You should see a 200 response:

test result

4 Next Steps

5 Help with Micronaut

Object Computing, Inc. (OCI) sponsored the creation of this Guide. A variety of consulting and support services are available.

OCI is Home to Micronaut.

Meet the Team