diff --git a/multi/multi__deploying_a_packaged_function.html b/multi/multi__deploying_a_packaged_function.html index fe7fe76c0..b54584179 100644 --- a/multi/multi__deploying_a_packaged_function.html +++ b/multi/multi__deploying_a_packaged_function.html @@ -1,3 +1,3 @@ - 9. Deploying a Packaged Function

9. Deploying a Packaged Function

Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library).

The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by default).

\ No newline at end of file + 8. Deploying a Packaged Function

8. Deploying a Packaged Function

Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library).

The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault).

\ No newline at end of file diff --git a/multi/multi__introduction.html b/multi/multi__introduction.html index 1a3f5cb63..c73a3e044 100644 --- a/multi/multi__introduction.html +++ b/multi/multi__introduction.html @@ -1,6 +1,6 @@ - 1. Introduction

1. Introduction

Spring Cloud Function is a project with the following high-level goals:

It abstracts away all of the transport details and + 1. Introduction

1. Introduction

Spring Cloud Function is a project with the following high-level goals:

  • Promote the implementation of business logic via functions.
  • Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task.
  • Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS).
  • Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers.

It abstracts away all of the transport details and infrastructure, allowing the developer to keep all the familiar tools and processes, and focus firmly on business logic.

Here’s a complete, executable, testable Spring Boot application (implementing a simple string manipulation):

@SpringBootApplication
diff --git a/multi/multi__serverless_platform_adapters.html b/multi/multi__serverless_platform_adapters.html
index 3bb77b75c..429b98714 100644
--- a/multi/multi__serverless_platform_adapters.html
+++ b/multi/multi__serverless_platform_adapters.html
@@ -1,11 +1,58 @@
 
       
-   8. Serverless Platform Adapters

8. Serverless Platform Adapters

As well as being able to run as a standalone process, a Spring Cloud + 9. Serverless Platform Adapters

9. Serverless Platform Adapters

As well as being able to run as a standalone process, a Spring Cloud Function application can be adapted to run one of the existing -servlerless platforms. In the project there are adapters for +serverless platforms. In the project there are adapters for AWS Lambda, Azure, and Apache -OpenWhisk. The Oracle Fn platform has its own Spring Cloud Function adapter.

\ No newline at end of file +OpenWhisk. The Oracle Fn platform +has its own Spring Cloud Function adapter. And +Riff supports Java functions and its +Java Function +Invoker acts natively is an adapter for Spring Cloud Function jars.

9.1 AWS Lambda

The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda.

9.1.1 Introduction

The adapter has a couple of generic request handlers that you can use. The most generic is SpringBootStreamHandler, which uses a Jackson ObjectMapper provided by Spring Boot to serialize and deserialize the objects in the function. There is also a SpringBootRequestHandler which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself).

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name (e.g. as FUNCTION_NAME environment variable in AWS). The functions are extracted from the Spring Cloud FunctionCatalog (searching first for Function then Consumer and finally Supplier).

9.1.2 Notes on JAR Layout

You don’t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might need to exclude those before you create the JAR you send to AWS. A Lambda application has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample). The sample app creates 2 jar files, one with an aws classifier for deploying in Lambda, and one executable (thin) jar that includes spring-cloud-function-web at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file manifest, using the Start-Class attribute (which will be added for you by the Spring Boot tooling if you use the starter parent). If there is no Start-Class in your manifest you can use an environment variable MAIN_CLASS when you deploy the function to AWS.

9.1.3 Upload

Build the sample under spring-cloud-function-samples/function-sample-aws and upload the -aws jar file to Lambda. The handler can be example.Handler or org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler (FQN of the class, not a method reference, although Lambda does accept method references).

./mvnw -U clean package

Using the AWS command line tools it looks like this:

aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-1.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish

The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it:

{
+  "value": "test"
+}

9.2 Azure Functions

The Azure adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The Spring Cloud Function Azure adapter trades the convenience of these annotations for portability of the function implementations. Instead of using the annotations you have to write some JSON by hand (at least for now) to guide the platform to call the right methods in the adapter.

The adapter has a generic http request handler that you can use. +There is a AzureSpringBootRequestHandler which you must extend, and provide the input and output types as type parameters (enabling Azure to inspect the class and do the JSON conversions itself).

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name. +The functions are extracted from the Spring Cloud FunctionCatalog.

9.2.1 Notes on JAR Layout

You don’t need the Spring Cloud Function Web at runtime in Azure, so you need to exclude this before you create the JAR you deploy to Azure. +A function application on Azure has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample here). +The sample app creates the shaded jar file, with an azure classifier for deploying in Azure.

9.2.2 JSON Configuration

The Azure tooling needs to find some JSON configuration files to tell it how to deploy and integrate the function (e.g. which Java class to use as the entry point, and which triggers to use). Those files can be created with the Maven plugin for a non-Spring function, but the tooling doesn’t work yet with the adapter in its current form. There is an example function.json in the sample which hooks the function up as an HTTP endpoint:

{
+  "scriptFile" : "../function-sample-azure-1.0.0.BUILD-SNAPSHOT-azure.jar",
+  "entryPoint" : "example.FooHandler.execute",
+  "bindings" : [ {
+    "type" : "httpTrigger",
+    "name" : "foo",
+    "direction" : "in",
+    "authLevel" : "anonymous",
+    "methods" : [ "get", "post" ]
+  }, {
+    "type" : "http",
+    "name" : "$return",
+    "direction" : "out"
+  } ],
+  "disabled" : false
+}

9.2.3 Build

./mvnw -U clean package

9.2.4 Running the sample

You can run the sample locally, just like the other Spring Cloud Function samples:

and curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'.

You will need the az CLI app and some node.js fu (see https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven for more detail). To deploy the function on Azure runtime:

$ az login
+$ mvn azure-functions:deploy

On another terminal try this: curl https://<azure-function-url-from-the-log>/api/uppercase -d '{"value": "hello foobar!"}'. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run").

The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below:

{
+  "value": "foobar"
+}

9.3 Apache Openwhisk

The OpenWhisk adapter is in the form of an executable jar that can be used in a a docker image to be deployed to Openwhisk. The platform works in request-response mode, listening on port 8080 on a specific endpoint, so the adapter is a simple Spring MVC application.

9.3.1 Quick Start

Implement a POF (be sure to use the functions package):

package functions;
+
+import java.util.function.Function;
+
+public class Uppercase implements Function<String, String> {
+
+	public String apply(String input) {
+		return input.toUpperCase();
+	}
+}

Install it into your local Maven repository:

./mvnw clean install

Create a function.properties file that provides its Maven coordinates. For example:

dependencies.function: com.example:pof:0.0.1-SNAPSHOT

Copy the openwhisk runner JAR to the working directory (same directory as the properties file):

cp spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk/target/spring-cloud-function-adapter-openwhisk-1.0.0.BUILD-SNAPSHOT.jar runner.jar

Generate a m2 repo from the --thin.dryrun of the runner JAR with the above properties file:

java -jar -Dthin.root=m2 runner.jar --thin.name=function --thin.dryrun

Use the following Dockerfile:

FROM openjdk:8-jdk-alpine
+VOLUME /tmp
+COPY m2 /m2
+ADD runner.jar .
+ADD function.properties .
+ENV JAVA_OPTS=""
+ENTRYPOINT [ "java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "runner.jar", "--thin.root=/m2", "--thin.name=function", "--function.name=uppercase"]
+EXPOSE 8080
[Note]Note

you could use a Spring Cloud Function app, instead of just a jar with a POF in it, in which case you would have to change the way the app runs in the container so that it picks up the main class as a source file. For example, you could change the ENTRYPOINT above and add --spring.main.sources=com.example.SampleApplication.

Build the Docker image:

docker build -t [username/appname] .

Push the Docker image:

docker push [username/appname]

Use the OpenWhisk CLI (e.g. after vagrant ssh) to create the action:

wsk action create example --docker [username/appname]

Invoke the action:

wsk action invoke example --result --param payload foo
+{
+    "result": "FOO"
+}
\ No newline at end of file diff --git a/multi/multi__standalone_streaming_applications.html b/multi/multi__standalone_streaming_applications.html index a95b3741a..a29d6d34f 100644 --- a/multi/multi__standalone_streaming_applications.html +++ b/multi/multi__standalone_streaming_applications.html @@ -1,3 +1,3 @@ - 7. Standalone Streaming Applications

7. Standalone Streaming Applications

To send or receive messages from a broker (such as RabbitMQ or Kafka) you can use the spring-cloud-function-stream adapter. Add the adapter to your classpath along with the appropriate binder from Spring Cloud Stream. The adapter will bind to the message broker as a Processor (input and output streams) unless the user explicitly disables one or the other using spring.cloud.function.stream.{source,sink}.enabled=false.

An incoming message is routed to a function (or consumer). If there is only one, then the choice is obvious. If there are multiple functions that can accept an incoming message, the message is inspected to see if there is a stream_routekey header containing the name of a function. Routing headers or function names can be composed using a comma- or pipe-separated name. The header is also added to outgoing messages from a supplier. Messages with no route key can be routed exclusively to a function or consumer by specifying spring.cloud.function.stream.{processor,sink}.name. If a single function cannot be identified to process an incoming message there will be an error, unless you set spring.cloud.function.stream.shared=true, in which case such messages will be sent to all compatible functions. A single supplier can be chosen for output messages from a supplier (if more than one is available) using the spring.cloud.function.stream.source.name.

[Note]Note

some binders will fail on startup if the message broker is not available and the function catalog contains suppliers that immediately produce messages when accessed. You can switch off the automatic publishing from suppliers on startup using the spring.cloud.function.strean.supplier.enabled=false flag.

\ No newline at end of file + 7. Standalone Streaming Applications

7. Standalone Streaming Applications

To send or receive messages from a broker (such as RabbitMQ or Kafka) you can use the spring-cloud-function-stream adapter. Add the adapter to your classpath along with the appropriate binder from Spring Cloud Stream. The adapter will bind to the message broker as a Processor (input and output streams) unless the user explicitly disables one or the other using spring.cloud.function.stream.{source,sink}.enabled=false.

An incoming message is routed to a function (or consumer). If there is only one, then the choice is obvious. If there are multiple functions that can accept an incoming message, the message is inspected to see if there is a stream_routekey header containing the name of a function. Routing headers or function names can be composed using a comma- or pipe-separated name. The header is also added to outgoing messages from a supplier. Messages with no route key can be routed exclusively to a function or consumer by specifying spring.cloud.function.stream.{processor,sink}.name. If a single function cannot be identified to process an incoming message there will be an error, unless you set spring.cloud.function.stream.shared=true, in which case such messages will be sent to all compatible functions. A single supplier can be chosen for output messages from a supplier (if more than one is available) using the spring.cloud.function.stream.source.name.

[Note]Note

some binders will fail on startup if the message broker is not available and the function catalog contains suppliers that immediately produce messages when accessed. You can switch off the automatic publishing from suppliers on startup using the spring.cloud.function.strean.supplier.enabled=false flag.

\ No newline at end of file diff --git a/multi/multi_spring-cloud-function.html b/multi/multi_spring-cloud-function.html index ebab20a5c..685ddfc27 100644 --- a/multi/multi_spring-cloud-function.html +++ b/multi/multi_spring-cloud-function.html @@ -1,3 +1,3 @@ - Spring Cloud Function \ No newline at end of file + Spring Cloud Function \ No newline at end of file diff --git a/single/spring-cloud-function.html b/single/spring-cloud-function.html index 5b8cd07d2..a4502f2d5 100644 --- a/single/spring-cloud-function.html +++ b/single/spring-cloud-function.html @@ -1,6 +1,6 @@ - Spring Cloud Function

Spring Cloud Function


Mark Fisher, Dave Syer

1. Introduction

Spring Cloud Function is a project with the following high-level goals:

  • Promote the implementation of business logic via functions.
  • Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task.
  • Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS).
  • Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers.

It abstracts away all of the transport details and + Spring Cloud Function

Spring Cloud Function


Mark Fisher, Dave Syer

1. Introduction

Spring Cloud Function is a project with the following high-level goals:

  • Promote the implementation of business logic via functions.
  • Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task.
  • Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS).
  • Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers.

It abstracts away all of the transport details and infrastructure, allowing the developer to keep all the familiar tools and processes, and focus firmly on business logic.

Here’s a complete, executable, testable Spring Boot application (implementing a simple string manipulation):

@SpringBootApplication
@@ -97,12 +97,59 @@ getting started experience.

With the web configurations activated your app endpoint (on "/" by default, but configurable with spring.cloud.function.web.path) that can be used to access the functions in the application context. The supported content types are -plain text and JSON.

MethodPathRequestResponseStatus

GET

/{supplier}

-

Items from the named supplier

200 OK

POST

/{consumer}

JSON object or text

Mirrors input and pushes request body into consumer

202 Accepted

POST

/{consumer}

JSON array or text with new lines

Mirrors input and pushes body into consumer one by one

202 Accepted

POST

/{function}

JSON object or text

The result of applying the named function

200 OK

POST

/{function}

JSON array or text with new lines

The result of applying the named function

200 OK

GET

/{function}/{item}

-

Convert the item into an object and return the result of applying the function

200 OK

As the table above shows the behaviour of the endpoint depends on the method and also the type of incoming request data. When the incoming data is single valued, and the target function is declared as obviously single valued (i.e. not returning a collection or Flux), then the response will also contain a single value. For multi-valued responses the client can ask for a server-sent event stream by sending `Accept: text/event-stream". If there is only one function (consumer etc.) then the name in the path is optional. Composite functions can be addressed using pipes or commas to separate function names (pipes are legal in URL paths, but a bit awkward to type on the command line).

Functions and consumers that are declared with input and output in Message<?> will see the request headers on the input messages, and the output message headers will be converted to HTTP headers.

When POSTing text the response format might be different with Spring Boot 2.0 and older versions, depending on the content negotiation (provide content type and accpt headers for the best results).

7. Standalone Streaming Applications

To send or receive messages from a broker (such as RabbitMQ or Kafka) you can use the spring-cloud-function-stream adapter. Add the adapter to your classpath along with the appropriate binder from Spring Cloud Stream. The adapter will bind to the message broker as a Processor (input and output streams) unless the user explicitly disables one or the other using spring.cloud.function.stream.{source,sink}.enabled=false.

An incoming message is routed to a function (or consumer). If there is only one, then the choice is obvious. If there are multiple functions that can accept an incoming message, the message is inspected to see if there is a stream_routekey header containing the name of a function. Routing headers or function names can be composed using a comma- or pipe-separated name. The header is also added to outgoing messages from a supplier. Messages with no route key can be routed exclusively to a function or consumer by specifying spring.cloud.function.stream.{processor,sink}.name. If a single function cannot be identified to process an incoming message there will be an error, unless you set spring.cloud.function.stream.shared=true, in which case such messages will be sent to all compatible functions. A single supplier can be chosen for output messages from a supplier (if more than one is available) using the spring.cloud.function.stream.source.name.

[Note]Note

some binders will fail on startup if the message broker is not available and the function catalog contains suppliers that immediately produce messages when accessed. You can switch off the automatic publishing from suppliers on startup using the spring.cloud.function.strean.supplier.enabled=false flag.

8. Serverless Platform Adapters

As well as being able to run as a standalone process, a Spring Cloud +plain text and JSON.

MethodPathRequestResponseStatus

GET

/{supplier}

-

Items from the named supplier

200 OK

POST

/{consumer}

JSON object or text

Mirrors input and pushes request body into consumer

202 Accepted

POST

/{consumer}

JSON array or text with new lines

Mirrors input and pushes body into consumer one by one

202 Accepted

POST

/{function}

JSON object or text

The result of applying the named function

200 OK

POST

/{function}

JSON array or text with new lines

The result of applying the named function

200 OK

GET

/{function}/{item}

-

Convert the item into an object and return the result of applying the function

200 OK

As the table above shows the behaviour of the endpoint depends on the method and also the type of incoming request data. When the incoming data is single valued, and the target function is declared as obviously single valued (i.e. not returning a collection or Flux), then the response will also contain a single value. For multi-valued responses the client can ask for a server-sent event stream by sending `Accept: text/event-stream". If there is only one function (consumer etc.) then the name in the path is optional. Composite functions can be addressed using pipes or commas to separate function names (pipes are legal in URL paths, but a bit awkward to type on the command line).

Functions and consumers that are declared with input and output in Message<?> will see the request headers on the input messages, and the output message headers will be converted to HTTP headers.

When POSTing text the response format might be different with Spring Boot 2.0 and older versions, depending on the content negotiation (provide content type and accpt headers for the best results).

7. Standalone Streaming Applications

To send or receive messages from a broker (such as RabbitMQ or Kafka) you can use the spring-cloud-function-stream adapter. Add the adapter to your classpath along with the appropriate binder from Spring Cloud Stream. The adapter will bind to the message broker as a Processor (input and output streams) unless the user explicitly disables one or the other using spring.cloud.function.stream.{source,sink}.enabled=false.

An incoming message is routed to a function (or consumer). If there is only one, then the choice is obvious. If there are multiple functions that can accept an incoming message, the message is inspected to see if there is a stream_routekey header containing the name of a function. Routing headers or function names can be composed using a comma- or pipe-separated name. The header is also added to outgoing messages from a supplier. Messages with no route key can be routed exclusively to a function or consumer by specifying spring.cloud.function.stream.{processor,sink}.name. If a single function cannot be identified to process an incoming message there will be an error, unless you set spring.cloud.function.stream.shared=true, in which case such messages will be sent to all compatible functions. A single supplier can be chosen for output messages from a supplier (if more than one is available) using the spring.cloud.function.stream.source.name.

[Note]Note

some binders will fail on startup if the message broker is not available and the function catalog contains suppliers that immediately produce messages when accessed. You can switch off the automatic publishing from suppliers on startup using the spring.cloud.function.strean.supplier.enabled=false flag.

8. Deploying a Packaged Function

Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library).

The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault).

9. Serverless Platform Adapters

As well as being able to run as a standalone process, a Spring Cloud Function application can be adapted to run one of the existing -servlerless platforms. In the project there are adapters for +serverless platforms. In the project there are adapters for AWS Lambda, Azure, and Apache -OpenWhisk. The Oracle Fn platform has its own Spring Cloud Function adapter.

9. Deploying a Packaged Function

Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library).

The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by default).

\ No newline at end of file +OpenWhisk. The Oracle Fn platform +has its own Spring Cloud Function adapter. And +Riff supports Java functions and its +Java Function +Invoker acts natively is an adapter for Spring Cloud Function jars.

9.1 AWS Lambda

The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda.

9.1.1 Introduction

The adapter has a couple of generic request handlers that you can use. The most generic is SpringBootStreamHandler, which uses a Jackson ObjectMapper provided by Spring Boot to serialize and deserialize the objects in the function. There is also a SpringBootRequestHandler which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself).

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name (e.g. as FUNCTION_NAME environment variable in AWS). The functions are extracted from the Spring Cloud FunctionCatalog (searching first for Function then Consumer and finally Supplier).

9.1.2 Notes on JAR Layout

You don’t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might need to exclude those before you create the JAR you send to AWS. A Lambda application has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample). The sample app creates 2 jar files, one with an aws classifier for deploying in Lambda, and one executable (thin) jar that includes spring-cloud-function-web at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file manifest, using the Start-Class attribute (which will be added for you by the Spring Boot tooling if you use the starter parent). If there is no Start-Class in your manifest you can use an environment variable MAIN_CLASS when you deploy the function to AWS.

9.1.3 Upload

Build the sample under spring-cloud-function-samples/function-sample-aws and upload the -aws jar file to Lambda. The handler can be example.Handler or org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler (FQN of the class, not a method reference, although Lambda does accept method references).

./mvnw -U clean package

Using the AWS command line tools it looks like this:

aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-1.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish

The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it:

{
+  "value": "test"
+}

9.2 Azure Functions

The Azure adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The Spring Cloud Function Azure adapter trades the convenience of these annotations for portability of the function implementations. Instead of using the annotations you have to write some JSON by hand (at least for now) to guide the platform to call the right methods in the adapter.

The adapter has a generic http request handler that you can use. +There is a AzureSpringBootRequestHandler which you must extend, and provide the input and output types as type parameters (enabling Azure to inspect the class and do the JSON conversions itself).

If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name. +The functions are extracted from the Spring Cloud FunctionCatalog.

9.2.1 Notes on JAR Layout

You don’t need the Spring Cloud Function Web at runtime in Azure, so you need to exclude this before you create the JAR you deploy to Azure. +A function application on Azure has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample here). +The sample app creates the shaded jar file, with an azure classifier for deploying in Azure.

9.2.2 JSON Configuration

The Azure tooling needs to find some JSON configuration files to tell it how to deploy and integrate the function (e.g. which Java class to use as the entry point, and which triggers to use). Those files can be created with the Maven plugin for a non-Spring function, but the tooling doesn’t work yet with the adapter in its current form. There is an example function.json in the sample which hooks the function up as an HTTP endpoint:

{
+  "scriptFile" : "../function-sample-azure-1.0.0.BUILD-SNAPSHOT-azure.jar",
+  "entryPoint" : "example.FooHandler.execute",
+  "bindings" : [ {
+    "type" : "httpTrigger",
+    "name" : "foo",
+    "direction" : "in",
+    "authLevel" : "anonymous",
+    "methods" : [ "get", "post" ]
+  }, {
+    "type" : "http",
+    "name" : "$return",
+    "direction" : "out"
+  } ],
+  "disabled" : false
+}

9.2.3 Build

./mvnw -U clean package

9.2.4 Running the sample

You can run the sample locally, just like the other Spring Cloud Function samples:

and curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'.

You will need the az CLI app and some node.js fu (see https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven for more detail). To deploy the function on Azure runtime:

$ az login
+$ mvn azure-functions:deploy

On another terminal try this: curl https://<azure-function-url-from-the-log>/api/uppercase -d '{"value": "hello foobar!"}'. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run").

The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below:

{
+  "value": "foobar"
+}

9.3 Apache Openwhisk

The OpenWhisk adapter is in the form of an executable jar that can be used in a a docker image to be deployed to Openwhisk. The platform works in request-response mode, listening on port 8080 on a specific endpoint, so the adapter is a simple Spring MVC application.

9.3.1 Quick Start

Implement a POF (be sure to use the functions package):

package functions;
+
+import java.util.function.Function;
+
+public class Uppercase implements Function<String, String> {
+
+	public String apply(String input) {
+		return input.toUpperCase();
+	}
+}

Install it into your local Maven repository:

./mvnw clean install

Create a function.properties file that provides its Maven coordinates. For example:

dependencies.function: com.example:pof:0.0.1-SNAPSHOT

Copy the openwhisk runner JAR to the working directory (same directory as the properties file):

cp spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk/target/spring-cloud-function-adapter-openwhisk-1.0.0.BUILD-SNAPSHOT.jar runner.jar

Generate a m2 repo from the --thin.dryrun of the runner JAR with the above properties file:

java -jar -Dthin.root=m2 runner.jar --thin.name=function --thin.dryrun

Use the following Dockerfile:

FROM openjdk:8-jdk-alpine
+VOLUME /tmp
+COPY m2 /m2
+ADD runner.jar .
+ADD function.properties .
+ENV JAVA_OPTS=""
+ENTRYPOINT [ "java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "runner.jar", "--thin.root=/m2", "--thin.name=function", "--function.name=uppercase"]
+EXPOSE 8080
[Note]Note

you could use a Spring Cloud Function app, instead of just a jar with a POF in it, in which case you would have to change the way the app runs in the container so that it picks up the main class as a source file. For example, you could change the ENTRYPOINT above and add --spring.main.sources=com.example.SampleApplication.

Build the Docker image:

docker build -t [username/appname] .

Push the Docker image:

docker push [username/appname]

Use the OpenWhisk CLI (e.g. after vagrant ssh) to create the action:

wsk action create example --docker [username/appname]

Invoke the action:

wsk action invoke example --result --param payload foo
+{
+    "result": "FOO"
+}
\ No newline at end of file diff --git a/spring-cloud-function.xml b/spring-cloud-function.xml index 0c56032f6..655839b3e 100644 --- a/spring-cloud-function.xml +++ b/spring-cloud-function.xml @@ -16,16 +16,16 @@ Spring Cloud Function is a project with the following high-level goals: -Promote the implementation of business logic via functions. +Promote the implementation of business logic via functions. -Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task. +Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task. -Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS). +Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS). -Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers. +Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers. It abstracts away all of the transport details and @@ -352,21 +352,153 @@ plain text and JSON. some binders will fail on startup if the message broker is not available and the function catalog contains suppliers that immediately produce messages when accessed. You can switch off the automatic publishing from suppliers on startup using the spring.cloud.function.strean.supplier.enabled=false flag. + +Deploying a Packaged Function +Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library). +The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault). + Serverless Platform Adapters As well as being able to run as a standalone process, a Spring Cloud Function application can be adapted to run one of the existing -servlerless platforms. In the project there are adapters for +serverless platforms. In the project there are adapters for AWS Lambda, Azure, and Apache -OpenWhisk. The Oracle Fn platform has its own Spring Cloud Function adapter. - - -Deploying a Packaged Function -Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the Riff Java function invoker uses this library). -The standard entry point of the API is the Spring configuration annotation @EnableFunctionDeployer. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a function.location which is a URL or resource location for the archive containing the functions. It can optionally use a maven: prefix to locate the artifact via a dependency lookup (see FunctionProperties for complete details). A Spring Boot application is bootstrapped from the jar file, using the MANIFEST.MF to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application’s FunctionCatalog. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by default). +OpenWhisk. The Oracle Fn platform +has its own Spring Cloud Function adapter. And +Riff supports Java functions and its +Java Function +Invoker acts natively is an adapter for Spring Cloud Function jars. +
+AWS Lambda +The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda. +
+Introduction +The adapter has a couple of generic request handlers that you can use. The most generic is SpringBootStreamHandler, which uses a Jackson ObjectMapper provided by Spring Boot to serialize and deserialize the objects in the function. There is also a SpringBootRequestHandler which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself). +If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name (e.g. as FUNCTION_NAME environment variable in AWS). The functions are extracted from the Spring Cloud FunctionCatalog (searching first for Function then Consumer and finally Supplier). +
+
+Notes on JAR Layout +You don’t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might need to exclude those before you create the JAR you send to AWS. A Lambda application has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample). The sample app creates 2 jar files, one with an aws classifier for deploying in Lambda, and one executable (thin) jar that includes spring-cloud-function-web at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file manifest, using the Start-Class attribute (which will be added for you by the Spring Boot tooling if you use the starter parent). If there is no Start-Class in your manifest you can use an environment variable MAIN_CLASS when you deploy the function to AWS. +
+
+Upload +Build the sample under spring-cloud-function-samples/function-sample-aws and upload the -aws jar file to Lambda. The handler can be example.Handler or org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler (FQN of the class, not a method reference, although Lambda does accept method references). +./mvnw -U clean package +Using the AWS command line tools it looks like this: +aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-1.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish +The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it: +{ + "value": "test" +} +
+
+
+Azure Functions +The Azure adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The Spring Cloud Function Azure adapter trades the convenience of these annotations for portability of the function implementations. Instead of using the annotations you have to write some JSON by hand (at least for now) to guide the platform to call the right methods in the adapter. +The adapter has a generic http request handler that you can use. +There is a AzureSpringBootRequestHandler which you must extend, and provide the input and output types as type parameters (enabling Azure to inspect the class and do the JSON conversions itself). +If your app has more than one @Bean of type Function etc. then you can choose the one to use by configuring function.name. +The functions are extracted from the Spring Cloud FunctionCatalog. +
+Notes on JAR Layout +You don’t need the Spring Cloud Function Web at runtime in Azure, so you need to exclude this before you create the JAR you deploy to Azure. +A function application on Azure has to be shaded, but a Spring Boot standalone application does not, so you can run the same app using 2 separate jars (as per the sample here). +The sample app creates the shaded jar file, with an azure classifier for deploying in Azure. +
+
+JSON Configuration +The Azure tooling needs to find some JSON configuration files to tell it how to deploy and integrate the function (e.g. which Java class to use as the entry point, and which triggers to use). Those files can be created with the Maven plugin for a non-Spring function, but the tooling doesn’t work yet with the adapter in its current form. There is an example function.json in the sample which hooks the function up as an HTTP endpoint: +{ + "scriptFile" : "../function-sample-azure-1.0.0.BUILD-SNAPSHOT-azure.jar", + "entryPoint" : "example.FooHandler.execute", + "bindings" : [ { + "type" : "httpTrigger", + "name" : "foo", + "direction" : "in", + "authLevel" : "anonymous", + "methods" : [ "get", "post" ] + }, { + "type" : "http", + "name" : "$return", + "direction" : "out" + } ], + "disabled" : false +} +
+
+Build +./mvnw -U clean package +
+
+Running the sample +You can run the sample locally, just like the other Spring Cloud Function samples: + + +and curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'. +You will need the az CLI app and some node.js fu (see https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven for more detail). To deploy the function on Azure runtime: +$ az login +$ mvn azure-functions:deploy +On another terminal try this: curl https://<azure-function-url-from-the-log>/api/uppercase -d '{"value": "hello foobar!"}'. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run"). +The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below: +{ + "value": "foobar" +} +
+
+
+Apache Openwhisk +The OpenWhisk adapter is in the form of an executable jar that can be used in a a docker image to be deployed to Openwhisk. The platform works in request-response mode, listening on port 8080 on a specific endpoint, so the adapter is a simple Spring MVC application. +
+Quick Start +Implement a POF (be sure to use the functions package): +package functions; + +import java.util.function.Function; + +public class Uppercase implements Function<String, String> { + + public String apply(String input) { + return input.toUpperCase(); + } +} +Install it into your local Maven repository: +./mvnw clean install +Create a function.properties file that provides its Maven coordinates. For example: +dependencies.function: com.example:pof:0.0.1-SNAPSHOT +Copy the openwhisk runner JAR to the working directory (same directory as the properties file): +cp spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk/target/spring-cloud-function-adapter-openwhisk-1.0.0.BUILD-SNAPSHOT.jar runner.jar +Generate a m2 repo from the --thin.dryrun of the runner JAR with the above properties file: +java -jar -Dthin.root=m2 runner.jar --thin.name=function --thin.dryrun +Use the following Dockerfile: +FROM openjdk:8-jdk-alpine +VOLUME /tmp +COPY m2 /m2 +ADD runner.jar . +ADD function.properties . +ENV JAVA_OPTS="" +ENTRYPOINT [ "java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "runner.jar", "--thin.root=/m2", "--thin.name=function", "--function.name=uppercase"] +EXPOSE 8080 +
+ +you could use a Spring Cloud Function app, instead of just a jar with a POF in it, in which case you would have to change the way the app runs in the container so that it picks up the main class as a source file. For example, you could change the ENTRYPOINT above and add --spring.main.sources=com.example.SampleApplication. + +
+Build the Docker image: +docker build -t [username/appname] . +Push the Docker image: +docker push [username/appname] +Use the OpenWhisk CLI (e.g. after vagrant ssh) to create the action: +wsk action create example --docker [username/appname] +Invoke the action: +wsk action invoke example --result --param payload foo +{ + "result": "FOO" +} +
+
\ No newline at end of file