Edge Serverless and Event-Driven Architectures with Knative and Cloud Events
local graph
Chapter 9 — Edge Serverless and Event-Driven Architectures with Knative and Cloud Events
Section titled “Chapter 9 — Edge Serverless and Event-Driven Architectures with Knative and Cloud Events”Serverless architecture reduces the costs of running distributed systems at scale. This use case is particularly useful in edge computing, where a lot of dedicated hardware and computational resources are used. This chapter covers how Knative can help you to implement APIs using serverless technologies. It also shows how to reduce costs and complexity using Knative for simple event-driven architectures and serverless functions to build your system. Across the chapter, we explain how Knative uses Cloud Events for its cloud event specification to call events, and how serverless can be helpful in the development of event-driven applications.
In this chapter, we’re going to cover the following main topics:
- Serverless at the edge with Knative and Cloud Events
- Implementing serverless functions using Knative Serving
- Implementing a serverless API using traffic splitting with Knative
- Using declarative files in Knative
- Implementing events and event-driven pipelines using sequences with Knative Eventing
Technical requirements
Section titled “Technical requirements”For this chapter, you need the following:
- A single or multi-node K3s cluster using ARM devices with MetalLB installed and with the options to avoid Traefik being installed as the default ingress controller.
- kubectl configured to be used on your local machine to avoid using the
--kubeconfigparameter. - Clone the repository at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch9 if you want to run the YAML configuration by using
kubectl applyinstead of copying the code from the book. Take a look at the code for Python and YAML configurations inside thech9directory.
We are going to install Knative to implement simple use cases using serverless APIs and event-driven pipelines. Let’s understand what serverless architectures are and how can they help in edge computing environments.
Serverless at the edge with Knative and Cloud Events
Section titled “Serverless at the edge with Knative and Cloud Events”Edge computing is a paradigm that processes information near the source of data. This improves the response time of the application. It also saves bandwidth when the data is accessed because instead of getting data from the cloud, data is accessed near to the source. But one of the problems is that the services are always up and running. Here is where serverless can help to reduce costs, scaling down services when they are not used, helping to reduce additional costs compared with the traditional way of having services running all the time.
Ben Ellerby, in his Medium article called Why Serverless will enable the Edge Computing Revolution, mentions that Serverless enables us to build applications and services without thinking about the underlying servers. This refers to thinking more about the applications instead of managing infrastructure. In this way, serverless technologies and cloud services have been increasing in popularity in recent years. Serverless cloud services only charge you for the execution time when you are using the service. You can often find serverless services as small code functions. Serverless technologies enabled event-driven architectures to flourish, because of their simplicity and low cost to implement new functionalities. According to the https://solace.com/ website, an event-driven architecture is a software design pattern in which decoupled applications can asynchronously publish and subscribe to events via an event broker (modern messaging-oriented-middleware).
One of the key aspects to evaluate when building a new system is the cost of implementation. This will be a common scenario for choosing serverless technologies. Serverless technologies implemented in on-premises scenarios could take advantage of the temporal use of resources to execute serverless functions. Knative implements serverless functions and events that can be used to implement event-driven applications. In addition, an event specification such as Cloud Events can help to standardize the communication of your services and define events:

Figure 9.1 – Knative architecture
Knative was born in Google, and it was given to the community as an open source project. Knative consists of two parts: Serving and Eventing. With Knative Serving, you can create serverless functions in Kubernetes. Knative Serving implements the features of networking, autoscaling, and revision tracking. This abstraction gives the user the ability to focus more on the logic of the business instead of managing infrastructure. On the other hand, Knative Eventing gives the user the ability to implement event-driven architectures and call functions created with the Serving feature. You can configure your events to use different sources and broker types to manage your events depending on your use case. After choosing a source and broker that fit your scenario, you can trigger sequences or simple calls of your functions.
Cloud Events works together with Knative to give a standard structure to the events and have a uniform way to declare and call events. Cloud Events follows an event specification that is used to implement events. This structure has been adopted for different open source projects such as OpenFaaS, Tekton, Argo Events, Falco, Google Cloud Eventarc, and so on. The Cloud Events SDK is available for different programming languages such as Python and Go. This SDK will help you to describe cloud events through definitions such as ID, version of the cloud event specification, type, source, and content type.
Knative and Cloud Events provide a way to implement serverless functions and event-driven architectures at the edge, for low-resource devices, and a lightweight implementation that permits cost-saving in an edge computing scenario.
Important Note
For more information about Knative, you can visit its official documentation: https://knative.dev/docs. For Cloud Events, you can visit its official website: https://cloudevents.io or its specification 1.0, which is used in our examples: https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md.
Implementing serverless functions using Knative Serving
Section titled “Implementing serverless functions using Knative Serving”To start building our simple use cases for serverless and event-driven use cases, we have to install Knative with Serving, Eventing, channels, and brokers. In this case, we are going to use the basic options using in-memory channels and Knative Eventing Sugar Controller, which creates Knative resources based on labels in your cluster or namespace. So, let’s start installing Knative Serving in the next section.
Installing Knative Serving
Section titled “Installing Knative Serving”In this section, we are going to start installing Knative Serving, which will be used to implement serverless functions. Let’s follow the next steps to install Knative Serving:
- Install the Knative CLI with the following command:
$ brew install kn
To upgrade your current Knative binary, run the following:
$ brew upgrade kn- Install the Knative Serving CRDs to install the serving components:
$ kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.2.0/serving-crds.yaml$ kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.2.0/serving-core.yaml
Note
To learn more about Custom Resource Definitions (CRDs) you can check out this link: https://docs.openshift.com/aro/3/dev_guide/creating_crd_objects.html. You can also check the CRD documentation from the Kubernetes official website with the next link: https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources.
- Now install the Contour ingress controller, which will be used as the default for Knative (this component is available for ARM):
$ kubectl apply -f https://github.com/knative/net-contour/releases/download/knative-v1.2.0/contour.yaml
- Install the network component of Knative for other functionalities using the previous ingress running the following command:
$ kubectl apply -f https://github.com/knative/net-contour/releases/download/knative-v1.2.0/net-contour.yaml
- Then set Contour as the default ingress controller to be used by Knative:
$ kubectl patch configmap/config-network \--namespace knative-serving \--type merge \--patch '{"data":{"ingress-class":"contour.ingress.networking.knative.dev"}}'
- Get the IP that your Contour ingress controller created as the endpoint for your applications. In this case, we are going to call this IP
EXTERNAL_IP:$ EXTERNAL_IP="$(kubectl get svc envoy -n contour-external -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')" - Set the domain that Knative is going to use to expose your serverless applications:
$ KNATIVE_DOMAIN="$EXTERNAL_IP.nip.io"$ kubectl patch configmap/config-domain \--namespace knative-serving \--type merge \--patch '{"data":{"'$KNATIVE_DOMAIN'":""}}'
- Now set the Horizontal Pod Autoscaler (HPA) feature of Knative Serving to run:
$ kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.2.0/serving-hpa.yaml
- Finally, perform simple troubleshooting for the Knative components running:
$ kubectl get pods -n knative-serving
This will return the state of the pods of your Knative Serving installation. These pods should have a ready status after a few minutes.
Important Note
To uninstall the components, you can use kubectl delete instead of kubectl apply.
Now Knative Serving is installed and ready to use. So, let’s move on to create a simple serverless function using Knative Serving in the next section.
Creating a simple serverless function
Section titled “Creating a simple serverless function”Now it’s time to use Knative Serving. In this section, we are going to run a sample API using Python and Flask. The code will look like this:
from flask import Flaskfrom flask import jsonifyimport osimport socketapp = Flask(__name__)host = socket.gethostname()msg = os.environ['MESSAGE']@app.route('/')def index(): return jsonify({"host":host,"msg":msg})if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)Every time you call the function, it is going to return the variable host with the container ID and msg with the value of the MESSAGE environment variable. This API will use port 5000. This Python program is already packaged in a container. It was built and published on Docker Hub as sergioarmgpl/app2demo.
Important Note
You can explore how to build and customize this code in the GitHub repository: https://github.com/sergioarmgpl/containers.
Now, to deploy this API as a serverless function using Knative, follow the next steps:
- Create your function with the following command:
$ kn service create api \--image sergioarmgpl/app2demo \--port 5000 \--env MESSAGE="Knative demo v1" \--revision-name=v1
This command redirects port 5000 where your API is exposed in your container to the HTTP endpoint that Knative generates. It also receives the MESSAGE parameter with the Knative demo value and sets the revision of this function as v1. After running this command, you will get an output like this:
Service 'api' created to latest revision 'api-v1' is available at URL:http://api.default.192.168.0.54.nip.ioAt the end of the output, you will find the endpoint for your function. In this output, we are assuming that the IP address assigned to the Contour ingress controller is 192.168.0.54, which is the same value assigned to the EXTERNAL_IP variable. Knative creates the necessary pods for this function in the default namespace. Refer to the Installing Knative Serving section for more information about to how to get the IP assigned to your Contour ingress.
- Now, access your function using the
EXTERNAL_IPvariable defined in the Installing Knative Serving section, by running the following command:$ curl http://api.default.$EXTERNAL_IP.nip.io
This command will return a JSON output in your terminal like this:
{ "host": "api-v1-deployment-84f568857d-cxv9z", "msg": "Knative demo v1"}- To monitor the pods created for your function, run this:
$ watch kubectl get pods
- After 2 minutes of inactivity for your functions, the pods created to run your functions will be scaled down. If you execute
watch kubectl get pods, you will see a similar output to this:NAME READY STATUSapi-v1 2/2 Runningapi-v1 2/2 Terminatingapi-v1 1/2 Terminatingapi-v1 0/2 Terminating - Open another terminal and execute
watch kubectl get pods, and then call the function again. The pods of the function will be scaled up and you will see a similar output to this:NAME READY STATUSapi-v1 0/2 Pendingapi-v1 0/2 ContainerCreatingapi-v1 1/2 Runningapi-v1 2/2 Running
With the scaling to zero functionality, you can cut costs in your cloud infrastructure when your functions have an idle status after 2 minutes of inactivity.
Important Note
The watch command might not be installed on your operating system. This can be installed with the yum or apt command on Linux, or the brew command on macOS.
- Check the created services in the default namespace using the following command:
$ kn service list
Or, run the following command to check the available functions in a specific namespace:
$ kn service list -n <YOUR_NAMESPACE>- To check your current revisions, run the following:
$ kn revisions list
- (Optional) If you don’t want to create a public endpoint for your function, use the
--cluster-localflag for thekncommand to create a private endpoint. To create the same function but with a private endpoint, use the following command:$ kn service create api --cluster-local \--image sergioarmgpl/app2demo \--port 5000 \--env MESSAGE="Knative demo v1" \--revision-name=v1
At the end of the output, you will see something like this:
Service 'api' created to latest revision 'api-v1' is available at URL:http://api.default.svc.cluster.localThis endpoint will be the URL service that Knative creates for you, which is the same service object used in Kubernetes.
- (Optional) To access this endpoint, you have to call it inside the cluster. To do this, create a client container that contains
curl. Run the following command:$ kubectl run curl -it --rm --image=curlimages/curl:7.81.0 /bin/sh
Once the pod is created, you have to run the following command to access the function:
$ curl http://api.default.svc.cluster.localThe output will look like this:
{ "host": "api-v1-deployment-776c896776-vxhhk", "msg": "Knative demo v1"}- To delete the serverless function created in this section, run this:
$ kn service delete hello
Now, you know how to create serverless functions to implement a simple API using Knative Serving and scale to zero functionality to save costs. It’s time to implement the traffic splitting functionality using Knative Serving in the next section.
Implementing a serverless API using traffic splitting with Knative
Section titled “Implementing a serverless API using traffic splitting with Knative”Knative has traffic splitting functionality that consists of distributing the traffic across two or more versions within a service but uses a proxy to implement this feature. By default, it uses Istio. For this implementation, we are using Contour, an Envoy-based proxy that consumes fewer resources than Istio. Both Istio and Contour use Envoy, a layer 7 proxy to implement service mesh capabilities such as traffic splitting. Traffic splitting could be used to implement deployment strategies such as canary and blue-green deployments, and also could be used to simulate faulty traffic for some basic chaos engineering scenarios. In this section, we are going to implement traffic splitting for the previous API function created in the Creating a simple serverless function section. In that section, we created a function called api with the revision name v1. Now we are going to update this function with another revision called v2. This revision just changes the MESSAGE value that is shown when you call the function. For this example, we are going to split traffic with 50% to revision v1 and 50% to revision v2.
To implement this scenario, follow the next steps:
- Update the current
apifunction with the new revision,v2, which has the value of theMESSAGEvariable withKnative demo v2, for this run:$ kn service update api \--env MESSAGE="Knative demo v2" \--revision-name=v2
The output of this command will look like this:
Service hello created to latest revision 'api-v2' is available at URL: http://api.default.192.168.0.54.nip.io- Let’s check the revisions of our
apifunction with the following command:$ kn revisions list
With this command, you will see that 100% of the traffic will be processed by the v2 revision. The output will look like this:
NAME SERVICE TRAFFICapi-v2 api 100%api-v1 apiImportant Note
We are omitting the TAGS, GENERATION, AGE, CONDITIONS, READY, and REASON fields of the output for learning purposes. We are assuming that the IP address assigned to the Contour ingress controller is 192.168.0.54, which is the same value assigned to the EXTERNAL_IP variable.
- Set the traffic splitting to 50% for version
v1and 50% for versionv2:$ kn service update api \--traffic api-v1=50 \--traffic @latest=50
The expected output will look like this:
Service 'api' with latest revision 'api-v2' (unchanged) is available at URL:http://api.default.192.168.0.54.nip.ioYou can also use api-v2 instead of the @latest option. You can also customize your parameter with your own versions and different traffic splitting rates.
- Let’s check how traffic is distributed across the
apifunction after setting the traffic splitting by running this:$ kn revisions list
The output will look like this:
NAME SERVICE TRAFFICapi-v2 api 50%api-v1 api 50%You will see that the traffic is split by 50% for each revision.
- Let’s send traffic to our function with a simple
BASHloop script that you can stop with Ctrl + C by running the following command:$ while true; do curl http://api.default.$EXTERNAL_IP.nip.io;echo "";sleep 0.3; done
This command is going to continuously call your function that is split in to two versions every 0.3 seconds. The latest available revision will be running by default. In this case revision v2 will be available for responses. After waiting a few seconds v1 is provisioned and the output starts to show that the traffic is split by 50% for each revision. The output will look something like this:
{ "host": "api-v1-deployment-85f6f977b5-hcgdz", "msg": "Knative demo v1"}
{ "host": "api-v1-deployment-85f6f977b5-hcgdz", "msg": "Knative demo v2"}Use Ctrl + C to stop the BASH loop.
- If you want to check the pods of this traffic splitting, run the following command:
$ kubectl get pods -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase
The output will look like this:
NAME STATUSapi-v1-deployment-85f6f977b5-jhss5 Runningapi-v2-deployment-b97859489-mtvjm RunningIn this output, there are two pods running – one for revision v1 and the other for v2. These pods are created on demand. By the default one of these revisions will be running if idle time was not exceeded to be called down. After requests start coming, the other revision is scaled up to start splitting the traffic between these pods by 50% each.
- Finally, you can delete your API function with all your revisions running:
$ kn service delete api
Now you have learned how to use traffic splitting and revisions in Knative. Now let’s go deep into Knative, learning how to use declarative files to create services in the next section.
Using declarative files in Knative
Section titled “Using declarative files in Knative”A good practice when creating environments is to create declarative definitions for your applications. Knative supports this with the --target flag. For example, if you want to change the previous example into a YAML file, you could use this flag. To do this, run the following command:
$ kn service create api --cluster-local \--image sergioarmgpl/app2demo \--port 5000 \--env MESSAGE="Knative demo v1" \--revision-name=v1 --target=api.yamlThis command outputs a YAML file with the definition of an API function, without a public endpoint. The output in the api.yaml file will look like this:
apiVersion: serving.knative.dev/v1kind: Servicemetadata: labels: networking.knative.dev/visibility: cluster-local name: api namespace: defaultspec: template: metadata: annotations: autoscaling.knative.dev/max-scale: "5" containerConcurrency: 2 name: api-v1 spec: containers: - env: - name: MESSAGE value: "Knative demo v1" image: sergioarmgpl/app2demo name: "" ports: - containerPort: 5000In the annotations section, you can configure different features that Knative provides; for example, autoscaling, rate limits, concurrency, and so on. In this case, we used autoscaling.knative.dev/max-scale to set the maximum replicas for the deployment of the function and containerConcurrency to set the number of simultaneous requests for each replica in the function.
Another example is how you can define the YAML for traffic splitting. Based on our previous traffic splitting example in the Implementing a serverless API using traffic splitting with Knative section, to generate the equivalent YAML configuration use the following command:
$ kn service update api \--traffic api-v1=50 \--traffic @latest=50 --target=api.yamlThe output will look like this:
apiVersion: serving.knative.dev/v1kind: Servicemetadata: labels: networking.knative.dev/visibility: cluster-local name: api namespace: defaultspec: traffic: - latestRevision: true percent: 50 - latestRevision: false percent: 50 revisionName: api-v1 template: metadata: annotations: autoscaling.knative.dev/max-scale: "5" containerConcurrency: "2" name: api-v1 spec: containers: - env: - name: MESSAGE value: "Knative demo v1" image: sergioarmgpl/app2demo name: "" ports: - containerPort: 5000This is a desirable feature and best practice. To have declarative definitions for creating your functions and other Knative objects, you can explore the official documentation of Knative to find examples of declarative definitions. Now it’s time to move on to install another feature, Knative Eventing, in the next section.
Implementing events and event-driven pipelines using sequences with Knative Eventing
Section titled “Implementing events and event-driven pipelines using sequences with Knative Eventing”Knative provides Eventing components to implement event-driven architectures. We are going to explore a simple Eventing pipeline with Knative using the lightweight in-memory channel component to implement two simple events that call a service showing a message. In the second part, we are going to implement a simple sequence that calls two servers sequentially, one after the other, showing custom messages. So, let’s get started with the first part to implement simple events.
Installing Knative Eventing
Section titled “Installing Knative Eventing”Before creating our events, we need to install all the Knative components. We are going to use the in-memory channel to manage our events, which is the simplest and most lightweight channel implemented in Knative, and Sugar Controller to provision Knative Eventing resources in namespaces using labels. To get started with installing Knative Eventing, follow the next steps:
- Install the Knative Eventing CRDs:
$ kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.2.0/eventing-crds.yaml
- Install Knative Eventing core components by running the following command:
$ kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.2.0/eventing-core.yaml
- Now install the in-memory channel component by running this:
$ kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.2.0/in-memory-channel.yaml
- Now install the MT channel broker, which is a lightweight and simple implementation to use the in-memory channel:
$ kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.2.0/mt-channel-broker.yaml
- Finally, install Knative Eventing Sugar Controller, which reacts to special labels and annotations and produces Eventing resources:
$ kubectl apply -f https://github.com/knative/eventing/releases/download/knative-v1.2.0/eventing-sugar-controller.yaml
- Check whether all the components have a
READYstatus by running the following command:$ kubectl get pods -n knative-eventing -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase
You will see a similar output to this:
NAME STATUSmt-broker-filter-574dc4457f-pjs7z Runningimc-dispatcher-7fcb4b5d8c-qxrq2 Runningmt-broker-controller-8d979648f-6st56 Runningsugar-controller-6dd4c4bc5f-76kqc Runningmt-broker-ingress-5ddd6f8b5d-h94z5 Runningeventing-webhook-5968f79978-5nhlc Runningeventing-controller-58875c5478-n8xzl Runningimc-controller-86cd7b7857-hpcpq RunningNow you have installed all the necessary components to implement a simple event-driven pipeline using Knative. Let’s move to the next section to learn how to implement events.
Implementing a simple event
Section titled “Implementing a simple event”Now it’s time to implement some basic events. This scenario consists of creating two services and calling them with their attribute type. First, let’s explore the code inside the container that is in Docker Hub called sergioarmgpl/app3demo. The code used is this:
from flask import Flask, requestfrom cloudevents.http import from_httpapp = Flask(__name__)
@app.route("/", methods=["POST"])def route(): event = from_http(request.headers, request.get_data()) app.logger.warning(event) return "", 204
if __name__ == "__main__": app.run(debug=True, host='0.0.0.0',port=5000)This code receives the call and transforms the data of the requests using the Cloud Events library to output the event with the app.logger.warning function implemented in Flask. So, every time the application is called in the / route path, it is going to show the information of the request that is calling the container using the Cloud Events structure format in the logs. In this case, we are not returning any data in response. It just returns HTTP status response code 204, which refers to a successful request call. You can also customize this code if necessary to fit your needs.
Now we have to create two services using YAML definitions. The first service will be called api-demo, and the second api-demo2. These services will be called every time the broker is called, sending their cloud event’s attributes. When the attribute type is set to event.show, the api-demo service is called, and when the broker is called with the attribute type set to event.show.2, the api-demo2 service will be called. Both services are configured to listen on port 5000 and forward requests to port 80 to properly work with Knative Eventing.
To start implementing the first scenario, follow the next steps:
- Create and inject the
event-demonamespace where the event is going to be created:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Namespacemetadata:name: event-demolabels:eventing.knative.dev/injection: enabledEOF - Create the default broker to use for this implementation:
$ cat <<EOF | kubectl apply -f -apiVersion: eventing.knative.dev/v1kind: Brokermetadata:name: defaultnamespace: event-demoannotations:eventing.knative.dev/broker.class: MTChannelBasedBrokerEOF
- Deploy the container that is going to process the event:
$ cat <<EOF | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata:labels:app: api-demoname: api-demonamespace: event-demospec:replicas: 1selector:matchLabels:app: api-demotemplate:metadata:labels:app: api-demospec:containers:- image: sergioarmgpl/app3demoname: app3demoimagePullPolicy: AlwaysEOF
- Create the service for this
api-demodeployment:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata:labels:app: api-demoname: api-demonamespace: event-demospec:ports:- port: 80protocol: TCPtargetPort: 5000selector:app: api-demotype: ClusterIPEOF - Create a trigger to be consumed by the service:
$ cat <<EOF | kubectl apply -f -apiVersion: eventing.knative.dev/v1kind: Triggermetadata:name: api-demonamespace: event-demospec:broker: defaultfilter:attributes:type: event.showsubscriber:ref:apiVersion: v1kind: Servicename: api-demoEOF
- Create a pod in the
event-demonamespace to call the broker. This broker is going to call our pod that shows the message Simple Event using Knative. To create this pod, run this:$ kubectl run -n event-demo curl -it --rm --image=curlimages/curl:7.81.0 /bin/sh - Inside this pod, run the
curlcommand to send a request to the broker. The broker will take the parameters of the previously implemented cloud event to send it to your pod. To call the broker, run this:$ curl -v "broker-ingress.knative-eventing.svc.cluster.local/event-demo/default" \-X POST \-H "Ce-Id: call-api-demo" \-H "Ce-specversion: 1.0" \-H "Ce-Type: event.show" \-H "Ce-Source: test-send" \-H "Content-Type: application/json" \-d '{"msg":"Simple Event using Knative."}'
The output will look like this:
* Connected to broker-ingress.knative-eventing.svc.cluster.local (10.43.130.39) port 80 (#0)> POST /event-demo/default HTTP/1.1> Host: broker-ingress.knative-eventing.svc.cluster.local> User-Agent: curl/7.81.0-DEV> Accept: */*> Ce-Id: 536808d3-88be-4077-9d7a-a3f162705f79> Ce-specversion: 0.3> Ce-Type: dev.knative.myevents.api-demo> Ce-Source: dev.knative.myevents/api-demo-source> Content-Type: application/json> Content-Length: 37>* Mark bundle as not supporting multiuse< HTTP/1.1 202 Accepted< Allow: POST, OPTIONS< Date: Thu, 24 Feb 2022 05:30:13 GMT< Content-Length: 0<* Connection #0 to host broker-ingress.knative-eventing.svc.cluster.local left intact- To exit, run the next command inside the pod:
$ exit
- Now inspect the logs of the pod by running the following command:
$ kubectl -n event-demo logs -l app=api-demo --tail=50
Or, if you want to see the log in real time, when you call the broker that calls your pod, run the following command:
$ kubectl -n event-demo logs -f -l app=api-demoThe output will look like this:
* Serving Flask app 'index' (lazy loading)* Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Debug mode: on* Running on all addresses. WARNING: This is a development server. Do not use it in a production deployment.* Running on http://10.42.0.42:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 110-221-376[2022-02-27 06:02:02,107] WARNING in index: {'attributes': {'specversion': '1.0', 'id': 'call-api-demo', 'source': 'test-send', 'type': 'event.show', 'datacontenttype': 'application/json', 'knativearrivaltime': '2022-02-27T06:02:02.069191004Z', 'time': '2022-02-27T06:02:02.107288+00:00'}, 'data': {'msg': 'Simple Event using Knative.'}}As you can see, the pod got the msg value Simple Event using Knative. and it’s printed in the logs of the pod. This means that when you call the broker, the trigger calls the pod exposed using the service that was previously created.
Let’s say, for example, that you want to create another event, using the same image. This time, let’s call it api-demo2 for the second service. Create the next YAML definitions:
- To create the
api-demo2deployment, run the following:$ cat <<EOF | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata:labels:app: api-demo2name: api-demo2namespace: event-demospec:replicas: 1selector:matchLabels:app: api-demo2template:metadata:labels:app: api-demo2spec:containers:- image: sergioarmgpl/app3demoname: app4imagePullPolicy: AlwaysEOF - Create the service for this
api-demo2deployment:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata:labels:app: api-demo2name: api-demo2namespace: event-demospec:ports:- port: 80protocol: TCPtargetPort: 5000selector:app: api-demo2type: ClusterIPEOF - Create a trigger that launches
api-demo2, and let’s call the attribute typeevent.show.2to call theapi-demo2service, which points to theapi-demo2deployment:$ cat <<EOF | kubectl apply -f -apiVersion: eventing.knative.dev/v1kind: Triggermetadata:name: api-demo2namespace: event-demospec:broker: defaultfilter:attributes:type: event.show.2subscriber:ref:apiVersion: v1kind: Servicename: api-demo2EOF - In the previously created
curlpod, run the following command:$ curl -v "broker-ingress.knative-eventing.svc.cluster.local/event-demo/default" \-X POST \-H "Ce-Id: call-api-demo2" \-H "Ce-specversion: 1.0" \-H "Ce-Type: event.show.2" \-H "Ce-Source: test-send" \-H "Content-Type: application/json" \-d '{"msg":"Simple Event using Knative."}' - Check the logs in the new
api-demo2deployment with the following command:$ kubectl -n event-demo logs -l app=api-demo2 --tail=50 - The log will look like this:
* Serving Flask app 'index' (lazy loading)* Environment: productionWARNING: This is a development server. Do not use it in a production deployment.Use a production WSGI server instead.* Debug mode: on* Running on all addresses.WARNING: This is a development server. Do not use it in a production deployment.* Running on http://10.42.0.43:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 602-982-734[2022-02-27 06:16:07,689] WARNING in index: {'attributes': {'specversion': '1.0', 'id': 'call-api-demo2', 'source': 'test-send', 'type': 'event.show.2', 'datacontenttype': 'application/json', 'knativearrivaltime': '2022-02-27T06:16:07.654229185Z', 'time': '2022-02-27T06:16:07.688895+00:00'}, 'data': {'msg': 'Simple Event using Knative2.'}}
Now you have created two basic events using Knative Eventing. This can help you to implement simple and lightweight event-driven architectures. Now, it’s time to explore how to use the Sequence feature of Knative Eventing to create and run simple pipelines using an event-driven architecture.
Using sequences to implement event-driven pipelines
Section titled “Using sequences to implement event-driven pipelines”Another common use case for event-driven architectures is to trigger a series of steps one after the other to automate workflows. In those cases, you can use the Sequence object of Knative. In this example, we are going to create a sequence that consists of two steps. Each step prints the MESSAGE variable, which contains the number of the step that is running. This sequence is going to be called using a trigger. We are going to call the trigger using the curl command. This is a simple example pipeline using event-driven architecture. Let’s get started by following the next steps:
- Create the
sequence-demonamespace with theeventing.knative.dev/injection: enabledlabel. When Knative Eventing detects this label in your namespace, it is going to create the default Knative broker. This is possible thanks to the Knative Sugar Controller previously installed. So, let’s create the namespace by running the following command:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Namespacemetadata:name: sequence-demolabels:eventing.knative.dev/injection: enabledEOF - Create
step1using the Knative Service definition file by running the following command:$ cat <<EOF | kubectl apply -f -apiVersion: serving.knative.dev/v1kind: Servicemetadata:name: step1namespace: sequence-demospec:template:spec:containers:- image: sergioarmgpl/app4demoports:- containerPort: 5000env:- name: MESSAGEvalue: "step1"EOF - Now create
step2by running the following:$ cat <<EOF | kubectl apply -f -apiVersion: serving.knative.dev/v1kind: Servicemetadata:name: step2namespace: sequence-demospec:template:spec:containers:- image: sergioarmgpl/app4demoports:- containerPort: 5000env:- name: MESSAGEvalue: "step2"EOF
Important Note
We are using the containerPort parameter in the service definition, to define a custom port where our container is listening, in order to talk with Knative Eventing. By default, Knative uses port 80 to listen to services.
- Let’s create our sequence object called
sequence-demoto run the steps as a small pipeline using the in-memory channel for messaging:$ cat <<EOF | kubectl apply -f -apiVersion: flows.knative.dev/v1kind: Sequencemetadata:name: sequencenamespace: sequence-demospec:channelTemplate:apiVersion: messaging.knative.dev/v1kind: InMemoryChannelsteps:- ref:apiVersion: serving.knative.dev/v1kind: Servicename: step1- ref:apiVersion: serving.knative.dev/v1kind: Servicename: step2EOF - Create the trigger that we are going to use. We are going to define an attribute to call it. In this case, every time we call an event with the
typeattribute with the valueevent.call.sequence, it is going to call our sequence:$ cat <<EOF | kubectl apply -f -apiVersion: eventing.knative.dev/v1kind: Triggermetadata:name: sequence-triggernamespace: sequence-demospec:broker: defaultfilter:attributes:type: event.call.sequencesubscriber:ref:apiVersion: flows.knative.dev/v1kind: Sequencename: sequenceEOF - Now let’s create a
curlpod inside thesequence-demonamespace to call our sequence using the endpoint of our broker:$ kubectl run -n sequence-demo curl -it --rm --image=curlimages/curl:7.81.0 /bin/sh - Inside the pod, run the following
curlcommand:$ curl -v "broker-ingress.knative-eventing.svc.cluster.local/sequence-demo/default" \-X POST \-H "Ce-Id: call-sequence-demo" \-H "Ce-specversion: 1.0" \-H "Ce-Type: event.call.sequence" \-H "Ce-Source: test-sequence" \-H "Content-Type: application/json" \-d '{"SOME_VARIABLE":"Simple Sequence using Knative."}'
This is going to show an output like this:
* Trying 10.43.130.39:80...* Connected to broker-ingress.knative-eventing.svc.cluster.local (10.43.130.39) port 80 (#0)> POST /sequence-demo/default HTTP/1.1> Host: broker-ingress.knative-eventing.svc.cluster.local> User-Agent: curl/7.81.0-DEV> Accept: */*> Ce-Id: call-sequence-demo> Ce-specversion: 1.0> Ce-Type: event.call.sequense> Ce-Source: test-sequence> Content-Type: application/json>* Mark bundle as not supporting multiuse< HTTP/1.1 202 Accepted< Allow: POST, OPTIONS< Date: Mon, 28 Feb 2022 01:00:50 GMT< Content-Length: 0<* Connection #0 to host broker-ingress.knative-eventing.svc.cluster.local left intact- Exit the pod and check the output of the pod for step 1 by running the following:
$ kubectl logs deploy/step1-00001-deployment -n sequence-demo user-container
You will see an output like this:
[2022-02-28 01:06:54,364] WARNING in index: b'{"SOME_VARIABLE":"Simple Sequence using Knative."}'[2022-02-28 01:06:54,365] WARNING in index: step1This is going to receive the SOME_VARIABLE variable, sent by the curl command, which could be used to customize your sequence.
- Now check the output for step 2 by running the following:
$ kubectl logs deploy/step2-00001-deployment -n sequence-demo user-containerThe output will look like:[2022-02-28 01:07:02,623] WARNING in index: b'{\n "ENV_VAR": "step1"\n}\n'[2022-02-28 01:07:02,624] WARNING in index: step2
This is going to show the ENV_VAR value sent by the previous step and the current environment variable showing the step currently running – in this case, step 2.
- After a few minutes of being idle, the deployments for the steps in the namespace will scale down and will scale up every time you call it.
We have finished with the basics of serverless and event-driven pipelines using Knative. It’s time to finish this chapter.
Summary
Section titled “Summary”In this chapter, we learned how to implement public serverless and internal serverless functions using Knative Serving and use the features of traffic splitting. We also learned how to implement simple events and a sequence of events to implement small event-driven architectures using Knative Eventing, and how to integrate and standardize API event calls using the Cloud Events Python SDK. In the next chapter, we are going to learn how to use databases at the edge to add more functionality to edge systems using K3s.
Questions
Section titled “Questions”Here are a few questions to validate your new knowledge:
- What are the use cases for serverless architectures?
- What is a serverless function?
- What are the advantages of serverless technology?
- How can I implement a serverless function using Knative?
- How can I implement an event using Knative?
- How can I implement an event-driven pipeline using Knative?
- How does Cloud Events help you to implement events?
Further reading
Section titled “Further reading”You can refer to the following references for more information on the topics covered in this chapter:
- Why Serverless will enable the Edge Computing Revolution: https://medium.com/serverless-transformation/why-serverless-will-enable-the-edge-computing-revolution-4f52f3f8a7b0
- What is edge serverless: https://www.stackpath.com/edge-academy/what-is-edge-serverless
- AI/ML, edge and serverless computing top priority list for the year ahead: https://www.redhat.com/en/blog/aiml-edge-and-serverless-computing-top-priority-list
- Running Knative on Raspberry Pi: https://github.com/csantanapr/knative-pi
- Install Knative Serving using YAML: https://knative.dev/docs/install/serving/install-serving-with-yaml/#install-a-networking-layer
- Cloud Events website: https://cloudevents.io
- Cloud Events SDK: https://github.com/cloudevents/sdk-python
- CloudEvents – version 1.0.2: https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md
- A Hello World Python example with Knative Eventing: https://github.com/knative/docs/tree/main/code-samples/eventing/helloworld/helloworld-python
- Sending events to the broker: https://knative.dev/docs/eventing/getting-started/#sending-events-to-the-broker
- Using Sequence with Broker and Trigger: https://knative.dev/docs/eventing/flows/sequence/sequence-with-broker-trigger