Este contenido no está disponible en el idioma seleccionado.
Chapter 11. Functions
11.1. Setting up OpenShift Serverless Functions Copiar enlaceEnlace copiado en el portapapeles!
To improve the process of deployment of your application code, you can use OpenShift Serverless to deploy stateless, event-driven functions as a Knative service on OpenShift Container Platform. If you want to develop functions, you must complete the set up steps.
11.1.1. Prerequisites Copiar enlaceEnlace copiado en el portapapeles!
To enable the use of OpenShift Serverless Functions on your cluster, you must complete the following steps:
The OpenShift Serverless Operator and Knative Serving are installed on your cluster.
NoteFunctions are deployed as a Knative service. If you want to use event-driven architecture with your functions, you must also install Knative Eventing.
-
You have the
ocCLI installed. -
You have the Knative (
kn) CLI installed. Installing the Knative CLI enables the use ofcommands which you can use to create and manage functions.kn func - You have installed Docker Container Engine or Podman version 3.4.7 or higher.
- You have access to an available image registry, such as the OpenShift Container Registry.
- If you are using Quay.io as the image registry, you must ensure that either the repository is not private, or that you have followed the OpenShift Container Platform documentation on Allowing pods to reference images from other secured registries.
- If you are using the OpenShift Container Registry, a cluster administrator must expose the registry.
11.1.2. Setting up Podman Copiar enlaceEnlace copiado en el portapapeles!
To use advanced container management features, you might want to use Podman with OpenShift Serverless Functions. To do so, you need to start the Podman service and configure the Knative (
kn
Procedure
Start the Podman service that serves the Docker API on a UNIX socket at
:${XDG_RUNTIME_DIR}/podman/podman.sock$ systemctl start --user podman.socketNoteOn most systems, this socket is located at
./run/user/$(id -u)/podman/podman.sockEstablish the environment variable that is used to build a function:
$ export DOCKER_HOST="unix://${XDG_RUNTIME_DIR}/podman/podman.sock"Run the build command inside your function project directory with the
flag to see verbose output. You should see a connection to your local UNIX socket:-v$ kn func build -v
11.1.3. Setting up Podman on macOS Copiar enlaceEnlace copiado en el portapapeles!
To use advanced container management features, you might want to use Podman with OpenShift Serverless Functions. To do so on macOS, you need to start the Podman machine and configure the Knative (
kn
Procedure
Create the Podman machine:
$ podman machine init --memory=8192 --cpus=2 --disk-size=20Start the Podman machine, which serves the Docker API on a UNIX socket:
$ podman machine start Starting machine "podman-machine-default" Waiting for VM ... Mounting volume... /Users/myuser:/Users/user [...truncated output...] You can still connect Docker API clients by setting DOCKER_HOST using the following command in your terminal session: export DOCKER_HOST='unix:///Users/myuser/.local/share/containers/podman/machine/podman-machine-default/podman.sock' Machine "podman-machine-default" started successfullyNoteOn most macOS systems, this socket is located at
./Users/myuser/.local/share/containers/podman/machine/podman-machine-default/podman.sockEstablish the environment variable that is used to build a function:
$ export DOCKER_HOST='unix:///Users/myuser/.local/share/containers/podman/machine/podman-machine-default/podman.sock'Run the build command inside your function project directory with the
flag to see verbose output. You should see a connection to your local UNIX socket:-v$ kn func build -v
11.1.4. Next steps Copiar enlaceEnlace copiado en el portapapeles!
- For more information about Docker Container Engine or Podman, see Container build tool options.
- See Getting started with functions.
11.2. Getting started with functions Copiar enlaceEnlace copiado en el portapapeles!
Function lifecycle management includes creating, building, and deploying a function. Optionally, you can also test a deployed function by invoking it. You can do all of these operations on OpenShift Serverless using the
kn func
11.2.1. Prerequisites Copiar enlaceEnlace copiado en el portapapeles!
Before you can complete the following procedures, you must ensure that you have completed all of the prerequisite tasks in Setting up OpenShift Serverless Functions.
11.2.2. Creating functions Copiar enlaceEnlace copiado en el portapapeles!
Before you can build and deploy a function, you must create it by using the Knative (
kn
-c
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn
Procedure
Create a function project:
$ kn func create -r <repository> -l <runtime> -t <template> <path>-
Accepted runtime values include ,
quarkus,node,typescript,go,python, andspringboot.rust Accepted template values include
andhttp.cloudeventsExample command
$ kn func create -l typescript -t cloudevents examplefuncExample output
Created typescript function in /home/user/demo/examplefuncAlternatively, you can specify a repository that contains a custom template.
Example command
$ kn func create -r https://github.com/boson-project/templates/ -l node -t hello-world examplefuncExample output
Created node function in /home/user/demo/examplefunc
-
Accepted runtime values include
11.2.3. Running a function locally Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn func run
--path
kn func run
Example command to run a function in the current directory
$ kn func run
Example command to run a function in a directory specified as a path
$ kn func run --path=<directory_path>
You can also force a rebuild of an existing image before running the function, even if there have been no changes to the project files, by using the
--build
Example run command using the build flag
$ kn func run --build
If you set the
build
Example run command using the build flag
$ kn func run --build=false
You can use the help command to learn more about
kn func run
Build help command
$ kn func help run
11.2.4. Building functions Copiar enlaceEnlace copiado en el portapapeles!
Before you can run a function, you must build the function project. If you are using the
kn func run
kn func build
The
kn func build
11.2.4.1. Image container types Copiar enlaceEnlace copiado en el portapapeles!
By default,
kn func build
Example build command using Red Hat Source-to-Image (S2I)
$ kn func build
11.2.4.2. Image registry types Copiar enlaceEnlace copiado en el portapapeles!
The OpenShift Container Registry is used by default as the image registry for storing function images.
Example build command using OpenShift Container Registry
$ kn func build
Example output
Building function image
Function image has been built, image: registry.redhat.io/example/example-function:latest
You can override using OpenShift Container Registry as the default image registry by using the
--registry
Example build command overriding OpenShift Container Registry to use quay.io
$ kn func build --registry quay.io/username
Example output
Building function image
Function image has been built, image: quay.io/username/example-function:latest
11.2.4.3. Push flag Copiar enlaceEnlace copiado en el portapapeles!
You can add the
--push
kn func build
Example build command using OpenShift Container Registry
$ kn func build --push
11.2.4.4. Help command Copiar enlaceEnlace copiado en el portapapeles!
You can use the help command to learn more about
kn func build
Build help command
$ kn func help build
11.2.5. Deploying functions Copiar enlaceEnlace copiado en el portapapeles!
You can deploy a function to your cluster as a Knative service by using the
kn func deploy
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
- You must have already created and initialized the function that you want to deploy.
Procedure
Deploy a function:
$ kn func deploy [-n <namespace> -p <path> -i <image>]Example output
Function deployed at: http://func.example.com-
If no is specified, the function is deployed in the current namespace.
namespace -
The function is deployed from the current directory, unless a is specified.
path - The Knative service name is derived from the project name, and cannot be changed using this command.
-
If no
11.2.6. Invoking a deployed function with a test event Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn func invoke
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
- You must have already deployed the function that you want to invoke.
Procedure
Invoke a function:
$ kn func invoke-
The command only works when there is either a local container image currently running, or when there is a function deployed in the cluster.
kn func invoke -
The command executes on the local directory by default, and assumes that this directory is a function project.
kn func invoke
-
The
11.2.7. Deleting a function Copiar enlaceEnlace copiado en el portapapeles!
You can delete a function by using the
kn func delete
Procedure
Delete a function:
$ kn func delete [<function_name> -n <namespace> -p <path>]-
If the name or path of the function to delete is not specified, the current directory is searched for a file that is used to determine the function to delete.
func.yaml -
If the namespace is not specified, it defaults to the value in the
namespacefile.func.yaml
-
If the name or path of the function to delete is not specified, the current directory is searched for a
11.2.9. Next steps Copiar enlaceEnlace copiado en el portapapeles!
11.3. On-cluster function building and deploying Copiar enlaceEnlace copiado en el portapapeles!
Instead of building a function locally, you can build a function directly on the cluster. When using this workflow on a local development machine, you only need to work with the function source code. This is useful, for example, when you cannot install on-cluster function building tools, such as docker or podman.
11.3.1. Building and deploying functions on the cluster Copiar enlaceEnlace copiado en el portapapeles!
You can use the Knative (
kn
Prerequisites
- Red Hat OpenShift Pipelines must be installed on your cluster.
-
You have installed the OpenShift CLI ().
oc -
You have installed the Knative () CLI.
kn
Procedure
In each namespace where you want to run Pipelines and deploy a function, you must create the following resources:
Create the
Tekton task to be able to use Source-to-Image in the pipeline:s2i$ oc apply -f https://raw.githubusercontent.com/openshift-knative/kn-plugin-func/serverless-1.28.0/pipelines/resources/tekton/task/func-s2i/0.1/func-s2i.yamlCreate the
deploy Tekton task to be able to deploy the function in the pipeline:kn func$ oc apply -f https://raw.githubusercontent.com/openshift-knative/kn-plugin-func/serverless-1.28.0/pipelines/resources/tekton/task/func-deploy/0.1/func-deploy.yaml
Create a function:
$ kn func create <function_name> -l <runtime>-
After you have created a new function project, you must add the project to a Git repository and ensure that the repository is available to the cluster. Information about this Git repository is used to update the file in the next step.
func.yaml Update the configuration in the
file for your function project to enable on-cluster builds for the Git repository:func.yaml... git: url: <git_repository_url>1 revision: main2 contextDir: <directory_path>3 ...- Implement the business logic of your function. Then, use Git to commit and push the changes.
Deploy your function:
$ kn func deploy --remoteIf you are not logged into the container registry referenced in your function configuration, you are prompted to provide credentials for the remote container registry that hosts the function image:
Example output and prompts
🕕 Creating Pipeline resources Please provide credentials for image registry used by Pipeline. ? Server: https://index.docker.io/v1/ ? Username: my-repo ? Password: ******** Function deployed at URL: http://test-function.default.svc.cluster.local-
To update your function, commit and push new changes by using Git, then run the command again.
kn func deploy --remote
11.3.2. Specifying function revision Copiar enlaceEnlace copiado en el portapapeles!
When building and deploying a function on the cluster, you must specify the location of the function code by specifying the Git repository, branch, and subdirectory within the repository. You do not need to specify the branch if you use the
main
func.yaml
kn func deploy
Prerequisites
- Red Hat OpenShift Pipelines must be installed on your cluster.
-
You have installed the OpenShift () CLI.
oc -
You have installed the Knative () CLI.
kn
Procedure
Deploy your function:
$ kn func deploy --remote \1 --git-url <repo-url> \2 [--git-branch <branch>] \3 [--git-dir <function-dir>]4 - 1
- With the
--remoteflag, the build runs remotely. - 2
- Substitute
<repo-url>with the URL of the Git repository. - 3
- Substitute
<branch>with the Git branch, tag, or commit. If using the latest commit on themainbranch, you can skip this flag. - 4
- Substitute
<function-dir>with the directory containing the function if it is different than the repository root directory.
For example:
$ kn func deploy --remote \ --git-url https://example.com/alice/myfunc.git \ --git-branch my-feature \ --git-dir functions/example-func/
11.4. Developing Quarkus functions Copiar enlaceEnlace copiado en el portapapeles!
After you have created a Quarkus function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
11.4.1. Prerequisites Copiar enlaceEnlace copiado en el portapapeles!
- Before you can develop functions, you must complete the setup steps in Setting up OpenShift Serverless Functions.
11.4.2. Quarkus function template structure Copiar enlaceEnlace copiado en el portapapeles!
When you create a Quarkus function by using the Knative (
kn
func.yaml
Both
http
event
Template structure
.
├── func.yaml
├── mvnw
├── mvnw.cmd
├── pom.xml
├── README.md
└── src
├── main
│ ├── java
│ │ └── functions
│ │ ├── Function.java
│ │ ├── Input.java
│ │ └── Output.java
│ └── resources
│ └── application.properties
└── test
└── java
└── functions
├── FunctionTest.java
└── NativeFunctionIT.java
- 1
- Used to determine the image name and registry.
- 2
- The Project Object Model (POM) file contains project configuration, such as information about dependencies. You can add additional dependencies by modifying this file.
Example of additional dependencies
... <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.8.0</version> <scope>test</scope> </dependency> </dependencies> ...Dependencies are downloaded during the first compilation.
- 3
- The function project must contain a Java method annotated with
@Funq. You can place this method in theFunction.javaclass. - 4
- Contains simple test cases that can be used to test your function locally.
11.4.3. About invoking Quarkus functions Copiar enlaceEnlace copiado en el portapapeles!
You can create a Quarkus project that responds to cloud events, or one that responds to simple HTTP requests. Cloud events in Knative are transported over HTTP as a POST request, so either function type can listen and respond to incoming HTTP requests.
When an incoming request is received, Quarkus functions are invoked with an instance of a permitted type.
| Invocation method | Data type contained in the instance | Example of data |
|---|---|---|
| HTTP POST request | JSON object in the body of the request |
|
| HTTP GET request | Data in the query string |
|
|
| JSON object in the
|
|
The following example shows a function that receives and processes the
customerId
productId
Example Quarkus function
public class Functions {
@Funq
public void processPurchase(Purchase purchase) {
// process the purchase
}
}
The corresponding
Purchase
Example class
public class Purchase {
private long customerId;
private long productId;
// getters and setters
}
11.4.3.1. Invocation examples Copiar enlaceEnlace copiado en el portapapeles!
The following example code defines three functions named
withBeans
withCloudEvent
withBinary
Example
import io.quarkus.funqy.Funq;
import io.quarkus.funqy.knative.events.CloudEvent;
public class Input {
private String message;
// getters and setters
}
public class Output {
private String message;
// getters and setters
}
public class Functions {
@Funq
public Output withBeans(Input in) {
// function body
}
@Funq
public CloudEvent<Output> withCloudEvent(CloudEvent<Input> in) {
// function body
}
@Funq
public void withBinary(byte[] in) {
// function body
}
}
The
withBeans
Functions
An HTTP POST request with a JSON body:
$ curl "http://localhost:8080/withBeans" -X POST \ -H "Content-Type: application/json" \ -d '{"message": "Hello there."}'An HTTP GET request with query parameters:
$ curl "http://localhost:8080/withBeans?message=Hello%20there." -X GETA
object in binary encoding:CloudEvent$ curl "http://localhost:8080/" -X POST \ -H "Content-Type: application/json" \ -H "Ce-SpecVersion: 1.0" \ -H "Ce-Type: withBeans" \ -H "Ce-Source: cURL" \ -H "Ce-Id: 42" \ -d '{"message": "Hello there."}'A
object in structured encoding:CloudEvent$ curl http://localhost:8080/ \ -H "Content-Type: application/cloudevents+json" \ -d '{ "data": {"message":"Hello there."}, "datacontenttype": "application/json", "id": "42", "source": "curl", "type": "withBeans", "specversion": "1.0"}'
The
withCloudEvent
Functions
CloudEvent
withBeans
withBeans
withCloudEvent
The
withBinary
Functions
A
object in binary encoding:CloudEvent$ curl "http://localhost:8080/" -X POST \ -H "Content-Type: application/octet-stream" \ -H "Ce-SpecVersion: 1.0"\ -H "Ce-Type: withBinary" \ -H "Ce-Source: cURL" \ -H "Ce-Id: 42" \ --data-binary '@img.jpg'A
object in structured encoding:CloudEvent$ curl http://localhost:8080/ \ -H "Content-Type: application/cloudevents+json" \ -d "{ \"data_base64\": \"$(base64 --wrap=0 img.jpg)\", \"datacontenttype\": \"application/octet-stream\", \"id\": \"42\", \"source\": \"curl\", \"type\": \"withBinary\", \"specversion\": \"1.0\"}"
11.4.4. CloudEvent attributes Copiar enlaceEnlace copiado en el portapapeles!
If you need to read or write the attributes of a CloudEvent, such as
type
subject
CloudEvent<T>
CloudEventBuilder
<T>
In the following example,
CloudEventBuilder
public class Functions {
private boolean _processPurchase(Purchase purchase) {
// do stuff
}
public CloudEvent<Void> processPurchase(CloudEvent<Purchase> purchaseEvent) {
System.out.println("subject is: " + purchaseEvent.subject());
if (!_processPurchase(purchaseEvent.data())) {
return CloudEventBuilder.create()
.type("purchase.error")
.build();
}
return CloudEventBuilder.create()
.type("purchase.success")
.build();
}
}
11.4.5. Quarkus function return values Copiar enlaceEnlace copiado en el portapapeles!
Functions can return an instance of any type from the list of permitted types. Alternatively, they can return the
Uni<T>
<T>
The
Uni<T>
- If a function receives an HTTP request, then the returned object is sent in the body of an HTTP response.
-
If a function receives a object in binary encoding, then the returned object is sent in the data property of a binary-encoded
CloudEventobject.CloudEvent
The following example shows a function that fetches a list of purchases:
Example command
public class Functions {
@Funq
public List<Purchase> getPurchasesByName(String name) {
// logic to retrieve purchases
}
}
- Invoking this function through an HTTP request produces an HTTP response that contains a list of purchases in the body of the response.
-
Invoking this function through an incoming object produces a
CloudEventresponse with a list of purchases in theCloudEventproperty.data
11.4.5.1. Permitted types Copiar enlaceEnlace copiado en el portapapeles!
The input and output of a function can be any of the
void
String
byte[]
int
Integer
CloudEvents<T>
Maps, lists, arrays, the
<T>
CloudEvents<T>
Example
public class Functions {
public List<Integer> getIds();
public Purchase[] getPurchasesByName(String name);
public String getNameById(int id);
public Map<String,Integer> getNameIdMapping();
public void processImage(byte[] img);
}
11.4.6. Testing Quarkus functions Copiar enlaceEnlace copiado en el portapapeles!
Quarkus functions can be tested locally on your computer. In the default project that is created when you create a function using
kn func create
src/test/
Prerequisites
- You have created a Quarkus function.
-
You have installed the Knative () CLI.
kn
Procedure
- Navigate to the project folder for your function.
Run the Maven tests:
$ ./mvnw test
11.4.7. Next steps Copiar enlaceEnlace copiado en el portapapeles!
11.5. Developing Node.js functions Copiar enlaceEnlace copiado en el portapapeles!
After you have created a Node.js function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
11.5.1. Prerequisites Copiar enlaceEnlace copiado en el portapapeles!
- Before you can develop functions, you must complete the steps in Setting up OpenShift Serverless Functions.
11.5.2. Node.js function template structure Copiar enlaceEnlace copiado en el portapapeles!
When you create a Node.js function using the Knative (
kn
func.yaml
Both
http
event
Template structure
.
├── func.yaml
├── index.js
├── package.json
├── README.md
└── test
├── integration.js
└── unit.js
- 1
- The
func.yamlconfiguration file is used to determine the image name and registry. - 2
- Your project must contain an
index.jsfile which exports a single function. - 3
- You are not restricted to the dependencies provided in the template
package.jsonfile. You can add additional dependencies as you would in any other Node.js project.Example of adding npm dependencies
npm install --save opossumWhen the project is built for deployment, these dependencies are included in the created runtime container image.
- 4
- Integration and unit test scripts are provided as part of the function template.
11.5.3. About invoking Node.js functions Copiar enlaceEnlace copiado en el portapapeles!
When using the Knative (
kn
Node.js functions can be invoked with a simple HTTP request. When an incoming request is received, functions are invoked with a
context
11.5.3.1. Node.js context objects Copiar enlaceEnlace copiado en el portapapeles!
Functions are invoked by providing a
context
Example context object
function handle(context, data)
This information includes the HTTP request method, any query strings or headers sent with the request, the HTTP version, and the request body. Incoming requests that contain a
CloudEvent
context.cloudevent
11.5.3.1.1. Context object methods Copiar enlaceEnlace copiado en el portapapeles!
The
context
cloudEventResponse()
In a Knative system, if a function deployed as a service is invoked by an event broker sending a CloudEvent, the broker examines the response. If the response is a CloudEvent, this event is handled by the broker.
Example context object method
// Expects to receive a CloudEvent with customer data
function handle(context, customer) {
// process the customer
const processed = handle(customer);
return context.cloudEventResponse(customer)
.source('/handle')
.type('fn.process.customer')
.response();
}
11.5.3.1.2. CloudEvent data Copiar enlaceEnlace copiado en el portapapeles!
If the incoming request is a CloudEvent, any data associated with the CloudEvent is extracted from the event and provided as a second parameter. For example, if a CloudEvent is received that contains a JSON string in its data property that is similar to the following:
{
"customerId": "0123456",
"productId": "6543210"
}
When invoked, the second parameter to the function, after the
context
customerId
productId
Example signature
function handle(context, data)
The
data
customerId
productId
11.5.4. Node.js function return values Copiar enlaceEnlace copiado en el portapapeles!
Functions can return any valid JavaScript type or can have no return value. When a function has no return value specified, and no failure is indicated, the caller receives a
204 No Content
Functions can also return a CloudEvent or a
Message
Example
function handle(context, customer) {
// process customer and return a new CloudEvent
return new CloudEvent({
source: 'customer.processor',
type: 'customer.processed'
})
}
11.5.4.1. Returning headers Copiar enlaceEnlace copiado en el portapapeles!
You can set a response header by adding a
headers
return
Example response header
function handle(context, customer) {
// process customer and return custom headers
// the response will be '204 No content'
return { headers: { customerid: customer.id } };
}
11.5.4.2. Returning status codes Copiar enlaceEnlace copiado en el portapapeles!
You can set a status code that is returned to the caller by adding a
statusCode
return
Example status code
function handle(context, customer) {
// process customer
if (customer.restricted) {
return { statusCode: 451 }
}
}
Status codes can also be set for errors that are created and thrown by the function:
Example error status code
function handle(context, customer) {
// process customer
if (customer.restricted) {
const err = new Error(‘Unavailable for legal reasons’);
err.statusCode = 451;
throw err;
}
}
11.5.5. Testing Node.js functions Copiar enlaceEnlace copiado en el portapapeles!
Node.js functions can be tested locally on your computer. In the default project that is created when you create a function by using
kn func create
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn -
You have created a function by using .
kn func create
Procedure
- Navigate to the test folder for your function.
Run the tests:
$ npm test
11.5.6. Next steps Copiar enlaceEnlace copiado en el portapapeles!
- See the Node.js context object reference documentation.
- Build and deploy a function.
11.6. Developing TypeScript functions Copiar enlaceEnlace copiado en el portapapeles!
After you have created a TypeScript function project, you can modify the template files provided to add business logic to your function. This includes configuring function invocation and the returned headers and status codes.
11.6.1. Prerequisites Copiar enlaceEnlace copiado en el portapapeles!
- Before you can develop functions, you must complete the steps in Setting up OpenShift Serverless Functions.
11.6.2. TypeScript function template structure Copiar enlaceEnlace copiado en el portapapeles!
When you create a TypeScript function using the Knative (
kn
func.yaml
Both
http
event
Template structure
.
├── func.yaml
├── package.json
├── package-lock.json
├── README.md
├── src
│ └── index.ts
├── test
│ ├── integration.ts
│ └── unit.ts
└── tsconfig.json
- 1
- The
func.yamlconfiguration file is used to determine the image name and registry. - 2
- You are not restricted to the dependencies provided in the template
package.jsonfile. You can add additional dependencies as you would in any other TypeScript project.Example of adding npm dependencies
npm install --save opossumWhen the project is built for deployment, these dependencies are included in the created runtime container image.
- 3
- Your project must contain an
src/index.jsfile which exports a function namedhandle. - 4
- Integration and unit test scripts are provided as part of the function template.
11.6.3. About invoking TypeScript functions Copiar enlaceEnlace copiado en el portapapeles!
When using the Knative (
kn
TypeScript functions can be invoked with a simple HTTP request. When an incoming request is received, functions are invoked with a
context
11.6.3.1. TypeScript context objects Copiar enlaceEnlace copiado en el portapapeles!
To invoke a function, you provide a
context
context
Example context object
function handle(context:Context): string
This information includes the HTTP request method, any query strings or headers sent with the request, the HTTP version, and the request body. Incoming requests that contain a
CloudEvent
context.cloudevent
11.6.3.1.1. Context object methods Copiar enlaceEnlace copiado en el portapapeles!
The
context
cloudEventResponse()
In a Knative system, if a function deployed as a service is invoked by an event broker sending a CloudEvent, the broker examines the response. If the response is a CloudEvent, this event is handled by the broker.
Example context object method
// Expects to receive a CloudEvent with customer data
export function handle(context: Context, cloudevent?: CloudEvent): CloudEvent {
// process the customer
const customer = cloudevent.data;
const processed = processCustomer(customer);
return context.cloudEventResponse(customer)
.source('/customer/process')
.type('customer.processed')
.response();
}
11.6.3.1.2. Context types Copiar enlaceEnlace copiado en el portapapeles!
The TypeScript type definition files export the following types for use in your functions.
Exported type definitions
// Invokable is the expeted Function signature for user functions
export interface Invokable {
(context: Context, cloudevent?: CloudEvent): any
}
// Logger can be used for structural logging to the console
export interface Logger {
debug: (msg: any) => void,
info: (msg: any) => void,
warn: (msg: any) => void,
error: (msg: any) => void,
fatal: (msg: any) => void,
trace: (msg: any) => void,
}
// Context represents the function invocation context, and provides
// access to the event itself as well as raw HTTP objects.
export interface Context {
log: Logger;
req: IncomingMessage;
query?: Record<string, any>;
body?: Record<string, any>|string;
method: string;
headers: IncomingHttpHeaders;
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
cloudevent: CloudEvent;
cloudEventResponse(data: string|object): CloudEventResponse;
}
// CloudEventResponse is a convenience class used to create
// CloudEvents on function returns
export interface CloudEventResponse {
id(id: string): CloudEventResponse;
source(source: string): CloudEventResponse;
type(type: string): CloudEventResponse;
version(version: string): CloudEventResponse;
response(): CloudEvent;
}
11.6.3.1.3. CloudEvent data Copiar enlaceEnlace copiado en el portapapeles!
If the incoming request is a CloudEvent, any data associated with the CloudEvent is extracted from the event and provided as a second parameter. For example, if a CloudEvent is received that contains a JSON string in its data property that is similar to the following:
{
"customerId": "0123456",
"productId": "6543210"
}
When invoked, the second parameter to the function, after the
context
customerId
productId
Example signature
function handle(context: Context, cloudevent?: CloudEvent): CloudEvent
The
cloudevent
customerId
productId
11.6.4. TypeScript function return values Copiar enlaceEnlace copiado en el portapapeles!
Functions can return any valid JavaScript type or can have no return value. When a function has no return value specified, and no failure is indicated, the caller receives a
204 No Content
Functions can also return a CloudEvent or a
Message
Example
export const handle: Invokable = function (
context: Context,
cloudevent?: CloudEvent
): Message {
// process customer and return a new CloudEvent
const customer = cloudevent.data;
return HTTP.binary(
new CloudEvent({
source: 'customer.processor',
type: 'customer.processed'
})
);
};
11.6.4.1. Returning headers Copiar enlaceEnlace copiado en el portapapeles!
You can set a response header by adding a
headers
return
Example response header
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, any> {
// process customer and return custom headers
const customer = cloudevent.data as Record<string, any>;
return { headers: { 'customer-id': customer.id } };
}
11.6.4.2. Returning status codes Copiar enlaceEnlace copiado en el portapapeles!
You can set a status code that is returned to the caller by adding a
statusCode
return
Example status code
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, any> {
// process customer
const customer = cloudevent.data as Record<string, any>;
if (customer.restricted) {
return {
statusCode: 451
}
}
// business logic, then
return {
statusCode: 240
}
}
Status codes can also be set for errors that are created and thrown by the function:
Example error status code
export function handle(context: Context, cloudevent?: CloudEvent): Record<string, string> {
// process customer
const customer = cloudevent.data as Record<string, any>;
if (customer.restricted) {
const err = new Error(‘Unavailable for legal reasons’);
err.statusCode = 451;
throw err;
}
}
11.6.5. Testing TypeScript functions Copiar enlaceEnlace copiado en el portapapeles!
TypeScript functions can be tested locally on your computer. In the default project that is created when you create a function using
kn func create
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn -
You have created a function by using .
kn func create
Procedure
If you have not previously run tests, install the dependencies first:
$ npm install- Navigate to the test folder for your function.
Run the tests:
$ npm test
11.6.6. Next steps Copiar enlaceEnlace copiado en el portapapeles!
- See the TypeScript context object reference documentation.
- Build and deploy a function.
- See the Pino API documentation for more information about logging with functions.
11.7. Using functions with Knative Eventing Copiar enlaceEnlace copiado en el portapapeles!
Functions are deployed as Knative services on an OpenShift Container Platform cluster. You can connect functions to Knative Eventing components so that they can receive incoming events.
11.7.1. Connect an event source to a function using the Developer perspective Copiar enlaceEnlace copiado en el portapapeles!
Functions are deployed as Knative services on an OpenShift Container Platform cluster. When you create an event source by using the OpenShift Container Platform web console, you can specify a deployed function that events are sent to from that source.
Prerequisites
- The OpenShift Serverless Operator, Knative Serving, and Knative Eventing are installed on your OpenShift Container Platform cluster.
- You have logged in to the web console and are in the Developer perspective.
- You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
- You have created and deployed a function.
Procedure
-
Create an event source of any type, by navigating to +Add
Event Source and selecting the event source type that you want to create. - In the Sink section of the Create Event Source form view, select your function in the Resource list.
- Click Create.
Verification
You can verify that the event source was created and is connected to the function by viewing the Topology page.
- In the Developer perspective, navigate to Topology.
- View the event source and click the connected function to see the function details in the right panel.
11.8. Function project configuration in func.yaml Copiar enlaceEnlace copiado en el portapapeles!
The
func.yaml
func.yaml
kn func
kn func build
build
11.8.1. Configurable fields in func.yaml Copiar enlaceEnlace copiado en el portapapeles!
Many of the fields in
func.yaml
11.8.1.1. buildEnvs Copiar enlaceEnlace copiado en el portapapeles!
The
buildEnvs
envs
buildEnv
You can set a
buildEnv
buildEnv
EXAMPLE1
one
buildEnvs:
- name: EXAMPLE1
value: one
You can also set a
buildEnv
buildEnv
EXAMPLE2
LOCAL_ENV_VAR
buildEnvs:
- name: EXAMPLE1
value: '{{ env:LOCAL_ENV_VAR }}'
11.8.1.2. envs Copiar enlaceEnlace copiado en el portapapeles!
The
envs
- Directly from a value.
- From a value assigned to a local environment variable. See the section "Referencing local environment variables from func.yaml fields" for more information.
- From a key-value pair stored in a secret or config map.
- You can also import all key-value pairs stored in a secret or config map, with keys used as names of the created environment variables.
This examples demonstrates the different ways to set an environment variable:
name: test
namespace: ""
runtime: go
...
envs:
- name: EXAMPLE1
value: value
- name: EXAMPLE2
value: '{{ env:LOCAL_ENV_VALUE }}'
- name: EXAMPLE3
value: '{{ secret:mysecret:key }}'
- name: EXAMPLE4
value: '{{ configMap:myconfigmap:key }}'
- value: '{{ secret:mysecret2 }}'
- value: '{{ configMap:myconfigmap2 }}'
- 1
- An environment variable set directly from a value.
- 2
- An environment variable set from a value assigned to a local environment variable.
- 3
- An environment variable assigned from a key-value pair stored in a secret.
- 4
- An environment variable assigned from a key-value pair stored in a config map.
- 5
- A set of environment variables imported from key-value pairs of a secret.
- 6
- A set of environment variables imported from key-value pairs of a config map.
11.8.1.3. builder Copiar enlaceEnlace copiado en el portapapeles!
The
builder
pack
s2i
11.8.1.4. build Copiar enlaceEnlace copiado en el portapapeles!
The
build
local
git
git
11.8.1.5. volumes Copiar enlaceEnlace copiado en el portapapeles!
The
volumes
name: test
namespace: ""
runtime: go
...
volumes:
- secret: mysecret
path: /workspace/secret
- configMap: myconfigmap
path: /workspace/configmap
11.8.1.6. options Copiar enlaceEnlace copiado en el portapapeles!
The
options
These options are available:
scale-
: The minimum number of replicas. Must be a non-negative integer. The default is 0.
min -
: The maximum number of replicas. Must be a non-negative integer. The default is 0, which means no limit.
max -
: Defines which metric type is watched by the Autoscaler. It can be set to
metric, which is the default, orconcurrency.rps -
: Recommendation for when to scale up based on the number of concurrently incoming requests. The
targetoption can be a float value greater than 0.01. The default is 100, unless thetargetis set, in which caseoptions.resources.limits.concurrencydefaults to its value.target -
: Percentage of concurrent requests utilization allowed before scaling up. It can be a float value between 1 and 100. The default is 70.
utilization
-
resourcesrequests-
: A CPU resource request for the container with deployed function.
cpu -
: A memory resource request for the container with deployed function.
memory
-
limits-
: A CPU resource limit for the container with deployed function.
cpu -
: A memory resource limit for the container with deployed function.
memory -
: Hard Limit of concurrent requests to be processed by a single replica. It can be integer value greater than or equal to 0, default is 0 - meaning no limit.
concurrency
-
This is an example configuration of the
scale
name: test
namespace: ""
runtime: go
...
options:
scale:
min: 0
max: 10
metric: concurrency
target: 75
utilization: 75
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 1000m
memory: 256Mi
concurrency: 100
11.8.1.7. image Copiar enlaceEnlace copiado en el portapapeles!
The
image
kn func build
kn func deploy
11.8.1.8. imageDigest Copiar enlaceEnlace copiado en el portapapeles!
The
imageDigest
11.8.1.9. labels Copiar enlaceEnlace copiado en el portapapeles!
The
labels
You can set a label directly from a value. In the following example, the label with the
role
backend
labels:
- key: role
value: backend
You can also set a label from a local environment variable. In the following example, the label with the
author
USER
labels:
- key: author
value: '{{ env:USER }}'
11.8.1.10. name Copiar enlaceEnlace copiado en el portapapeles!
The
name
11.8.1.11. namespace Copiar enlaceEnlace copiado en el portapapeles!
The
namespace
11.8.1.12. runtime Copiar enlaceEnlace copiado en el portapapeles!
The
runtime
python
11.8.2. Referencing local environment variables from func.yaml fields Copiar enlaceEnlace copiado en el portapapeles!
If you want to avoid storing sensitive information such as an API key in the function configuration, you can add a reference to an environment variable available in the local environment. You can do this by modifying the
envs
func.yaml
Prerequisites
- You need to have the function project created.
- The local environment needs to contain the variable that you want to reference.
Procedure
To refer to a local environment variable, use the following syntax:
{{ env:ENV_VAR }}Substitute
with the name of the variable in the local environment that you want to use.ENV_VARFor example, you might have the
variable available in the local environment. You can assign its value to theAPI_KEYvariable, which you can then directly use within your function:MY_API_KEYExample function
name: test namespace: "" runtime: go ... envs: - name: MY_API_KEY value: '{{ env:API_KEY }}' ...
11.9. Accessing secrets and config maps from functions Copiar enlaceEnlace copiado en el portapapeles!
After your functions have been deployed to the cluster, they can access data stored in secrets and config maps. This data can be mounted as volumes, or assigned to environment variables. You can configure this access interactively by using the Knative CLI, or by manually by editing the function configuration YAML file.
To access secrets and config maps, the function must be deployed on the cluster. This functionality is not available to a function running locally.
If a secret or config map value cannot be accessed, the deployment fails with an error message specifying the inaccessible values.
11.9.1. Modifying function access to secrets and config maps interactively Copiar enlaceEnlace copiado en el portapapeles!
You can manage the secrets and config maps accessed by your function by using the
kn func config
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
Run the following command in the function project directory:
$ kn func configAlternatively, you can specify the function project directory using the
or--pathoption.-pUse the interactive interface to perform the necessary operation. For example, using the utility to list configured volumes produces an output similar to this:
$ kn func config ? What do you want to configure? Volumes ? What operation do you want to perform? List Configured Volumes mounts: - Secret "mysecret" mounted at path: "/workspace/secret" - Secret "mysecret2" mounted at path: "/workspace/secret2"This scheme shows all operations available in the interactive utility and how to navigate to them:
kn func config ├─> Environment variables │ ├─> Add │ │ ├─> ConfigMap: Add all key-value pairs from a config map │ │ ├─> ConfigMap: Add value from a key in a config map │ │ ├─> Secret: Add all key-value pairs from a secret │ │ └─> Secret: Add value from a key in a secret │ ├─> List: List all configured environment variables │ └─> Remove: Remove a configured environment variable └─> Volumes ├─> Add │ ├─> ConfigMap: Mount a config map as a volume │ └─> Secret: Mount a secret as a volume ├─> List: List all configured volumes └─> Remove: Remove a configured volumeOptional. Deploy the function to make the changes take effect:
$ kn func deploy -p test
11.9.2. Modifying function access to secrets and config maps interactively by using specialized commands Copiar enlaceEnlace copiado en el portapapeles!
Every time you run the
kn func config
kn func config
To list configured environment variables:
$ kn func config envs [-p <function-project-path>]To add environment variables to the function configuration:
$ kn func config envs add [-p <function-project-path>]To remove environment variables from the function configuration:
$ kn func config envs remove [-p <function-project-path>]To list configured volumes:
$ kn func config volumes [-p <function-project-path>]To add a volume to the function configuration:
$ kn func config volumes add [-p <function-project-path>]To remove a volume from the function configuration:
$ kn func config volumes remove [-p <function-project-path>]
11.9.3. Adding function access to secrets and config maps manually Copiar enlaceEnlace copiado en el portapapeles!
You can manually add configuration for accessing secrets and config maps to your function. This might be preferable to using the
kn func config
11.9.3.1. Mounting a secret as a volume Copiar enlaceEnlace copiado en el portapapeles!
You can mount a secret as a volume. Once a secret is mounted, you can access it from the function as a regular file. This enables you to store on the cluster data needed by the function, for example, a list of URIs that need to be accessed by the function.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For each secret you want to mount as a volume, add the following YAML to the
section:volumesname: test namespace: "" runtime: go ... volumes: - secret: mysecret path: /workspace/secret-
Substitute with the name of the target secret.
mysecret Substitute
with the path where you want to mount the secret./workspace/secretFor example, to mount the
secret, use the following YAML:addressesname: test namespace: "" runtime: go ... volumes: - configMap: addresses path: /workspace/secret-addresses
-
Substitute
- Save the configuration.
11.9.3.2. Mounting a config map as a volume Copiar enlaceEnlace copiado en el portapapeles!
You can mount a config map as a volume. Once a config map is mounted, you can access it from the function as a regular file. This enables you to store on the cluster data needed by the function, for example, a list of URIs that need to be accessed by the function.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For each config map you want to mount as a volume, add the following YAML to the
section:volumesname: test namespace: "" runtime: go ... volumes: - configMap: myconfigmap path: /workspace/configmap-
Substitute with the name of the target config map.
myconfigmap Substitute
with the path where you want to mount the config map./workspace/configmapFor example, to mount the
config map, use the following YAML:addressesname: test namespace: "" runtime: go ... volumes: - configMap: addresses path: /workspace/configmap-addresses
-
Substitute
- Save the configuration.
11.9.3.3. Setting environment variable from a key value defined in a secret Copiar enlaceEnlace copiado en el portapapeles!
You can set an environment variable from a key value defined as a secret. A value previously stored in a secret can then be accessed as an environment variable by the function at runtime. This can be useful for getting access to a value stored in a secret, such as the ID of a user.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For each value from a secret key-value pair that you want to assign to an environment variable, add the following YAML to the
section:envsname: test namespace: "" runtime: go ... envs: - name: EXAMPLE value: '{{ secret:mysecret:key }}'-
Substitute with the name of the environment variable.
EXAMPLE -
Substitute with the name of the target secret.
mysecret Substitute
with the key mapped to the target value.keyFor example, to access the user ID that is stored in
, use the following YAML:userdetailssecretname: test namespace: "" runtime: go ... envs: - value: '{{ configMap:userdetailssecret:userid }}'
-
Substitute
- Save the configuration.
11.9.3.4. Setting environment variable from a key value defined in a config map Copiar enlaceEnlace copiado en el portapapeles!
You can set an environment variable from a key value defined as a config map. A value previously stored in a config map can then be accessed as an environment variable by the function at runtime. This can be useful for getting access to a value stored in a config map, such as the ID of a user.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For each value from a config map key-value pair that you want to assign to an environment variable, add the following YAML to the
section:envsname: test namespace: "" runtime: go ... envs: - name: EXAMPLE value: '{{ configMap:myconfigmap:key }}'-
Substitute with the name of the environment variable.
EXAMPLE -
Substitute with the name of the target config map.
myconfigmap Substitute
with the key mapped to the target value.keyFor example, to access the user ID that is stored in
, use the following YAML:userdetailsmapname: test namespace: "" runtime: go ... envs: - value: '{{ configMap:userdetailsmap:userid }}'
-
Substitute
- Save the configuration.
11.9.3.5. Setting environment variables from all values defined in a secret Copiar enlaceEnlace copiado en el portapapeles!
You can set an environment variable from all values defined in a secret. Values previously stored in a secret can then be accessed as environment variables by the function at runtime. This can be useful for simultaneously getting access to a collection of values stored in a secret, for example, a set of data pertaining to a user.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For every secret for which you want to import all key-value pairs as environment variables, add the following YAML to the
section:envsname: test namespace: "" runtime: go ... envs: - value: '{{ secret:mysecret }}'1 - 1
- Substitute
mysecretwith the name of the target secret.
For example, to access all user data that is stored in
, use the following YAML:userdetailssecretname: test namespace: "" runtime: go ... envs: - value: '{{ configMap:userdetailssecret }}'- Save the configuration.
11.9.3.6. Setting environment variables from all values defined in a config map Copiar enlaceEnlace copiado en el portapapeles!
You can set an environment variable from all values defined in a config map. Values previously stored in a config map can then be accessed as environment variables by the function at runtime. This can be useful for simultaneously getting access to a collection of values stored in a config map, for example, a set of data pertaining to a user.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For every config map for which you want to import all key-value pairs as environment variables, add the following YAML to the
section:envsname: test namespace: "" runtime: go ... envs: - value: '{{ configMap:myconfigmap }}'1 - 1
- Substitute
myconfigmapwith the name of the target config map.
For example, to access all user data that is stored in
, use the following YAML:userdetailsmapname: test namespace: "" runtime: go ... envs: - value: '{{ configMap:userdetailsmap }}'- Save the file.
11.10. Adding annotations to functions Copiar enlaceEnlace copiado en el portapapeles!
You can add Kubernetes annotations to a deployed Serverless function. Annotations enable you to attach arbitrary metadata to a function, for example, a note about the function’s purpose. Annotations are added to the
annotations
func.yaml
There are two limitations of the function annotation feature:
-
After a function annotation propagates to the corresponding Knative service on the cluster, it cannot be removed from the service by deleting it from the file. You must remove the annotation from the Knative service by modifying the YAML file of the service directly, or by using the OpenShift Container Platform web console.
func.yaml -
You cannot set annotations that are set by Knative, for example, the annotations.
autoscaling
11.10.1. Adding annotations to a function Copiar enlaceEnlace copiado en el portapapeles!
You can add annotations to a function. Similar to a label, an annotation is defined as a key-value map. Annotations are useful, for example, for providing metadata about a function, such as the function’s author.
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a function.
Procedure
-
Open the file for your function.
func.yaml For every annotation that you want to add, add the following YAML to the
section:annotationsname: test namespace: "" runtime: go ... annotations: <annotation_name>: "<annotation_value>"1 - 1
- Substitute
<annotation_name>: "<annotation_value>"with your annotation.
For example, to indicate that a function was authored by Alice, you might include the following annotation:
name: test namespace: "" runtime: go ... annotations: author: "alice@example.com"- Save the configuration.
The next time you deploy your function to the cluster, the annotations are added to the corresponding Knative service.
11.11. Functions development reference guide Copiar enlaceEnlace copiado en el portapapeles!
OpenShift Serverless Functions provides templates that can be used to create basic functions. A template initiates the function project boilerplate and prepares it for use with the
kn func
Templates for the following runtimes are available:
11.11.1. Node.js context object reference Copiar enlaceEnlace copiado en el portapapeles!
The
context
11.11.1.1. log Copiar enlaceEnlace copiado en el portapapeles!
Provides a logging object that can be used to write output to the cluster logs. The log adheres to the Pino logging API.
Example log
function handle(context) {
context.log.info(“Processing customer”);
}
You can access the function by using the
kn func invoke
Example command
$ kn func invoke --target 'http://example.function.com'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}
You can change the log level to one of
fatal
error
warn
info
debug
trace
silent
logLevel
FUNC_LOG_LEVEL
config
11.11.1.2. query Copiar enlaceEnlace copiado en el portapapeles!
Returns the query string for the request, if any, as key-value pairs. These attributes are also found on the context object itself.
Example query
function handle(context) {
// Log the 'name' query parameter
context.log.info(context.query.name);
// Query parameters are also attached to the context
context.log.info(context.name);
}
You can access the function by using the
kn func invoke
Example command
$ kn func invoke --target 'http://example.com?name=tiger'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
11.11.1.3. body Copiar enlaceEnlace copiado en el portapapeles!
Returns the request body if any. If the request body contains JSON code, this will be parsed so that the attributes are directly available.
Example body
function handle(context) {
// log the incoming request body's 'hello' parameter
context.log.info(context.body.hello);
}
You can access the function by using the
curl
Example command
$ kn func invoke -d '{"Hello": "world"}'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}
11.11.1.4. headers Copiar enlaceEnlace copiado en el portapapeles!
Returns the HTTP request headers as an object.
Example header
function handle(context) {
context.log.info(context.headers["custom-header"]);
}
You can access the function by using the
kn func invoke
Example command
$ kn func invoke --target 'http://example.function.com'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}
11.11.1.5. HTTP requests Copiar enlaceEnlace copiado en el portapapeles!
- method
- Returns the HTTP request method as a string.
- httpVersion
- Returns the HTTP version as a string.
- httpVersionMajor
- Returns the HTTP major version number as a string.
- httpVersionMinor
- Returns the HTTP minor version number as a string.
11.11.2. TypeScript context object reference Copiar enlaceEnlace copiado en el portapapeles!
The
context
11.11.2.1. log Copiar enlaceEnlace copiado en el portapapeles!
Provides a logging object that can be used to write output to the cluster logs. The log adheres to the Pino logging API.
Example log
export function handle(context: Context): string {
// log the incoming request body's 'hello' parameter
if (context.body) {
context.log.info((context.body as Record<string, string>).hello);
} else {
context.log.info('No data received');
}
return 'OK';
}
You can access the function by using the
kn func invoke
Example command
$ kn func invoke --target 'http://example.function.com'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}
You can change the log level to one of
fatal
error
warn
info
debug
trace
silent
logLevel
FUNC_LOG_LEVEL
config
11.11.2.2. query Copiar enlaceEnlace copiado en el portapapeles!
Returns the query string for the request, if any, as key-value pairs. These attributes are also found on the context object itself.
Example query
export function handle(context: Context): string {
// log the 'name' query parameter
if (context.query) {
context.log.info((context.query as Record<string, string>).name);
} else {
context.log.info('No data received');
}
return 'OK';
}
You can access the function by using the
kn func invoke
Example command
$ kn func invoke --target 'http://example.function.com' --data '{"name": "tiger"}'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}
11.11.2.3. body Copiar enlaceEnlace copiado en el portapapeles!
Returns the request body, if any. If the request body contains JSON code, this will be parsed so that the attributes are directly available.
Example body
export function handle(context: Context): string {
// log the incoming request body's 'hello' parameter
if (context.body) {
context.log.info((context.body as Record<string, string>).hello);
} else {
context.log.info('No data received');
}
return 'OK';
}
You can access the function by using the
kn func invoke
Example command
$ kn func invoke --target 'http://example.function.com' --data '{"hello": "world"}'
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}
11.11.2.4. headers Copiar enlaceEnlace copiado en el portapapeles!
Returns the HTTP request headers as an object.
Example header
export function handle(context: Context): string {
// log the incoming request body's 'hello' parameter
if (context.body) {
context.log.info((context.headers as Record<string, string>)['custom-header']);
} else {
context.log.info('No data received');
}
return 'OK';
}
You can access the function by using the
curl
Example command
$ curl -H'x-custom-header: some-value’' http://example.function.com
Example output
{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}
11.11.2.5. HTTP requests Copiar enlaceEnlace copiado en el portapapeles!
- method
- Returns the HTTP request method as a string.
- httpVersion
- Returns the HTTP version as a string.
- httpVersionMajor
- Returns the HTTP major version number as a string.
- httpVersionMinor
- Returns the HTTP minor version number as a string.