Book Image

Serverless Programming Cookbook

By : Heartin Kanikathottu
Book Image

Serverless Programming Cookbook

By: Heartin Kanikathottu

Overview of this book

Managing physical servers will be a thing of the past once you’re able to harness the power of serverless computing. If you’re already prepped with the basics of serverless computing, Serverless Programming Cookbook will help you take the next step ahead. This recipe-based guide provides solutions to problems you might face while building serverless applications. You'll begin by setting up Amazon Web Services (AWS), the primary cloud provider used for most recipes. The next set of recipes will cover various components to build a Serverless application including REST APIs, database, user management, authentication, web hosting, domain registration, DNS management, CDN, messaging, notifications and monitoring. The book also introduces you to the latest technology trends such as Data Streams, Machine Learning and NLP. You will also see patterns and practices for using various services in a real world application. Finally, to broaden your understanding of Serverless computing, you'll also cover getting started guides for other cloud providers such as Azure, Google Cloud Platform and IBM cloud. By the end of this book, you’ll have acquired the skills you need to build serverless applications efficiently using various cloud offerings.
Table of Contents (12 chapters)

Your first AWS Lambda

AWS Lambda is the core service in AWS for building serverless applications. You can run code without provisioning servers. You pay only for the time you run your code, unlike EC2 where you pay for the time the server is up. Lambda also takes care of high availability. You can invoke Lambdas from other AWS services, console, or AWS CLI.

In this recipe, we will create a Lambda in Java and deploy it using the AWS management console. In the next recipe, we will also explore AWS CLI to deploy Lambda. In later recipes and chapters, we will see how we can automate most of the deployment tasks using Amazon CloudWatch templates similar to how most enterprise projects do.

Getting ready

To follow the example in this recipe, you need a working AWS account. You should also set up Java Development Kit (JDK) and Maven in your local machine. I am currently using Java 8 and Maven 3.5.4.

Example projects in this book uses a maven parent project, serverless-cookbook-parent-aws-java.The versions of libraries used within each Lambda project (for example, aws.sdk.version) are defined in the parent project POM file.

If you want to extend any recipe for your particular use case without needing to have the parent project, you can easily get rid of the parent project by moving the required properties and dependencies into the individual projects.

It is a good idea to create a folder within your operating system to manage the code files for this book. I will use a folder with the name serverless. You need to make sure that you can execute the following commands from this folder:

javac -version 
mvn -version

You can set up the parent project inside our parent folder (serverless in my case) by executing the following commands from the command line:

  1. Clone our book's Github repository:
git clone https://github.com/PacktPublishing/Serverless-Programming-Cookbook.git
  1. Go inside the repository folder, go inside our project-specific parent project, and run mvn clean install:
cd Serverless-Programming-Cookbook
cd serverless-cookbook-parent-aws-java
mvn clean install
The code repository of this book already has working code for all the recipes, where applicable. You may also create another folder within the parent folder (serverless is the parent folder in my case) to practice the examples within this book, and look into the code repository files only, when in doubt.

Code repository usage guidelines

Each chapter has a directory of its own (for example, Chapter 01). Inside the chapter's directory there will be sub-directories for each recipe. The recipe specific directory has names corresponding to the recipe's title. For example, the directory for this chapter, recipe titled Your first Lambda is your-first-lambda.

Inside the recipe's directory, there will be a directory for storing all resources including the AWS CLI commands called resources. Long AWS CLI commands are split into multiple lines for better readability using the \ symbol. If you are using a Windows machine you can use the ^ symbol instead of the \ symbol in the code files or make a single line command without the \ symbol.

The recipe's directory also contains a sub-directory for each Lambda project. You need to run mvn clean package for generating the Lambda JAR from within this directory. The Lambda JAR is generated within the target directory inside this directory. Every Lambda project inherits from the common Lambda parent project's directory serverless-cookbook-parent-aws-java and hence needs to be built before any Lambda project, following the steps outlined in the previous section.

Code examples within the book follows the AWS documentation style and is tested primarily on Mac operating system. It should also work on most Unix based operating systems such as Linux. For alternative solutions you may refer to the code files repository. Please refer to the heading Alternative Solutions in the repository's readme file for more details.
Various user specific parameter values such as IDs, AWS account numbers, generated JAR file names etc. given within the examples has to be replaced with valid values based on previous steps executed and your account specific details. Copy pasting and executing the commands without verifying and replacing such parameter values can result in error.

How to do it...

We will create our first Lambda with Java as a Maven project. The javadoc comments and package-info.java files required for checkstyle checks from the parent are not shown here. We are also making use of the Maven shade plugin from the parent for generating the JAR files. You may refer to the code files for each recipe for the complete code:

  1. Create the Java project based on Maven.

Create a Java project based on Maven with our common parent, declared as shown next in the POM file:

You may use an IDE such as Intellij IDEA or Eclipse for working with the examples in this book.
<groupId>tech.heartin.books.serverless-cookbook</groupId>
<artifactId>helloworld-lambda</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>tech.heartin.books.serverlesscookbook</groupId>
<artifactId>serverless-cookbook-parent-aws-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
  1. Also, declare the only dependency we need for our hello world lambda project in the POM file:
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws.lambda.java.core.version}</version
</dependency>
</dependencies>

The dependency versions (for example, aws.lambda.java.core.version) are defined in the POM file for the parent project serverless-cookbook-parent-aws-java.

  1. Create the Lambda handler class and package it as a JAR.

Create a class, HelloWorldLambdaHandler, that implements the interface, RequestHandler:

package tech.heartin.books.serverlesscookbook;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public final class HelloWorldLambdaHandler implements RequestHandler<String, String> {
public String handleRequest(final String s, final Context context) {
context.getLogger().log("input: " + s + "\n");
String greeting = "Hello " + s;
return greeting;
}
}

To package the Lambda as a JAR file, from the project root folder, run the following:

mvn clean package

Two JARS will be created: one with only class files (starting with original-) and an Uber JAR with dependencies (starting with serverless-). You can easily differentiate between one and the other looking at their sizes. We will use the JAR file that starts with original- and that has only the class files for this recipe.

  1. Deploy the Lambda handler to the AWS:
    1. Log in to the AWS console, and go to Lambda dashboard by clicking on Services and searching or selecting Lambda. Currently, it is under the compute category.
    2. Create a Lambda function as follows:
      1. Click on Create Function.
      2. Select Author From Scratch, which is the default.
      3. Give a name, such as myHelloWorldLambda.
      4. Select Java 8 as the runtime.
      5. Under Role, select Create new role from one or more templates.
      6. Give a role name, such as myHelloWorldLambda.
      7. Leave the field for specifying Policy templates blank.
      8. Click on Create Function. You should see a success message after a while.
  2. Upload the Lambda JAR:

Go to the Function code section and do the following:

    1. Select Code entry type as Upload a .zip or .jar file.
    2. Select Java 8 as the runtime.
    3. Specify the fully qualified class name with handler method name as the following: tech.heartin.books.serverlesscookbook.HelloWorldLambdaHandler::handleRequest.
    4. Click on Upload under Function package and select the JAR file. You can select the JAR whose name starts with original-.
    5. Click on Save to save with defaults for other fields.
  1. We can test the uploaded JAR:
    1. Select Configure test events from the Select a test event dropdown next to the Test button.
    2. Select Create new test event.
    3. Give a name for the event: MyHelloWorldTest.
    4. Within the JSON request content area, just specify your name, such as Heartin.
    5. Click on Create. If successful, it will take you to the myHelloWorldLambda function page.
    6. From the myHelloWorldLambda function page, select the test event, MyHelloWorldTest, next to the Test button, and click the Test button.
    7. You should see the message Hello Heartin after expanding the details of execution result.
  1. We can also check the logs printed using context.getLogger().log():
    1. Under the Log output section, you can see the log you printed.
    2. You can also see the log in the CloudWatch service. There should be a Click here link to view the CloudWatch log group. Click on the link, wait or refresh for a stream that matches your invocation time, and click on the stream link to see the log statement within CloudWatch.

How it works...

The following are the in detail information about the role and functionality of Lambda plays and concepts that were introduced in this recipe.

About the parent POM

Example projects in this book use the Maven parent project serverless-cookbook-parent-aws-java that defines the dependency versions for our examples. The actual dependencies are defined within each example project to help you understand the dependencies needed for each use case. All dependency definitions are shown within comments in the parent POM for quick reference.

Our parent project serverless-cookbook-parent-aws-java is also dependent on two open source projects: simple-starter-parent-java for the common Java dependencies, and simple-starter-build-tools for the common build file, such as the code style plugin definitions.

Lambda roles

In this recipe, we selected the Create new role from template(s) and did not select any policy. The basic permissions required (logging to CloudWatch) are added by default. We can also choose an existing role or create a custom role.

Lambda runtimes

AWS Lambda supports various runtimes, such as C# (.NET Core 1.0), C# (.NET Core 2.0), C# (.NET Core 2.1), Go 1.x, Java 8, Node.js 4.3, Node.js 6.10, Node.js 8.10, Python 2.7, and Python 3.6. Inline code editing is only allowed for Node.js and Python.

Extra dependencies

Our parent project, serverless-cookbook-parent-aws-java, defines a few more dependencies than I have. You can download them automatically through Maven (these projects are already available in Maven Central) or set these up manually in your local machine (to examine or modify) by executing the following commands from the command line.

  1. Go inside the parent folder (serverless in my case) and clone the simple-starter-build-tools project:
git clone https://github.com/heartin/simple-starter-build-tools.git
  1. Go inside the project folder and run mvn clean install, as follows:
cd simple-starter-build-tools
mvn clean install
  1. Go back to the parent folder (serverless in my case) and clone the simple-starter-parent-java project:
git clone https://github.com/heartin/simple-starter-parent-java.git
  1. Go inside the project folder and run mvn clean install:
cd simple-starter-parent-java
mvn clean install
For more details on the preceding project dependencies, refer to the respective Readme files.

There's more...

The following are the in detail information about the other ways to create Lambda and to deploy its functions:

Other ways to create Lambda functions from the management console

Apart from the Author from scratch option, we can create Lambdas using Blueprints and Serverless Application Repository. Blueprints allow you to choose a preconfigured template as a starting point. Currently, blueprints are available only for Node.js and Python. Serverless Application Repository allows you to find and deploy Serverless apps developed by developers, companies and partners on AWS.

Other ways to deploy code in a Lambda function

In this recipe, we developed our code outside AWS and uploaded it to our AWS Lambda function as a JAR file. You can also upload the file to Amazon S3 by selecting Code entry type as Upload a file from Amazon S3, and providing the S3 link. For some languages such as Node.js and Python, you can also write the code inline within the Lambda function.

Passing JSON to and from Lambda handler

In this recipe, we passed simple Strings to and from our Lambda handler. We can instead pass a JSON and get back a JSON. To do this, we need to create two POJOs that represent our input and output, and specify them as generic types within our Handler declaration. We will see this approach in the next recipe.

See also