Skip to content
ImagineWorld

Monitoring the Edge with Prometheus and Grafana

node_idnode-book_edge-computing-systems-with-kubernetes_chapter-11-monitoring-the-edge-with-prometheus-and-grafana
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleMonitoring the Edge with Prometheus and Grafana
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Monitoring the Edge with Prometheus and Grafana

Section titled “Chapter 11 — Monitoring the Edge with Prometheus and Grafana”

One use case for edge computing is to monitor devices that get data about temperature, humidity, speed, noise, and so on. For this kind of use cases, monitoring would be critical. This chapter shows a simple use case of how to visualize data that comes from edge devices with sensors. This chapter presents a whole example of how to distribute and process data across the different layers of an edge computing system. This use case takes Prometheus and Grafana as the main components to visualize and store data from sensors and uses Mosquitto (an MQTT message broker) together with Redis to implement high availability queues to process data at the edge.

In this chapter, we’re going to cover the following main topics:

  • Monitoring edge environments
  • Deploying Redis to persist Mosquitto sensor data
  • Installing Mosquitto to process sensor data
  • Processing Mosquitto topics
  • Installing Prometheus, a time series database
  • Deploying a custom exporter for Prometheus
  • Configuring a DHT11 sensor to send humidity and temperature weather data
  • Installing Grafana to create dashboards

To deploy our databases in this chapter, you need the following:

  • A single or multi-node K3s cluster that uses ARM devices with MetalLB and Longhorn storage installed. If you are using Raspberry Pi devices, you will need at least 4 GB of RAM and at least the 4B model. Each node has to have an Ubuntu ARM64 operating system in order to support the ARMv8 processor. This processor type is necessary for some deployments to run, because they use ARM64 container images.
  • A Kubernetes cluster hosted in your public cloud provider (AWS, Azure, or GCP) or in your private cloud.
  • A Raspberry Pi 4B with 2 or 4 GB for your edge device.
  • A Keyes DHT11 sensor or similar connected to your edge device to read temperature and humidity.
  • kubectl configured to be used in your local machine for your Kubernetes cloud cluster and your edge cluster, to avoid using the --kubeconfig parameter.
  • A clone of the https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch11 repository, if you want to run the YAML configuration by using kubectl apply instead of copying the code from the book. Take a look at the code directory for Python source code and the yaml directory for YAML configurations located inside the ch11 directory.

With this, you can deploy Prometheus and Grafana to start monitoring sensors data in edge environments.

Before starting to build our monitoring system, let’s describe the system across the different layers of edge computing. For this, let’s take a look at the following diagram:

Figure 11.1 – Monitoring with edge devices

This diagram is divided into different layers. Let’s describe the different components of this use case we want to implement:

  • Tiny edge: Here you can find an edge device, in this case, a Raspberry Pi 4B. This Raspberry Pi works as an edge device that captures temperature and humidity data using a DHT11 sensor. Data is sent by running a small Python program called send.py. This file prepares the sensor to read data and sends the information to a queue in the Mosquitto broker.
  • Far edge: Here is installed a K3s cluster using a Raspberry Pi 4B. Inside this cluster is installed Mosquitto. Mosquitto is a broker that uses the MQTT protocol and is designed to be lightweight, using few resources for processing. That’s the reason Mosquitto is often used in edge and IoT scenarios. You can also find a process service that listens to a Mosquitto queue called sensor1. Every time the process detects new data, this data is sent to a Redis queue called sensor1 in the cloud layer. The idea is that the deployment called process processes the information in the format to be shown in the cloud layer. With this, you are processing data near the edge; that is the goal of edge computing.
  • Near edge: This is the home router that connects the edge device with the K3s cluster to process data. It is also the gateway to send data to the public Redis cluster in the cloud layer.
  • Cloud layer: Here you can find a Kubernetes cluster with Prometheus, Grafana, and Redis installed. Prometheus is used as a time series database to store data from the edge sensors, and Grafana is used to visualize data. Every time data is generated in the far edge, it is sent to Redis. Redis is used to store data coming from tiny edge sensors in a temporary queue. In this way, Redis acts as backup storage if the communication fails in the far edge or if Prometheus is down. Technically speaking, service1 is in charge of reading this data from the sensor1 Redis queue and exporting it to Prometheus. Prometheus calls the service1 service endpoint to get data. So, every time that Prometheus calls the app1 endpoint, service1 returns data stored in Redis in a format that Prometheus can consume. Finally, when data is stored in Prometheus, the data is visualized in real time in a Grafana dashboard.

As you can see, this small use case includes a whole interaction across the different edge computing layers. This use case pretends to be base code extensible to your own system needs. Now, let’s start implementing our use case, beginning with deploying Redis to persist Mosquitto sensor data.

Deploying Redis to persist Mosquitto sensor data

Section titled “Deploying Redis to persist Mosquitto sensor data”

To install our Redis to persist Mosquitto weather data, we are going to use Redis with persistence and a single list of messages. To deploy this Redis setup in your cluster, follow these steps:

  1. Create the PersistentVolume to persist Redis data using the /mnt/data directory in the node:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolume
    metadata:
    name: db-pv-volume
    labels:
    type: local
    spec:
    storageClassName: manual
    capacity:
    storage: 5Gi
    accessModes:
    - ReadWriteOnce
    hostPath:
    path: "/mnt/data"
    EOF
  2. Create a PersistentVolumeClaim using 5 GB of storage or more, depending on how many sensors and how much data you are processing:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: db-pv-claim
    spec:
    storageClassName: manual
    accessModes:
    - ReadWriteOnce
    resources:
    requests:
    storage: 5Gi
    EOF

Important Note

You can use the longhorn class if Longhorn is installed in your system. For more information, see Chapter 5, K3s Homelab for Edge Computing Experiments.

  1. Now let’s create a ConfigMap to use a custom configuration with the password YOUR_PASSWORD and the /data directory to store Redis data:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: redis-configmap
    namespace: monitoring
    data:
    redis-config: |
    dir /data
    requirepass YOUR_PASSWORD
    EOF
  2. Create the Redis deployment using the previous ConfigMap called redis-configmap. This ConfigMap is mounted as a volume and its content is available using the redis.conf file. It also uses a PersistentVolumeClaim called db-pv-claim and uses resource limits for CPU and memory. Let’s create this deployment by running the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    run: redis
    name: redis
    namespace: monitoring
    spec:
    replicas: 1
    selector:
    matchLabels:
    run: redis
    template:
    metadata:
    labels:
    run: redis
    spec:
    containers:
    - name: redis
    image: redis:6.2
    command:
    - redis-server
    - /redisconf/redis.conf
    ports:
    - containerPort: 6379
    resources:
    limits:
    cpu: "0.2"
    memory: "128Mi"
    volumeMounts:
    - mountPath: "/data"
    name: redis-storage
    - mountPath: /redisconf
    name: config
    volumes:
    - name: config
    configMap:
    name: redis-configmap
    items:
    - key: redis-config
    path: redis.conf
    - name: redis-storage
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF

Important Note

You can use the arm64v8/redis:6.2 image instead of redis:6.2 if you plan to deploy Redis on an ARM node.

  1. Now create the redis service, setting port 6379 in the configuration:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    run: redis
    name: redis
    namespace: monitoring
    spec:
    ports:
    - port: 6379
    protocol: TCP
    targetPort: 6379
    selector:
    run: redis
    type: ClusterIP
    EOF

This service will be used by the exporter that Prometheus reads as service1.

  1. Now create a LoadBalancer service called redis-lb to create a public load balancer that the process service can use to store data going from the far edge to the cloud layer:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    run: redis
    name: redis-lb
    namespace: monitoring
    spec:
    ports:
    - port: 6379
    protocol: TCP
    targetPort: 6379
    selector:
    run: redis
    type: LoadBalancer
    EOF

This is going to create an external IP to access Redis.

  1. To get the public IP generated by the previous LoadBalancer service, run the following command:
    $ EXTERNAL_IP="$(kubectl get svc redis-lb -n monitoring -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"

This IP will be used by the deployment process.

Now our Redis is ready to be used in the far edge. Let’s install Mosquitto to send sensor data to the sensor1 topic from Mosquitto.

Installing Mosquitto to process sensor data

Section titled “Installing Mosquitto to process sensor data”

Mosquitto is an open source broker that implements the MQTT protocol, and it’s lightweight too. It was designed to be used with low-power sensors and devices. This makes Mosquitto suitable for edge computing and IoT applications. Mosquitto provides a lightweight channel of communication for edge devices and uses the publisher/subscriber pattern to send and read messages, but it is not persistent. We are going to use Redis later to give this missing temporary persistence for the data queues. Now, let’s move to install Mosquitto in our edge cluster, located at the far edge. Remember that this single node cluster is using an ARM device. To deploy Mosquitto, follow these steps:

  1. Create a ConfigMap to listen over all the available network interfaces:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: mosquitto-configmap
    data:
    mosquitto-config: |
    listener 1883 0.0.0.0
    allow_anonymous true
    EOF
  2. Now create a deployment for Mosquitto, setting the ports to 1883 for the MQTT protocol and 9001 for HTTP requests. This deployment is going to use the previously created mosquitto-configmap:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: mosquitto
    name: mosquitto
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: mosquitto
    template:
    metadata:
    labels:
    app: mosquitto
    spec:
    containers:
    - name: mosquitto
    image: arm64v8/eclipse-mosquitto:2.0.14
    ports:
    - containerPort: 1883
    name: mqtt
    - containerPort: 9001
    name: http
    resources:
    limits:
    cpu: "0.2"
    memory: "128Mi"
    volumeMounts:
    - mountPath: /mosquitto/config
    name: config
    volumes:
    - name: config
    configMap:
    name: mosquitto-configmap
    items:
    - key: mosquitto-config
    path: mosquitto.conf
    EOF

You can customize the amount of RAM and CPU that this deployment is using.

  1. Now create a ClusterIP service to expose Mosquitto, so that other services inside the cluster can connect to Mosquitto to read messages:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: mosquitto
    name: mosquitto
    spec:
    ports:
    - name: mqtt
    port: 1883
    protocol: TCP
    targetPort: 1883
    - name: http
    port: 9001
    protocol: TCP
    targetPort: 9001
    selector:
    app: mosquitto
    type: ClusterIP
    EOF
  2. Now create a LoadBalancer service to expose Mosquitto, so that edge devices can connect to Mosquitto to publish messages with weather metrics. In this example, our device will publish in the sensor1 topic:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: mosquitto
    name: mosquitto-lb
    spec:
    ports:
    - name: mqtt
    port: 1883
    protocol: TCP
    targetPort: 1883
    - name: http
    port: 9001
    protocol: TCP
    targetPort: 9001
    selector:
    app: mosquitto
    type: LoadBalancer
    EOF

Now, let’s deploy the process service that sends all the weather data stored in the Mosquitto topics to the Redis database located in the cloud layer.

We have to deploy the deployment called process using the mqttsubs container image, which sends the data published in Mosquitto to a public or private Redis instance in the cloud layer. Let’s explore the code inside this container image:

import paho.mqtt.client as mqtt
import os
import redis
import sys
mqhost = os.environ['MOSQUITTO_HOST']
rhost = os.environ['REDIS_HOST']
rauth = os.environ['REDIS_AUTH']
stopic = os.environ['SENSOR_TOPIC']
def on_connect(client, userdata, flags, rc):
client.subscribe(stopic)
def on_message(client, userdata, msg):
r = redis.StrictRedis(host=rhost,\
port=6379,db=0,password=rauth,\
decode_responses=True)
r.rpush(stopic,msg.payload)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqhost, 1883, 60)
client.loop_forever()

Note

You can find the source of mqttsubs at https://github.com/sergioarmgpl/containers/tree/main/mqttsubs/src.

With this code, we get the necessary values to connect to Redis, the name of the topic that we are going to use. This value will be used to push sensor data into a Redis list. Finally, MOSQUITTO_HOST is where this service will be listened to. What this script basically does is it start listening to the SENSOR_TOPIC topic called sensor1 from Mosquitto, and when a message arrives, it is inserted into a Redis list with the same name in the cloud layer to persist the information temporarily. Redis uses port 6379 and is public but uses a password. Mosquitto is internally deployed on the far edge. This is how this service works.

To start deploying our process deployment, follow these steps:

  1. Create a Secret to store the password to connect to Redis. Redis will be used as a way to store all the information coming from our Mosquitto deployment:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Secret
    metadata:
    name: db-password
    data:
    password: WU9VUl9QQVNTV09SRA==
    EOF

The value of the password corresponds to the output of the next command using base64 encoding:

$ echo "YOUR_PASSWORD" | tr -d '\n' | base64
  1. Create the process deployment that receives data coming from a Mosquitto topic and send it to the Redis service located in the cloud layer. For this run the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: process
    name: process
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: process
    template:
    metadata:
    labels:
    app: process
    spec:
    containers:
    - image: sergioarmgpl/mqttsubs
    imagePullPolicy: Always
    name: mqttsubs
    env:
    - name: MOSQUITTO_HOST
    value: "mosquitto"
    - name: REDIS_HOST
    value: "192.168.0.242"
    - name: REDIS_AUTH
    valueFrom:
    secretKeyRef:
    name: db-password
    key: password
    - name: SENSOR_TOPIC
    value: "sensor1"
    EOF

The used variables are as follows:

  • MOSQUITTO_HOST: This is the hostname where the Mosquitto deployment is listening.
  • REDIS_HOST: This is the IP address assigned to the LoadBalancer service that exposes Redis in the cloud.
  • REDIS_AUTH: This variable uses the db-password secret value to set the password to connect with Redis.
  • SENSOR_TOPIC: This variable sets the Mosquitto topic to be listened to in order to get data from the sensors.

If you are using a private cloud, you might use an IP address like 192.168.0.242, for example. You can get this IP address by reading the Deploying Redis to persist Mosquitto sensor data section. Then, change the REDIS_HOST IP address to this value.

We have finished this section and have understood how data is processed. Let’s continue deploying Prometheus service to store sensor data coming from the temporary Redis list.

Installing Prometheus, a time series database

Section titled “Installing Prometheus, a time series database”

Prometheus is a time series database that you can use to store your weather data. It’s open source and it’s suitable for edge devices. It can be deployed on ARM devices and it’s very flexible to manage metrics and alerts. In this use case, we use Prometheus because of how flexible it is and the support it provides to store and visualize metrics. But we are going to use Grafana for visualizing data later. Now let’s install Prometheus in our Kubernetes cloud cluster, following these steps:

  1. Create the monitoring namespace, which will be used to install Prometheus and Grafana:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Namespace
    metadata:
    name: monitoring
    EOF
  2. Create a ConfigMap that contains static configurations for Prometheus. In this case, we are going to create two services that insert data into Prometheus: one stores a counter and the weather data. The first service is called service1 and the second service2. Each service uses port 5555. Let’s call this ConfigMap prometheus-server-conf. To create it, run the following command:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: prometheus-server-conf
    labels:
    name: prometheus-server-conf
    namespace: monitoring
    data:
    prometheus.yml: |-
    global:
    scrape_interval: 5s
    evaluation_interval: 5s
    external_labels:
    monitor: 'codelab-monitor'
    scrape_configs:
    - job_name: 'MonitoringJob1'
    scrape_interval: 5s
    static_configs:
    - targets: ['service1:5555']
    EOF

Targets are services that export data in the format that Prometheus can read. In this case, we are using two services. service1 exports data from sensor1; this data is collected by Redis and transformed to be consumed by Prometheus. In this use case, we are going to use only service1, but you can create as many services as you want.

  1. Now create the deployment for Prometheus, using the previous ConfigMap to configure Prometheus when its created, by running the following:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: prometheus-deployment
    namespace: monitoring
    labels:
    app: prometheus-server
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: prometheus-server
    template:
    metadata:
    labels:
    app: prometheus-server
    spec:
    containers:
    - name: prometheus
    image: prom/prometheus:v2.34.0
    args:
    - "--storage.tsdb.retention.time=12h"
    - "--config.file=/etc/prom/prometheus.yml"
    - "--storage.tsdb.path=/prometheus/"
    ports:
    - containerPort: 9090
    resources:
    requests:
    cpu: 500m
    memory: 500M
    limits:
    cpu: 1
    memory: 1Gi
    volumeMounts:
    - name: prometheus-config-volume
    mountPath: /etc/prom/
    - name: prometheus-storage-volume
    mountPath: /prometheus/
    volumes:
    - name: prometheus-config-volume
    configMap:
    defaultMode: 420
    name: prometheus-server-conf
    - name: prometheus-storage-volume
    emptyDir: {}
    EOF

This deployment listens on port 9090. This port is used to connect to Prometheus.

Important Note

You can use the same YAML to deploy Prometheus in a Kubernetes cluster deployed using a cloud provider, such as GCP, AWS, or Azure.

  1. Now create a ClusterIP service that redirects port 9090 to port 8080 for Prometheus:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: prometheus-server
    name: prometheus-service
    namespace: monitoring
    spec:
    ports:
    - port: 8080
    protocol: TCP
    targetPort: 9090
    selector:
    app: prometheus-server
    type: ClusterIP
    EOF
  2. Let’s explore Prometheus by using port-forward to access the UI. For this, run the following command:
    $ kubectl port-forward svc/prometheus-service 8080 -n monitoring --address 0.0.0.0
  3. Access http://localhost:8080; you will see the following page:

Figure 11.2 – Prometheus main page

  1. Now go to the Status | Targets menu:

Figure 11.3 – Status menu

You will see the following page:

Figure 11.4 – Prometheus with targets down

On this page, you will see that the monitoring jobs are down at the moment. Because the services are not already created. After these monitoring services are created in the cluster, the state will change to Up using green color.

Now the Prometheus deployment is ready. Let’s install our custom exporter in the cloud layer to export the temporary sensor data from our Redis list to Prometheus.

Deploying a custom exporter for Prometheus

Section titled “Deploying a custom exporter for Prometheus”

After configuring all the components, you need to deploy the exporter that Prometheus calls to get data from Redis; this service will be called service1. Remember that Redis was being used to persist temporary data that comes from the Mosquitto topic on the far edge. Before deploying this service, let’s understand the exporter container source code:

from flask import Response, Flask, request, jsonify
import prometheus_client
from prometheus_client import Gauge
import redis
import os
import sys
import json
t = Gauge('weather_metric1', 'temperature')
h = Gauge('weather_metric2', 'humidity')
rhost = os.environ['REDIS_HOST']
rauth = os.environ['REDIS_AUTH']
stopic = os.environ['SENSOR_TOPIC']
r = redis.StrictRedis(host=rhost,\
port=6379,db=0,password=rauth,\
decode_responses=True)
@app.route("/metrics")
def metrics():
data = r.lpop(stopic)
values = json.loads(str(data).replace("\'","\""))
t.set(int(values["temperature"]))
h.set(int(values["humidity"]))
res = []
res.append(prometheus_client.generate_latest(t))
res.append(prometheus_client.generate_latest(h))
print({"processed":"done"},file=sys.stderr)
return Response(res, mimetype="text/plain")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5555, debug=True)

In this code made using Python, first we set the REDIS_HOST and REDIS_AUTH variables to connect to Redis and SENSOR_TOPIC to correspond to the list name in Redis where sensor data is stored. So, every time Prometheus calls the /metrics path, it extracts and returns one element inside the Redis list set with the value of SENSOR_TOPIC and returns a response in a format that Prometheus can read. For this, the code uses the prometheus_client library and sets two metrics using the Gauge metric type, which represents simple values. In this code, we are using two metrics: the first one is called weather_metric1, which contains the temperature values, and the second is weather_metric2, which contains humidity data. Once data is stored in Prometheus, it returns the JSON response {"processed":"done"}; after that, you can access this information in Prometheus. Alternatively, you can connect Prometheus to Grafana to create a new graph to show this data in real time.

Important Note

You can find the source of the exporter at https://github.com/sergioarmgpl/containers/tree/main/exporter/src.

Now let’s deploy the exporter by following these steps:

  1. Create the exporter by creating the service1 deployment:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    labels:
    app: service1
    name: service1
    namespace: monitoring
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: service1
    template:
    metadata:
    labels:
    app: service1
    annotations:
    prometheus.io/scrape: "true"
    prometheus.io/path: /metrics
    prometheus.io/port: "5555"
    spec:
    containers:
    - image: sergioarmgpl/exporter
    name: exporter
    env:
    - name: REDIS_HOST
    value: "redis"
    - name: REDIS_AUTH
    value: "YOUR_PASSWORD"
    - name: SENSOR_TOPIC
    value: "sensor1"
    EOF

You can use secrets instead of using the plain password in your YAML.

  1. Now create the service1 service:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    labels:
    app: service1
    name: service1
    namespace: monitoring
    spec:
    ports:
    - port: 5555
    protocol: TCP
    targetPort: 5555
    selector:
    app: service1
    type: ClusterIP
    EOF

Now if you return to your Prometheus targets, service1 will appear as up and in green.

Now the exporter is running. It’s time to configure the Python script in the edge device to get data coming from the DHT11 sensor and send it to the Mosquitto topic. Let’s explore this in the next section.

Configuring a DHT11 sensor to send humidity and temperature weather data

Section titled “Configuring a DHT11 sensor to send humidity and temperature weather data”

Before you start using your edge device with a DHT11 sensor to send data, you need to follow these steps to configure it:

  1. Install at least Ubuntu 20.04 LTS on your Raspberry Pi. You can check Chapter 2, K3s Installation and Configuration, and Chapter 5, K3s Homelab for Edge Computing Experiments, for more on this.
  2. Configure your DHT11 sensor to send data to the Raspberry Pi. For this use case, we are going to use the DHT11 Keyes sensor, which comes from the Keystudio Raspberry Pi 4B Complete RFID Starter kit. This is a common sensor that you can find in other brands. This sensor gets the temperature and humidity. It often comes with three pins, which are G = Ground, V = VCC, and S = Signal. The way to connect is to connect G to a ground pin on the Raspberry and V to a 3V3 pin that powers the sensor with 3 volts. S, for signal, sends information to the Raspberry using a GPIO pin. In this case, you can use any free GPIO pin on the Raspberry; for this configuration, we are using the GPIO22 pin:

Figure 11.5 – DHT11 Keyes temperature and humidity sensor

  1. Now, install the system and Python libraries that we need to run the sensor code in your edge device by running the following commands:
    • If python3 is not installed in your Linux distribution, you can install it using the following command:
      $ sudo apt-get install python3 -y
      • Then continue installing the needed libraries:
      $ sudo apt-get install libgpiod2 git -y
      $ sudo python3 sensor.py
      $ sudo pip3 install adafruit-circuitpython-dht
      $ sudo pip3 install psutil
      $ sudo apt-get install i2c-tools
  2. Clone the repository:
    $ git clone https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes
    $ cd Edge-Computing-Systems-with-Kubernetes/ch11/code
  3. Run the following:
    $ sudo python3 send.py

Important Note

Only run the send.py code inside your edge device until all the components of the use case are deployed.

Now you are starting to send data from your edge device. But what is happening inside the send.py code? Let’s take a look:

import time
import board
import adafruit_dht
import psutil
import paho.mqtt.client as mqtt
import sys
for proc in psutil.process_iter():
if proc.name() == 'libgpiod_pulsein'
or proc.name() == 'libgpiod_pulsei':
proc.kill()
sensor = adafruit_dht.DHT11(board.D22)
mqhost="192.168.0.243"
client = mqtt.Client()
client.connect(mqhost, 1883, 60)
client.loop_start()
def main():
while True:
t = sensor.temperature
h = sensor.humidity
client.publish("sensor1",\
str({"t":int(t),"h":int(h)}))
time.sleep(2)
try:
main()
except KeyboardInterrupt:
pass
finally:
sensor.exit()

In this code, first, it’s validated if the Raspberry Pi can read data from the GPIO pins. Then, by using the Adafruit library, we set the GPIO22 pin of the Raspberry Pi to read data from the sensor. After this, we set the Mosquitto host with the IP of the LoadBalancer service where Mosquitto is listening. Finally, we start a loop to read data with the sensor variable. This data is sent to the Mosquitto sensor1 topic. The loop sends data every 2 seconds.

If you press Ctrl + C, the code stops and executes sensor.exit() to close the sensor and clean the state of the sensor. Finally, you are sending data. At this point, all the data passes across Mosquitto at the far edge and goes to Redis and Prometheus in the cloud layer. The only part that’s missing is Grafana to visualize this data. For this, let’s continue to the next section.

Grafana is a web application that you can use to visualize data from different data sources; it can also create alerts based on the data that you are visualizing. In our use case, Grafana will be used to visualize data that comes from Prometheus. Let’s remember that Prometheus is listening to service1, to get data that comes from Mosquitto at the far edge. To deploy Grafana, follow these steps:

  1. First, create a ConfigMap to configure your Grafana deployment:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: grafana-datasources
    namespace: monitoring
    data:
    prometheus.yaml: |-
    {
    "apiVersion": 1,
    "datasources": [
    {
    "access":"proxy",
    "editable": true,
    "name": "prometheus",
    "orgId": 1,
    "type": "prometheus",
    "url": "http://prometheus-service.monitoring.svc:8080",
    "version": 1
    }
    ]
    }
    EOF

This will be the default data source configured in your grafana deployment.

  1. Let’s create the grafana deployment by running the following:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: grafana
    namespace: monitoring
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: grafana
    template:
    metadata:
    name: grafana
    labels:
    app: grafana
    spec:
    containers:
    - name: grafana
    image: grafana/grafana:8.4.4
    ports:
    - name: grafana
    containerPort: 3000
    resources:
    limits:
    memory: "1Gi"
    cpu: "1000m"
    requests:
    memory: 500M
    cpu: "500m"
    volumeMounts:
    - mountPath: /var/lib/grafana
    name: grafana-storage
    - mountPath: /etc/grafana/provisioning/datasources
    name: grafana-datasources
    readOnly: false
    volumes:
    - name: grafana-storage
    emptyDir: {}
    - name: grafana-datasources
    configMap:
    defaultMode: 420
    name: grafana-datasources
    EOF
  2. Let’s create the service:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: grafana
    name: grafana
    namespace: monitoring
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: grafana
    type: ClusterIP
    EOF
  3. Let’s open the Grafana UI by running the following command:
    $ kubectl port-forward svc/grafana 3000 -n monitoring --address 0.0.0.0
  4. Let’s open the URL http://localhost:3000. When the login page appears, use the username admin and password admin, and click on the Log in button:

Figure 11.6 – Grafana login

  1. After login, you will see the main page of Grafana:

Figure 11.7 – Grafana main page

  1. Click on Configuration | Data sources:

Figure 11.8 – Grafana configuration menu

  1. Then, check whether the Prometheus data source exists:

Figure 11.9 – Grafana data sources

Because of our ConfigMap configuration, our default data source will be prometheus-service.monitoring.svc:8080.

  1. Now create a new folder or dashboard using the + icon. Let’s create a folder first:

Figure 11.10 – Grafana Create menu

  1. Now in the opened dialog fill the Folder name field with the value Dashboard Sensors to create a folder with this name, then click on the Create button:

Figure 11.11 – Grafana New dashboard folder dialog

You can use this folder to save your dashboards and alerts if you want.

  1. As in Figure 11.10, let’s follow the same steps as for folders but this time click Dashboard. You will then see the page in Figure 11.12. Click on the Add a new panel button:

Figure 11.12 – Grafana Add panel page

  1. In the next figure, you will see the settings to configure the new dashboard:

Figure 11.13 – Grafana New dashboard/Edit Panel page

Here you can configure this panel by setting the main part of the query. In this case, you have to write weather_metric1 or weather_metric2. Here, weather_metric1 gets the temperature and weather_metric2 gets the humidity.

  1. Set a time range to visualize data. Then, click on Apply time range:

Figure 11.14 – Grafana Absolute time range dialog

  1. Set the refresh time to 5 seconds in the next dialog, Query options:

Figure 11.15 – Setting real-time data values

Alternatively, you can click on the Refresh icon:

Figure 11.16 – Grafana setting refresh time

  1. Then, click on the Save button and save the panel with any name and in a folder that you, for example with the previously folder created and using the name Dashboard sensors or Temperature Sensor1:

Figure 11.17 – Saving a new dashboard

  1. You can also just apply the changes by clicking on the Apply button instead of the Save button:

Figure 11.18 – Applying changes to a new dashboard

  1. Now you will see your dashboard:

Figure 11.19 – Grafana Temperature Sensor1 dashboard

  1. You can see the dashboards you have created by clicking on the Search dashboards icon:

Figure 11.20 – Search dashboards

Now you can start visualizing the data that your edge device is generating, as shown in Figure 11.18. You can customize all the parameters to show the information according to your needs. You can also modify the code to add as many sensors as you want. We have now finished the chapter. Let’s get a quick summary of what we learned.

In this chapter, we learned how monitoring can help us to visualize data at the edge, especially how to visualize data that comes from sensors, and how to build a basic use case scenario to extend for production use cases. To build this system, we used Prometheus as our time series database, Mosquitto as our basic way to store data from sensors, and Redis as a temporary queue to prevent the loss of our data from sensors. We also practiced how to build an edge computing system, using its different layers from the far edge to the cloud layer. This shows how important time series databases can be to manage sensor data and how tools such as Grafana can help to visualize it. This scenario can also be extended to farming, ocean and sea monitoring, animal populations, and so on. In the next chapter, we are going to continue with a similar scenario but applied to GPS and reading sensor data at long distances.

Here are a few questions to validate your new knowledge:

  • How do I set up an edge device to capture sensor data?
  • How do I use Prometheus to store data from sensors?
  • How do I use Grafana to create custom graphs to visualize sensor data?
  • How do I design a persistent system to manage sensor data using Mosquitto and Redis?
  • How do I use Python to process and send sensor data?

You can refer to the following references for more information on the topics covered in this chapter: