[JAVA] First AWS Lambda (I tried to see what kind of environment it works in)

It was AWS architect training for 3 days from Monday. I was surprised when I first came into contact with Lambda. It is my own summary (for those who know it, I preach to Buddha).

What is Lambda?

I'm ashamed to say that when I heard the word "serverless," it didn't quite come to me. But this is literally right. It doesn't matter what environment the program runs in. It doesn't matter what the OS is, what the middleware is, how much memory is, how much the CPU is, what the NW is, what the topology is, etc. (Actually, you can specify the memory size and respond accordingly. CPU capacity will be allocated). Anyway, the code (program) moves with the "trigger" called "trigger" as a trigger. With Java, the JVM will start up and the uploaded jar will be executed. "Trigger" is highly integrated with AWS services, for example

Is it TDB (Trigger Driven Bean) instead of MDB? It doesn't have to be a bean, so it may be better to call it TDC (Trigger Driven Code).

Try to move

During the training, I had plenty of time for practical training, so I wrote a simple code in Eclipse that was in the training terminal and tried it. Tests can be kicked from the AWS Console, so it's easy to try if you just want to run it without defining a "trigger".

Manners

Basically any Java program will work if you include the necessary libraries, but there seems to be a promise in the method to call. It's an argument. Get ʻObject as the first argument and Contextas the second argument. The method name can be anything. The type can be anything (however, both the first argument and the return type must beSeriarizable`, primitive types are OK).

Specifically, the information from the "trigger" is entered in the first argument. If the trigger is that the message is puted to the queue, you can pass the message itself. If the return value is a synchronous call, it should be almost the same. All you have to do is Serialize and return it according to your interface requirements.

The second argument, Context, is not javax.naming.Context, but com.amazonaws.services.lambda.runtime.Context. So you need to add the AWS-provided jar file (https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core/1.1.0) to your build path. [^ 1] [^ 1]: Eclipse has a AWS toolkit plugin There is, so you can just set up this environment.

create

I don't have the skills or ideas to write meaningful code yet, so I decided to see what kind of environment (system properties, environment variables, passed Context objects) works like an infrastructure shop.

SystemInfo.class


package net.mognet.aws.lambda;

import java.util.Map;
import java.util.Properties;

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

public class SystemInfo {

    public static String printSystemInfo(int i, Context context) {
    		StringBuilder sb = new StringBuilder();
    		//Add header
    		sb.append("name,value\n");
    		
    		//Get system properties
    		Properties prop = System.getProperties();
    		for(Object key : prop.keySet()) {
    			String name = (String) key;
    			String value  = prop.getProperty(name);
    			sb.append(name + "," + value + "\n");
    		}
    		//Get environment variables
    		Map<String, String> env = System.getenv();
    		for(String key : env.keySet()) {
    			String value = env.get(key);
    			sb.append(key + "," + value + "\n");
    		}
    		//Get Context information
    		sb.append("context" + "," + context.toString());
    		return sb.toString();
    }
    
    public static void main(String[] args) {
    		System.out.println(printSystemInfo(1, null));
    }
}

main is for testing. The first argument is supposed to be important, but this time we will not do anything.

Put on

Open the AWS console and create a Lambda function (it works in units called functions. There seems to be a service that orchestrate multiple functions (details not yet investigated)). スクリーンショット 2018-01-31 21.39.16.png Select an appropriate name and runtime (Java8 this time) and press "Create Function". Since the standard output flows to CloudWatch Logs, create a role with Write permission to CloudWatch Logs in advance and attach it here if necessary. スクリーンショット 2018-01-31 21.39.50.png スクリーンショット 2018-01-31 21.39.57.png Normally, you would select a trigger here, but I just want to test it, so I'll just put in the conditions around that. スクリーンショット 2018-01-31 21.40.05.png In the function code, upload the jar file from" Upload ", and the important thing is to enter the method to be executed here in the" Handler ". The format is fixed, and it is the method name with "." Notation and "::" after the full path of the class. This time it will be " net.mognet.aws.lambda.SystemInfo :: printSystemInfo ". I also added environment variables. Once you "save", the file will actually be uploaded. スクリーンショット 2018-01-31 21.41.03.png Next is the preparation for the test. This is a test case (input setting = first argument setting). Select "Test Event Settings" at the top of the screen. スクリーンショット 2018-01-31 21.41.19.png Since the first argument of the method to be executed public static String printSystemInfo is ʻint`, write only 1 to finish. Press "Save" at the bottom. Now you are ready to test.

Let's do it!

Press "Test" as a matter of course. スクリーンショット 2018-01-31 21.42.15.png It worked. Since there is no log output (standard output) this time, I do not see the log, but the start and end messages were displayed. Since the String type method was executed, the return character string is displayed on the screen as it is (I wanted the line feed code to start a new line, but this is the correct way for the execution result display console).

appendix

The execution result is listed in the appendix.

name value
java.runtime.name OpenJDK Runtime Environment
sun.boot.library.path /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/amd64
java.vm.version 25.141-b16
java.vm.vendor Oracle Corporation
java.vendor.url http://java.oracle.com/
path.separator :
java.vm.name OpenJDK 64-Bit Server VM
file.encoding.pkg sun.io
user.country US
sun.java.launcher SUN_STANDARD
sun.os.patch.level unknown
java.vm.specification.name Java Virtual Machine Specification
user.dir /
java.runtime.version 1.8.0_141-b16
java.awt.graphicsenv sun.awt.X11GraphicsEnvironment
java.endorsed.dirs /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/endorsed
os.arch amd64
java.io.tmpdir /tmp
line.separator
java.vm.specification.vendor Oracle Corporation
os.name Linux
sun.jnu.encoding UTF-8
java.library.path /lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
java.specification.name Java Platform API Specification
java.class.version 52.0
sun.management.compiler HotSpot 64-Bit Tiered Compilers
os.version 4.9.77-31.58.amzn1.x86_64
user.home /home/sbx_user1066
user.timezone UTC
java.awt.printerjob sun.print.PSPrinterJob
file.encoding UTF-8
java.specification.version 1.8
java.class.path /var/runtime/lib/LambdaJavaRTEntry-1.0.jar
user.name sbx_user1066
java.vm.specification.version 1.8
sun.java.command /var/runtime/lib/LambdaJavaRTEntry-1.0.jar
java.home /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre
sun.arch.data.model 64
user.language en
java.specification.vendor Oracle Corporation
awt.toolkit sun.awt.X11.XToolkit
java.vm.info mixed mode, sharing
java.version 1.8.0_141
java.ext.dirs /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/ext:/usr/java/packages/lib/ext
sun.boot.class.path /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/resources.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/rt.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/jsse.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/jce.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/charsets.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/lib/jfr.jar:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.32.amzn1.x86_64/jre/classes
java.vendor Oracle Corporation
file.separator /
java.vendor.url.bug http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding UnicodeLittle
sun.cpu.endian little
sun.cpu.isalist
PATH /usr/local/bin:/usr/bin/:/bin
_AWS_XRAY_DAEMON_ADDRESS 169.254.79.2
LAMBDA_TASK_ROOT /var/task
AWS_LAMBDA_FUNCTION_MEMORY_SIZE 128
TZ :UTC
AWS_SECRET_ACCESS_KEY secret
AWS_EXECUTION_ENV AWS_Lambda_java8
AWS_DEFAULT_REGION ap-northeast-1
AWS_LAMBDA_LOG_GROUP_NAME /aws/lambda/SystemInfo
XFILESEARCHPATH /usr/dt/app-defaults/%L/Dt
_HANDLER net.mognet.aws.lambda.SystemInfo::printSystemInfo
LANG en_US.UTF-8
LAMBDA_RUNTIME_DIR /var/runtime
AWS_SESSION_TOKEN tokenString
AWS_ACCESS_KEY_ID accessKeyId
LD_LIBRARY_PATH /lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib
_X_AMZN_TRACE_ID Root=1-5a71b98c-393aaa7b51f5612a348586c0;Parent=3ff8164301e3ccd4;Sampled=0
AWS_SECRET_KEY secretKey
hogehoge gehogeho
AWS_REGION ap-northeast-1
AWS_LAMBDA_LOG_STREAM_NAME 2018/01/31/[$LATEST]29640ec0ac8e426ab2b0a041b3a1b1f4
AWS_XRAY_DAEMON_ADDRESS 169.254.79.2:2000
_AWS_XRAY_DAEMON_PORT 2000
NLSPATH /usr/dt/lib/nls/msg/%L/%N.cat
AWS_XRAY_CONTEXT_MISSING LOG_ERROR
AWS_LAMBDA_FUNCTION_VERSION $LATEST
AWS_ACCESS_KEY accessKey
AWS_LAMBDA_FUNCTION_NAME SystemInfo
context lambdainternal.api.LambdaContext@604ed9f0

Information such as the access key was also included in the environment variables, so I masked it. It may be necessary to understand that it is such a specification. Is it possible to call the AWS API using the keys around here? Also, the environment variables that have been set properly are also shown (obviously). It looks like it's running on OpenJDK on Amazon Linux. I don't know what will happen to this when it actually goes live. It's just that this was the case when this test was run. After all, it's serverless, so again, the execution environment (HW, OS, MW, etc.) doesn't matter. Rather, I realized that Lambda-like usage is to write the code on the assumption that it doesn't matter.

reference

Lambda Function Handler (Java) --AWS Lambda

Recommended Posts

First AWS Lambda (I tried to see what kind of environment it works in)
I tried to visualize the access of Lambda → Athena with AWS X-Ray
I tried to find out what changed in Java 9
I tried to build the environment of WSL2 + Docker + VSCode
I tried to make a client of RESAS-API in Java
I tried to develop the cache function of Application Container Cloud Service in the local environment
I tried to summarize the words that I often see in docker-compose.yml
I tried to implement Ajax processing of like function in Rails
Examine the system information of AWS Lambda operating environment in Java
I tried to build the environment of PlantUML Server with Docker
I tried to make a parent class of a value object in Ruby
I tried to build a Firebase application development environment with Docker in 2020
I tried to make full use of the CPU core in Ruby
I tried to summarize Java lambda expressions
What is Docker? I tried to summarize
Delegated type added in Rails 6.1 and Union types of GraphQL seem to be compatible, so I tried it
What I tried when I wanted to get all the fields of a bean
I didn't know what to write in Maven's scope so I looked it up
Retrieve the first day of week in current locale (what day of the week is it today?)
I tried to implement polymorphic related in Nogizaka.
I tried to chew C # (basic of encapsulation)
[Must see !!!] I tried to summarize object orientation!
I tried to output multiplication table in Java
I tried to build Micra mackerel in 1 hour!
I tried to develop an application in 2 languages
I tried to create Alexa skill in Java
Summary of what I learned in Spring Batch
I want to ESLint in Maven project. I want to run Node.js without putting it in my environment.
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver
I tried using Docker because I don't want to pollute the local environment in Microsoft Teams tab development of MS Learn
I tried to explain what you can do in a popular language for web development from a beginner's point of view.
I tried what I wanted to try with Stream softly.
AWS Lambda supports container images so I tried Puppeteer
I tried to implement Firebase push notification in Java
I tried to summarize the state transition of docker
I tried to operate SQS using AWS Java SDK
05. I tried to stub the source of Spring Boot
I tried to integrate AWS I oT button and Slack
I tried to reduce the capacity of Spring Boot
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to implement the Euclidean algorithm in Java
~ I tried to learn functional programming in Java now ~
roman numerals (I tried to simplify it with hash)
I tried to build an environment using Docker (beginner)
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
[SwiftUI] I tried to find out how it changes for each specified location of background
I want to recreate the contents of assets from scratch in the environment built with capistrano