Application Connector

Overview

The Application Connector (AC) is a proprietary Kyma implementation that allows you to connect with external solutions. No matter if you want to integrate an on-premise or a cloud system, the integration process doesn't change, which allows to avoid any configuration or network-related problems.

The external solution you connect to Kyma using the AC is represented as a Remote Environment (RE). There is always a one-to-one relationship between a connected solution and a RE, which helps to ensure the highest level of security and separation. This means that you must create five separate REs in your cluster to connect five different external solutions and use their APIs and Event catalogs in Kyma.

The AC gives you this functionality:

  • Manages the lifecycle of REs.
  • Establishes a secure connection and generates the client certificate used by the connected external solution.
  • Registers the APIs and the Event catalogs of the connected external solution.
  • Delivers the Events from the connected external solution to the Kyma Event Bus.
  • Proxies calls sent from Kyma to external APIs registered by the connected external solution.
  • Allows to map a RE to a Kyma Environment and use its registered APIs and Event catalogs in the context of that Environment.
  • Integrates the registered APIs and Event catalogs with the Kyma Service Catalog.

All of the AC components scale independently, which allows to adjust it to fit the needs of the implementation built using Kyma.

NOTE: To learn more about the concept of Environments in Kyma, read the Environments document in the Kyma documentation topic.

Application Connector components

Architecture Diagram

Nginx Ingress Controller

The Nginx Ingress Controller exposes the Application Connector by assigning a public IP address and a DNS name to it. The DNS name of the Ingress is cluster-dependant and follows the gateway.{cluster-dns} format, for example gateway.servicemanager.cluster.kyma.cx. You can access every exposed Remote Environment through its Gateway by using the assigned path. For example, to reach the Gateway for the ec-default Remote Environment, use this URL: gateway.servicemanager.cluster.kyma.cx/ec-default. The Nginx Ingress Controller secures the endpoint with certificate validation. Each call must include a valid client certificate which is Remote Environment-specific.

Connector Service

The Connector Service:

  • Handles the exchange of client certificates for a given RE.
  • Provides the Metadata Service and Event Service endpoints.
  • Signs client certificates using the server side certificate stored in Kubernetes Secrets.

Metadata Service

The Metadata Service stores all registered APIs and Event Catalog exposed by a connected external solution. The APIs and Event catalogs metadata are stored in RemoteEnvironment Custom Resource. The system creates a new Kubernetes service for each registered API. Additionally, a new Service Classes is registered in the Service Catalog.

NOTE: Using the Metadata Service, you can register an API along with its OAuth credentials. The credentials are stored in a Kubernetes Secret.

Event Service

The Event Service sends events to the Kyma Event Bus and enriches the events with metadata that indicates the source of the Event. This allows to route the events to Lambda functions and Services based on their source Remote Environment.

Remote Environment

A Remote Environment (RE) represents an external solution connected to Kyma. It handles the integration with other components, such as the Service Catalog or the Event Bus. Using the components of the Application Connector, the RE creates a coherent identity for a connected external solution and ensures its separation. All REs are created through the RemoteEnvironment Custom Resource, which also stores all of the relevant metadata. You can map a RE to many Kyma Environments and use the APIs and the Event Catalogs of the connected external solution within their context.

Remote Environment controller

The controller listens for creating or deleting the RemoteEnvironment Custom Resources and acts accordingly, either provisioning or de-provisioning an instance of Proxy Service and Event Service for every Custom Resource.

NOTE: Every RemoteEnvironment Custom Resource corresponds to a single RE to which you can connect an external solution.

Proxy Service

The Proxy Service is an intermediary component between a lambda function or a service and an external API registered with the Metadata Service. It acts as a proxy and can acquire OAuth tokens.

Access Service

The Access Service exposes the Proxy Service and manages the access from the Lambda functions and services deployed in Kyma to the external APIs over the Proxy Service.

Minio bucket

The Minio bucket stores the documentation of the connected external solution's registered APIs and Event catalogs.

Kubernetes Secret

The Kubernetes Secret is a Kubernetes object which stores sensitive data, such as the OAuth credentials.

Security

Client certificates

To provide maximum security, the Application Connector uses TLS protocol with Client Authentication enabled. As a result, whoever wants to connect to the Application Connector must present a valid client certificate, which is dedicated to a specific Remote Environment. In this way, the traffic is fully encrypted and the client has a valid identity.

Disable SSL certificate verification

You can disable the SSL certificate verification in the communication between Kyma and a Remote Environment to allow Kyma to send requests and data to an unsecured Remote Environment. Disabling the certificate verification can be useful in certain testing scenarios.

NOTE: By default, the SSL certificate verification is enabled when sending data and requests to every Remote Environment.

Follow these steps to disable SSL certificate verification for communication between Kyma and an existing Remote Environment:

  1. Edit the ec-default-proxy-service Deployment in the kyma-integration Namespace. Run:
    kubectl -n kyma-integration edit deployment ec-default-proxy-service
    
  2. Edit the Deployment in Vim. Select i to start editing.
  3. Find the skipVerify parameter and change its value to true.
  4. Select esc, type :wq, and select enter to write and quit.

Access the Application Connector on a local Kyma deployment

To access the Application Connector on a local deployment of Kyma, you must add the Kyma server certificate to the trusted certificate storage of your programming environment. This is necessary to connect the external solution to your local Kyma deployment, allow client certificate exchange, and API registration.

For example, to access the Application Connector from a Java environment, run this command to add the Kyma server certificate to the Java Keystore:

sudo {JAVA_HOME}/bin/keytool -import -alias “Kyma” -keystore {JAVA_HOME}/jre/lib/security/cacerts -file <KYMA_HOME>/installation/certs/workspace/raw/server.crt

Connector Service

The Connector Service generates client certificates which secure the communication between Kyma and the connected external solutions.

Generating a new client certificate is the first step in the process of configuring a Remote Environment (RE). Kyma stores the root certificate and serves as the Certificate Authority when you configure a new RE. When you generate a new client certificate, the Connector Service returns it along with the root certificate to allow validation.

This diagram illustrates the client certificate generation flow in details: Client certificate generation operation flow

  1. The administrator requests for a token using the CLI or the UI and receives a link with the token, which is valid for a limited period of time.
  2. The administrator passes the token to the external system, which requests for information regarding the Kyma installation. In the response, it receives the following information:
    • the URL to which a third-party solution sends its Certificate Signing Request (CSR)
    • URLs of the available APIs
    • information required to generate a CSR
  3. The external system generates a CSR based on the information provided by Kyma and sends the CSR to the designated URL. In the response, the external system receives a signed certificate. It can use the certificate to authenticate and safely communicate with Kyma.

Connector Service

The Connector Service exposes two separate APIs:

  • An internal API available in the Kyma cluster used to initiate certificate generation.
  • An external API exposed through Ingress used to finalize certificate generation.

Find the specification of both of these APIs here.

Alternatively, get the API specification directly from the Connector Service:

https://connector-service.{CLUSTER_DOMAIN}/v1/api.yaml

Run this command to access the API specification on a local Kyma deployment:

curl https://connector-service.kyma.local/v1/api.yaml

Consume applications through the Service Catalog

To consume an external solution connected to Kyma, you must register it as a Remote Environment. As a result of registering the external solution, ClusterServiceClasses are created in the Service Catalog.

External solution's services in the Service Catalog

The Example API is registered in Kyma with the targetUrl pointing to https://www.orders.com/v1/orders. The ID assigned to the API in the registration process is 01a702b8-e302-4e62-b678-8d361b627e49.

The Remote Environment Broker, which provides ServiceClasses to the Service Catalog, follows this naming convention for its objects:

re-{remote-environment-name}-{service-id}

The {service-id} is the service identifier assigned in the process of registration. The {remote-environment-name} is the name of the Remote Environment created in Kyma. It represents an instance of the connected external solution that owns the registered service. Such identifier used by the Remote Environment Broker is referred to as the name of a ClusterServiceClass in the Service Catalog.

This an example of a full ClusterServiceClass name:

re-ec-default-01a702b8-e302-4e62-b678-8d361b627e49

Service consumption

After you provision the Example API in the Environment of your choice using the Service Catalog, you can bind it to your application and consume it by calling the URL you get as a result of a successful binding.

This is a sample URL for the Example API:

re-ec-default-01a702b8-e302-4e62-b678-8d361b627e49.kyma-integration/orders

When you call this URL, the Proxy Service passes all requests to the https://www.orders.com/v1/orders address, which is the targetUrl registered for the Example API. You do not have to get an OAuth token and manually include it in the call as the Proxy Service does it for you automatically.

Metadata Service

The Metadata Service allows you to register the APIs and Event catalogs of the services exposed by the connected external solution.

The Metadata Service stores the data of all registered services in:

  • Remote Environment Custom Resource (CR), which stores the metadata of the service.
  • Minio bucket, which stores the API specification, Event catalog and documentation.
  • Kubernetes secrets, which stores sensitive data, such as OAuth credentials.

Kubernetes APIs interaction

The Metadata Service interacts with Kubernetes APIs to perform these tasks:

  • Modify the Remote Environment CR instance.
  • Create Secrets which contain client ID and client secret used to access OAuth-secured APIs.
  • Create the Access Service.

Metadata Service

You can get the API specification of the Metadata Service for a given version of the service using this command:

curl https://gateway.{CLUSTER_DOMAIN}/{RE_NAME}/v1/metadata/api.yaml

To access the API specification of the Metadata Service locally, provide the NodePort of the application-connector-nginx-ingress-controller.

To get the NodePort, run this command:

kubectl -n kyma-system get svc application-connector-nginx-ingress-controller -o 'jsonpath={.spec.ports[?(@.port==443)].nodePort}'

To access the specification, run:

curl https://gateway.kyma.local:{NODE_PORT}/{RE_NAME}/v1/metadata/api.yaml

Event Service

See this file for the Event Service API specification.

Proxy Service

The Proxy Service sends the requests from Lambda functions and services in Kyma to external APIs registered with the Metadata Service. The Proxy Service works in conjunction with the Access Service, which exposes the Proxy Service.

NOTE: The system creates an Access Service for every external API registered by the Metadata Service.

The following diagram illustrates how the Proxy Service interacts with other components and external APIs secured with OAuth.

Proxy Service Diagram

  1. A Lambda function calls the Access Service. The name of every Access Service follows this format: re-{remote-environment-name}-{service-id}
  2. The Access Service exposes the Proxy Service.
  3. The Proxy Service extracts the Remote Environment (RE) name and the service ID from the name of the Access Service name. Using the extracted RE name, the Proxy Service finds the respective RemoteEnvironment Custom Resource and obtains the information about the registered external API, such as the API URL and the OAuth server URL.
  4. The Proxy Service gets a token from the OAuth server.
  5. The Proxy Service calls the target API using the OAuth token.

Caching

To ensure optimal performance, the Proxy Service caches the OAuth tokens it obtains. If the service doesn't find a token valid for the call it makes, it gets a new token from the OAuth server. Additionally, the service caches ReverseProxy objects used to proxy the requests to the underlying URL.

Pass an access token in a request header

The Application Connector supports passing the access token directly in the request.

Passing the access token

If the user is already authenticated to the service deployed on Kyma, the access token can be passed in a custom Access-token header. If the Application Connector detects that the custom header is present, instead of obtaining a new token, it passes the received one as a Bearer token in the Authorization header.

Example

Find the example of passing the EC access token to the Application Connector using Lambda in the examples repository.

Create a new Remote Environment

The Remote Environment Controller provisions and de-provisions the necessary deployments for every created Remote Environment (RE).

NOTE: A Remote Environment represents a single connected external solution.

To create a new RE, run this command:

cat <<EOF | kubectl apply -f -
apiVersion: applicationconnector.kyma-project.io/v1alpha1
kind: RemoteEnvironment
metadata:
  name: {RE_NAME}
spec:
  description: {RE_DESCRIPTION}
  labels:
    region: us
    kind: production
EOF

Get the client certificate

After you create a Remote Environment (RE) in Kyma, it's time to connect it with an external solution, which allows to consume external APIs and Event catalogs of this solution. To accomplish this you must get the client certificate for the external solution and register its services.

This guide shows you how to get the client certificate.

Prerequisites

  • OpenSSL toolkit to create a Certificate Signing Request (CSR), keys, and certificates which fulfil high security standards.

Get the configuration URL with a token

Get the configuration URL with a token which allows you to get Kyma CSR configuration and URLs in Kyma required to connect your external solution to a created Remote Environment. Follow this steps to get it using the CLI:

  • Expose the Connector Service outside of Kubernetes using kubectl port-forward:

    kubectl -n=kyma-integration port-forward svc/connector-service-internal-api 8080:8080
    
  • Make a POST request to the tokens endpoint:

    curl -X POST http://localhost:8080/v1/remoteenvironments/{RE_NAME}/tokens
    

A successful call returns the following response:

  {
    "url":"{CONFIGURATION_URL_WITH_TOKEN}",
    "token":"example-token-123"
  }

Get the CSR information and configuration details from Kyma

Use the link you got in the previous step to fetch the CSR information and configuration details required to connect your external solution. Run:

curl {CONFIGURATION_URL_WITH_TOKEN}

NOTE: The URL you call in this step contains a token that is valid for a single call. If you need to get the configuration details once again, generate a new configuration URL with a valid token and call it again. You get a code 403 error if you call the same configuration URL more than once.

A successful call returns the following response:

{
    "csrUrl": "{CSR_SIGNING_URL_WITH_TOKEN}",
    "api":{
        "metadataUrl":      "https://gateway.{CLUSTER_DOMAIN}/{RE_NAME}/v1/metadata/services",
        "eventsUrl":        "https://gateway.{CLUSTER_DOMAIN}/{RE_NAME}/v1/events",
        "certificatesUrl":  "https://connector-service.{CLUSTER_DOMAIN}/v1/remoteenvironments/{RE_NAME}",
    },
    "certificate":{
        "subject":"OU=Test,O=Test,L=Blacksburg,ST=Virginia,C=US,CN={RE_NAME}",
        "extensions": "",
        "key-algorithm": "rsa2048",
    }
}

When you connect an external solution to a local Kyma deployment, you must set the NodePort of the application-connector-nginx-ingress-controller for the Metadata Service and for the Event Service.

  • To get the NodePort, run:
    kubectl -n kyma-system get svc application-connector-nginx-ingress-controller -o 'jsonpath={.spec.ports[?(@.port==443)].nodePort}'
    
  • Set it for the Metadata Service and the Event Service using these calls:
    curl https://gateway.kyma.local:{NODE_PORT}/{RE_NAME}/v1/metadata/services --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -k
    
    curl https://gateway.kyma.local:{NODE_PORT}/{RE_NAME}/v1/events --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -k
    

Generate a CSR and send it to Kyma

Generate a CSR using the values obtained in the previous step:

openssl genrsa -out generated.key 2048
openssl req -new -sha256 -out generated.csr -key generated.key -subj "/OU=OrgUnit/O=Organization/L=Waldorf/ST=Waldorf/C=DE/CN={RE_NAME}"
openssl base64 -in generated.csr

Send the encoded CSR to Kyma. Run:

curl -H "Content-Type: application/json" -d '{"csr":"BASE64_ENCODED_CSR_HERE"}' https://connector-service.{CLUSTER_DOMAIN}/v1/remoteenvironments/{RE_NAME}/client-certs?token=example-token-456

The response contains a valid client certificate signed by the Kyma Certificate Authority:

{
    "crt":"BASE64_ENCODED_CRT"
}

After you receive the certificate, decode it and use it in your application. Register the services of your external solution through the Metadata Service.

Register a service

This guide shows you how to register a service of your external solution in Kyma.

Prerequisites

Valid certificate signed by the Kyma Certificate Authority.

Register a service

To register a service, follow this template to prepare the request body:

{
  "provider": "example-provider",
  "name": "example-name",
  "description": "This is the long description of your service",
  "shortDescription": "Short description",
  "labels": {
    "example": "true"
  },
  "api": {
    "targetUrl": "https://httpbin.org/",
    "spec": {}
  },
  "events": {
    "spec": {
      "asyncapi": "1.0.0",
      "info": {
        "title": "PetStore Events",
        "version": "1.0.0",
        "description": "Description of all the events"
      },
      "baseTopic": "stage.com.some.company.system",
      "topics": {
        "petCreated.v1": {
          "subscribe": {
            "summary": "Event containing information about new pet added to the Pet Store.",
            "payload": {
              "type": "object",
              "properties": {
                "pet": {
                  "type": "object",
                  "required": [
                    "id",
                    "name"
                  ],
                  "example": {
                    "id": "4caad296-e0c5-491e-98ac-0ed118f9474e",
                    "category": "mammal",
                    "name": "doggie"
                  },
                  "properties": {
                    "id": {
                      "title": "Id",
                      "description": "Resource identifier",
                      "type": "string"
                    },
                    "name": {
                      "title": "Name",
                      "description": "Pet name",
                      "type": "string"
                    },
                    "category": {
                      "title": "Category",
                      "description": "Animal category",
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "documentation": {
    "displayName": "Documentation",
    "description": "Description",
    "type": "some type",
    "tags": ["tag1", "tag2"],
    "docs": [
        {
        "title": "Documentation title...",
        "type": "type",
        "source": "source"
        }
    ]
  }
}

Include the request body you prepared in this call:

curl -X POST -d '{YOUR_REQUEST_BODY}' https://gateway.{CLUSTER_DOMAIN}/{RE_NAME}/v1/metadata/services --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -k

On a local deployment run:

curl -X POST -d '{YOUR_REQUEST_BODY}' https://gateway.kyma.local:$NODE_PORT/{RE_NAME}/v1/metadata/services --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -k

A successful response returns the ID of the registered service:

{"id":"{YOUR_SERVICE_ID}"}

To check the details of a registered service, send this request:

curl https://gateway.{CLUSTER_DOMAIN}/{RE_NAME}/v1/metadata/services/{YOUR_SERVICE_ID} --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -k

On a local deployment run:

curl https://gateway.kyma.local:{NODE_PORT}/{RE_NAME}/v1/metadata/services/{YOUR_SERVICE_ID} --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -k

Bind a Remote Environment to an Environment

This guide shows you how to bind a Remote Environment (RE) to an Environment in Kyma. To execute the binding, create an EnvironmentMapping Custom Resource in the cluster. Follow the instructions to bind your Remote Environment to the production Environment.

Prerequisites

To complete this guide, your cluster must have at least one Remote Environment created.

Steps

  1. List all Remote Environments bound to the production Environment:

    kubectl get em -n production
    
  2. Bind a RE to an Environment. Run this command to create an EnvironmentMapping Custom Resource and apply it to the cluster:

    cat <<EOF | kubectl apply -f -
    apiVersion: applicationconnector.kyma-project.io/v1alpha1
    kind: EnvironmentMapping
    metadata:
     name: {NAME_OF_RE_TO_BIND}
     namespace: production
    EOF
    
  3. Check if the operation is successful. List all Environments to which your RE is bound:

    kubectl get em --all-namespaces -o jsonpath='{range .items[?(@.metadata.name=="{NAME_OF_YOUR_RE}")]}{@.metadata.namespace}{""}{end}'
    

RemoteEnvironment

The remoteenvironments.applicationconnector.kyma-project.io Custom Resource Definition (CRD) is a detailed description of the kind of data and the format used to register a Remote Environment (RE) in Kyma. The RemoteEnvironment Custom Resource defines the APIs that the RE offers. After creating a new Custom Resource for a given RE, the RE is mapped to appropriate ServiceClasses in the Service Catalog. To get the up-to-date CRD and show the output in the yaml format, run this command:

kubectl get crd remoteenvironments.applicationconnector.kyma-project.io -o yaml

Sample custom resource

This is a sample resource that registers the re-prod Remote Environment which offers one service.

apiVersion: applicationconnector.kyma-project.io/v1alpha1
kind: RemoteEnvironment
metadata:
  name: system_prod
spec:
  description: This is the system_production Remote Environment.
  labels:
    region: us
    kind: production

Custom resource parameters

This table lists all the possible parameters of a given resource together with their descriptions:

Parameter Mandatory Description
metadata.name YES Specifies the name of the CR.
spec.source NO Identifies the Remote Environment in the cluster.
spec.description NO Describes the connected Remote Environment.
spec.accessLabel NO Labels the RE when an EnvironmentMapping is created.
spec.labels NO Defines the labels of the RE.
spec.services NO Contains all services that the Remote Environment provides.
spec.services.id YES Identifies the service that the Remote Environment provides.
spec.services.identifier NO Provides an additional identifier of the ServiceClass.
spec.services.name NO Represents a unique name of the service used by the Service Catalog.
spec.services.displayName YES Specifies a human-readable name of the Remote Environment service. Parameter provided by the Metadata Service, do not edit.
spec.services.description NO Provides a short, human-readable description of the service offered by the RE. Parameter provided by the Metadata Service, do not edit.
spec.services.longDescription NO Provides a longer, human-readable description of the service offered by the RE. Parameter provided by the Metadata Service, do not edit.
spec.services.providerDisplayName YES Specifies a human-readable name of the Remote Environment service provider. Parameter provided by the Metadata Service, do not edit.
spec.services.tags NO Specifies additional tags used for better documentation of the available APIs. Parameter provided by the Metadata Service, do not edit.
spec.services.labels NO Specifies additional labels for the service offered by the RE. Parameter provided by the Metadata Service, do not edit.
spec.services.entries YES Contains the information about the APIs and Events that the service offered by the RE provides. Parameter provided by the Metadata Service, do not edit.
spec.services.entries.type YES Specifies the entry type: API or Event. Parameter provided by the Metadata Service, do not edit.
spec.services.entries.gatewayUrl NO Specifies the URL of the Application Connector. This field is required for the API entry type. Parameter provided by the Metadata Service, do not edit.
spec.services.entries.accessLabel NO Specifies the label used in Istio rules in the Application Connector. This field is required for the API entry type.
spec.services.entries.targetUrl NO Specifies the URL of a given API. This field is required for the API entry type. Parameter provided by the Metadata Service, do not edit.
spec.services.entries.oauthUrl NO Specifies the URL used to authorize with a given API. This field is required for the API entry type. Parameter provided by the Metadata Service, do not edit.
spec.services.entries.credentialsSecretName NO Specifies the name of the Secret which allows you to call a given API. This field is required if the spec.services.entries.oauthUrl is specified. Parameter provided by the Metadata Service, do not edit.

EnvironmentMapping

The environmentmappings.remoteenvironment.kyma.cx Custom Resource Definition (CRD) is a detailed description of the kind of data and the format used to enable APIs and Events from a Remote Environment as a ServiceClass in a given Namespace. To get the up-to-date CRD and show the output in the yaml format, run this command:

kubectl get crd environmentmappings.applicationconnector.kyma-project.io -o yaml

Sample custom resource

This is a sample resource in which the EnvironmentMapping enables the test Remote Environment in the production Environment:

apiVersion: applicationconnector.kyma-project.io/v1alpha1
kind: EnvironmentMapping
metadata:
  name: test
  namespace: production

Custom resource parameters

This table lists all the possible parameters of a given resource together with their descriptions:

Parameter Mandatory Description
metadata.name YES Specifies the name of the CR and the Remote Environment.
metadata.namespace YES Specifies the Namespace in which the Remote Environment is enabled.

These are the resources related to this CR:

Custom resource Description
RemoteEnvironment Uses this CR to expose RemoteEnvironment's services in a given Environment.

These components use this CR:

Component Description
Remote Environment Broker Uses this CR to enable the provisioning of ServiceClasses in a given Environment.
UI API Layer Uses this CR to filter enabled RemoteEnvironments. It also allows you to create or delete EnvironmentMappings.

Trigger a lambda with events

This guide shows how to create a simple lambda function and trigger it with an event.

Prerequisites

  • A Remote Environment (RE) bound to the production Environment
  • Client certificates generated for the connected RE.

Steps

  1. Register a service with the following specification to the desired Remote Environment.

    NOTE: To learn how to register a service, see the Register a service Getting Started Guide.

    {
    "name": "my-service",
    "provider": "myCompany",
    "Identifier": "identifier",
    "description": "This is some service",
    "events": {
     "spec": {
       "asyncapi": "1.0.0",
       "info": {
         "title": "Example Events",
         "version": "1.0.0",
         "description": "Description of all the example events"
       },
       "baseTopic": "example.events.com",
       "topics": {
         "exampleEvent.v1": {
           "subscribe": {
             "summary": "Example event",
             "payload": {
               "type": "object",
               "properties": {
                 "myObject": {
                   "type": "object",
                   "required": [
                     "id"
                   ],
                   "example": {
                     "id": "4caad296-e0c5-491e-98ac-0ed118f9474e"
                   },
                   "properties": {
                     "id": {
                       "title": "Id",
                       "description": "Resource identifier",
                       "type": "string"
                     }
                   }
                 }
               }
             }
           }
         }
       }
     }
    }
    }
    
  2. Get the externalName of the Service Class of the registered service.

    kubectl -n production get serviceclass {SERVICE_ID}  -o jsonpath='{.spec.externalName}'
    
  3. Create a Service Instance for the registered service.

    cat <<EOF | kubectl apply -f -
    apiVersion: servicecatalog.k8s.io/v1beta1
    kind: ServiceInstance
    metadata:
    name: my-service-instance-name
    namespace: production
    spec:
    serviceClassExternalName: {EXTERNAL_NAME}
    EOF
    
  4. Create a sample lambda function which sends a request to http://httpbin.org/uuid. A successful response logs a Response acquired successfully! Uuid: {RECEIVED_UUID} message. To create and register the lambda function in the production Environment, run:

    cat <<EOF | kubectl apply -f -
    apiVersion: kubeless.io/v1beta1
    kind: Function
    metadata:
    name: my-lambda
    namespace: production
    spec:
    deployment:
     spec:
       template:
         spec:
           containers:
           - name: ""
             resources: {}
    deps: |-
     {
         "name": "example-1",
         "version": "0.0.1",
         "dependencies": {
           "request": "^2.85.0"
         }
     }
    function: |-
     const request = require('request');
    
     module.exports = { main: function (event, context) {
         return new Promise((resolve, reject) => {
             const url = `http://httpbin.org/uuid`;
             const options = {
                 url: url,
             };
    
             sendReq(url, resolve, reject)
         })
     } }
    
     function sendReq(url, resolve, reject) {
         request.get(url, { json: true }, (error, response, body) => {
             if(error){
                 resolve(error);
             }
             console.log("Response acquired successfully! Uuid: " + response.body.uuid);
             resolve(response);
         })
     }
    function-content-type: text
    handler: handler.main
    horizontalPodAutoscaler:
     spec:
       maxReplicas: 0
    runtime: nodejs8
    service:
     ports:
     - name: http-function-port
       port: 8080
       protocol: TCP
       targetPort: 8080
     selector:
       created-by: kubeless
       function: my-lambda
    timeout: ""
    topic: exampleEvent
    EOF
    
  5. Create a Subscription to allow events to trigger the lambda function.

    cat <<EOF | kubectl apply -f -
    apiVersion: eventing.kyma.cx/v1alpha1
    kind: Subscription
    metadata:
    labels:
     Function: my-lambda
    name: lambda-my-lambda-exampleevent-v1
    namespace: production
    spec:
    endpoint: http://my-lambda.production:8080/
    event_type: exampleEvent
    event_type_version: v1
    include_subscription_name_header: true
    max_inflight: 400
    push_request_timeout_ms: 2000
    source_id: {RE_NAME}
    EOF
    
  6. Send an event to trigger the created lambda.

    • On a cluster:
      curl -X POST https://gateway.{CLUSTER_DOMAIN}/{RE_NAME}/v1/events -k --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -d     '{
         "event-type": "exampleEvent",
         "event-type-version": "v1",
         "event-id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
         "event-time": "2018-10-16T15:00:00Z",
         "data": "some data"
      }'
      
    • On a local deployment:
      curl -X POST https://gateway.kyma.local:{NODE_PORT}/{RE_NAME}/v1/events -k --cert {CERT_FILE_NAME}.crt --key {KEY_FILE_NAME}.key -d     '{
         "event-type": "exampleEvent",
         "event-type-version": "v1",
         "event-id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
         "event-time": "2018-10-16T15:00:00Z",
         "data": "some data"
      }'
      
  7. Check the logs of the lambda function to see if it was triggered. Every time an event successfully triggers the function, this message appears in the logs: Response acquired successfully! Uuid: {RECEIVED_UUID}. Run this command:

    kubectl -n production logs "$(kubectl -n production get po -l function=my-lambda -o jsonpath='{.items[0].metadata.name}')" -c my-lambda | grep "Response acquired successfully! Uuid: "
    

Call a registered external service from Kyma

This guide shows how to call a registered external service from Kyma using a simple lambda function.

Prerequisites

  • A Remote Environment (RE) bound to the production Environment
  • Client certificates generated for the connected RE.
  • Map the my-lambda-production.kyma.local to your Minikube IP to call the lambda function on a local Kyma deployment.

Steps

  1. Register a service with the following specification to the desired Remote Environment.

    NOTE: To learn how to register a service, see the Register a service Getting Started Guide.

    {
    "name": "my-service",
    "provider": "myCompany",
    "Identifier": "identifier",
    "description": "This is some service",
    "api": {
     "targetUrl": "http://httpbin.org/",
     "spec": {
       "swagger":"2.0"
     }
    }
    }
    
  2. Get the externalName of the Service Class of the registered service.

    kubectl -n production get serviceclass {SERVICE_ID}  -o jsonpath='{.spec.externalName}'
    
  3. Create a Service Instance for the registered service.

    cat <<EOF | kubectl apply -f -
    apiVersion: servicecatalog.k8s.io/v1beta1
    kind: ServiceInstance
    metadata:
    name: my-service-instance-name
    namespace: production
    spec:
    serviceClassExternalName: {EXTERNAL_NAME}
    EOF
    
  4. Create a lambda function that sends a request to the registered service with an additional path of /uuid. A successful response returns a UUID generated by httpbin.org. To create and register the lambda function in the production Environment, run:

    cat <<EOF | kubectl apply -f -
    apiVersion: kubeless.io/v1beta1
    kind: Function
    metadata:
    name: my-lambda
    namespace: production
    spec:
    deployment:
     spec:
       template:
         metadata:
           labels:
             re-{RE_NAME}-{SERVICE_ID}: "true"
         spec:
           containers:
           - env:
             - name: GATEWAY_URL
               value: re-{RE_NAME}-{SERVICE_ID}.kyma-integration
    deps: |-
     {
         "name": "example-1",
         "version": "0.0.1",
         "dependencies": {
           "request": "^2.85.0"
         }
     }
    function: |-
     const request = require('request');
    
     module.exports = { main: function (event, context) {
         return new Promise((resolve, reject) => {
             const url = `http://${process.env.GATEWAY_URL}/uuid`;
             const options = {
                 url: url,
             };
    
             sendReq(url, resolve, reject)
         })
     } }
    
     function sendReq(url, resolve, reject) {
         request.get(url, { json: true }, (error, response, body) => {
             if(error){
                 resolve(error);
             }
             resolve(response.body);
         })
     }
    function-content-type: text
    handler: handler.main
    horizontalPodAutoscaler:
     spec:
       maxReplicas: 0
    runtime: nodejs8
    service:
     ports:
     - name: http-function-port
       port: 8080
       protocol: TCP
       targetPort: 8080
     selector:
       created-by: kubeless
       function: my-lambda
    timeout: ""
    topic: http
    EOF
    
  5. Create a ServiceBinding and a ServiceBindingUsage to bind the Service Instance to the lambda function.

cat <<EOF | kubectl apply -f -
apiVersion: servicecatalog.k8s.io/v1beta1
kind: ServiceBinding
metadata:
  labels:
    Function: my-lambda
  name: my-service-binding
  namespace: production
spec:
  instanceRef:
    name: my-service-instance-name
EOF
cat <<EOF | kubectl apply -f -
apiVersion: servicecatalog.kyma.cx/v1alpha1
kind: ServiceBindingUsage
metadata:
  labels:
    Function: my-lambda
    ServiceBinding: my-service-binding
  name: my-service-binding
  namespace: production
spec:
  serviceBindingRef:
    name: my-service-binding
  usedBy:
    kind: function
    name: my-lambda
EOF
  1. To expose the lambda function outside the cluster create an Api custom resource:

    cat <<EOF | kubectl apply -f -
    apiVersion: gateway.kyma.cx/v1alpha2
    kind: Api
    metadata:
    labels:
     function: my-lambda
    name: my-lambda
    namespace: production
    spec:
    authentication: []
    hostname: my-lambda-production.{CLUSTER_DOMAIN}
    service:
     name: my-lambda
     port: 8080
    EOF
    
  2. To verify that everything was setup correctly you can now call the lambda through https:

    • On a cluster
      curl https://my-lambda-production.{CLUSTER_DOMAIN}/ -k
      
    • On a local deployment:
      curl https://my-lambda-production.kyma.local/ -k
      

A successful response returns a UUID generated by httpbin.org:

{
  "uuid": "d44cc373-b26e-4a36-9890-6418d131a285"
}