### Install chart with CLI flags Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Install the chart using helm install with configuration set via --set flags. ```bash helm install my-mqtt2prometheus ./helm \ --set config.mqtt.server=tcp://your-mqtt-broker:1883 \ --set config.mqtt.topic_path=your/topic/+ ``` -------------------------------- ### Configuration file example Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md An example YAML configuration file defining MQTT broker settings, cache behavior, and exported metrics. ```yaml mqtt: # The MQTT broker to connect to server: tcp://127.0.0.1:1883 # Optional: Username and Password for authenticating with the MQTT Server user: bob password: happylittleclouds # Optional: for TLS client certificates ca_cert: certs/AmazonRootCA1.pem client_cert: certs/xxxxx-certificate.pem.crt client_key: certs/xxxxx-private.pem.key # Optional: Used to specify ClientID. The default is - client_id: somedevice # The Topic path to subscribe to. Be aware that you have to specify the wildcard, if you want to follow topics for multiple sensors. topic_path: v1/devices/me/+ # Optional: Regular expression to extract the device ID from the topic path. The default regular expression, assumes # that the last "element" of the topic_path is the device id. # The regular expression must contain a named capture group with the name deviceid # For example the expression for tasamota based sensors is "tele/(?P.*)/.*" device_id_regex: "(.*/)?(?P.*)" # The MQTT QoS level qos: 0 # NOTE: Only one of metric_per_topic_config or object_per_topic_config should be specified in the configuration # Optional: Configures mqtt2prometheus to expect a single metric to be published as the value on an mqtt topic. metric_per_topic_config: # A regex used for extracting the metric name from the topic. Must contain a named group for `metricname`. metric_name_regex: "(.*/)?(?P.*)" # Optional: Configures mqtt2prometheus to expect an object containing multiple metrics to be published as the value on an mqtt topic. # This is the default. object_per_topic_config: # The encoding of the object, currently only json is supported encoding: JSON cache: # Timeout. Each received metric will be presented for this time if no update is send via MQTT. # Set the timeout to -1 to disable the deletion of metrics from the cache. The exporter presents the ingest timestamp # to prometheus. timeout: 24h # Path to the directory to keep the state for monotonic metrics. state_directory: "/var/lib/mqtt2prometheus" json_parsing: # Separator. Used to split path to elements when accessing json fields. # You can access json fields with dots in it. F.E. {"key.name": {"nested": "value"}} # Just set separator to -> and use key.name->nested as mqtt_name separator: . # This is a list of valid metrics. Only metrics listed here will be exported metrics: # The name of the metric in prometheus - prom_name: temperature # The name of the metric in a MQTT JSON message mqtt_name: temperature # The prometheus help text for this metric help: DHT22 temperature reading # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: gauge # A map of string to string for constant labels. This labels will be attached to every prometheus metric ``` -------------------------------- ### Install chart with custom values file Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Install the chart using a custom values.yaml file. ```bash helm install my-mqtt2prometheus ./helm -f my-values.yaml ``` -------------------------------- ### Start Shelly scenario with docker-compose Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/hack/Readme.md Starts the Shelly scenario using the shelly.env environment file. Requires a MQTT client like mqttcli. ```bash docker-compose --env-file shelly.env up ``` -------------------------------- ### Install with ServiceMonitor enabled Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Install the chart with ServiceMonitor enabled via CLI flags. ```bash helm install my-mqtt2prometheus ./helm \ --set serviceMonitor.enabled=true \ --set serviceMonitor.labels.prometheus=kube-prometheus ``` -------------------------------- ### Start DHT22 scenario with docker-compose Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/hack/Readme.md Starts the DHT22 scenario using the dht22.env environment file. This is the default scenario. ```bash docker-compose --env-file dht22.env up ``` -------------------------------- ### Run public Docker image Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Starts the latest public Docker image, mounting the local configuration file. ```bash docker run -it -v "$(pwd)/config.yaml:/config.yaml" -p 9641:9641 ghcr.io/hikhvar/mqtt2prometheus:latest ``` -------------------------------- ### Example values.yaml configuration Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md The mqtt2prometheus configuration is defined in the values.yaml file under the config section and mounted at /config.yaml. ```yaml config: mqtt: server: tcp://mqtt-broker:1883 user: myuser password: mypassword topic_path: sensors/+/data qos: 0 cache: timeout: 24h json_parsing: separator: . metrics: - prom_name: temperature mqtt_name: temperature help: Temperature reading type: gauge const_labels: sensor_type: dht22 ``` -------------------------------- ### Example MQTT JSON message Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Example MQTT message published by a sensor to the topic 'devices/home/livingroom'. The exporter extracts metrics from the JSON fields using the configured mqtt_name paths. ```json {"temperature":23.20,"humidity":51.60, "computed": {"heat_index":22.92} } ``` -------------------------------- ### Raw expression example Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md An example of a raw expression used for date parsing. ```text raw_expression: 'date(string(raw_value), "H060102150405", "Europe/Paris").Unix()' ``` -------------------------------- ### mqtt2prometheus Configuration File Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Example configuration defining various metrics like humidity, heat index, light state, and energy usage with their respective MQTT mappings and Prometheus settings. ```yaml const_labels: sensor_type: dht22 # A map of string to expression for dynamic labels. This labels will be attached to every prometheus metric # expression will be executed for each label every time a metric is processed # dynamic_labels: # raw_value: "raw_value" # The name of the metric in prometheus - prom_name: humidity # The name of the metric in a MQTT JSON message mqtt_name: humidity # The scale of the metric in a MQTT JSON message (prom_value = mqtt_value * scale) mqtt_value_scale: 100 # The prometheus help text for this metric help: DHT22 humidity reading # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: gauge # A map of string to string for constant labels. This labels will be attached to every prometheus metric const_labels: sensor_type: dht22 # The name of the metric in prometheus - prom_name: heat_index # The path of the metric in a MQTT JSON message mqtt_name: computed.heat_index # The prometheus help text for this metric help: DHT22 heatIndex calculation # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: gauge # A map of string to string for constant labels. This labels will be attached to every prometheus metric const_labels: sensor_type: dht22 # The name of the metric in prometheus - prom_name: state # The name of the metric in a MQTT JSON message mqtt_name: state # Regular expression to only match sensors with the given name pattern sensor_name_filter: "^.*-light$" # The prometheus help text for this metric help: Light state # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: gauge # according to prometheus exposition format timestamp is not mandatory, we can omit it if the reporting from the sensor is sporadic omit_timestamp: true # A map of string to string for constant labels. This labels will be attached to every prometheus metric const_labels: sensor_type: ikea # When specified, metric value to use if a value cannot be parsed (match cannot be found in the map above, invalid float parsing, expression fails, ...) # If not specified, parsing error will occur. error_value: 1 # When specified, enables mapping between string values to metric values. string_value_mapping: # A map of string to metric value. map: off: 0 low: 0 # The name of the metric in prometheus - prom_name: total_light_usage_seconds # The name of the metric in a MQTT JSON message mqtt_name: state # Regular expression to only match sensors with the given name pattern sensor_name_filter: "^.*-light$" # The prometheus help text for this metric help: Total time the light was on, in seconds # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: counter # according to prometheus exposition format timestamp is not mandatory, we can omit it if the reporting from the sensor is sporadic omit_timestamp: true # A map of string to string for constant labels. This labels will be attached to every prometheus metric const_labels: sensor_type: ikea # Metric value to use if a value cannot be parsed (match cannot be found in the map above, invalid float parsing, ...) # If not specified, parsing error will occur. error_value: 1 # When specified, enables mapping between string values to metric values. string_value_mapping: # A map of string to metric value. map: off: 0 low: 0 # Sum up the time the light is on, see the section "Expressions" below. expression: "value > 0 ? last_result + elapsed.Seconds() : last_result" # The name of the metric in prometheus - prom_name: total_energy # The name of the metric in a MQTT JSON message mqtt_name: aenergy.total # Regular expression to only match sensors with the given name pattern sensor_name_filter: "^shellyplus1pm-.*$" # The prometheus help text for this metric help: Total energy used # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: counter # This setting requires an almost monotonic counter as the source. When monotonicy is enforced, the metric value is regularly written to disk. Thus, resets in the source counter can be detected and corrected by adding an offset as if the reset did not happen. The result is a true monotonic increasing time series, like an ever growing counter. force_monotonicy: true - prom_name: linky_time # The name of the metric in a MQTT JSON message mqtt_name: linky_current_date # Regular expression to only match sensors with the given name pattern sensor_name_filter: "^linky.*$" # The prometheus help text for this metric help: current unix timestamp from linky # The prometheus type for this metric. Valid values are: "gauge" and "counter" type: gauge # convert dynamic datetime string to unix timestamp ``` -------------------------------- ### Example MQTT sensor message Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md A sample JSON payload sent by a sensor to the topic devices/workshop/storage. ```json {"temperature":3.0,"humidity":34.60, "computed": {"heat_index":15.92} } ``` -------------------------------- ### Configure expression for value integration Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Example of using expression to integrate positive values over time after raw value conversion. ```yaml expression: "value > 0 ? last_result + value * elapsed.Seconds() : last_result" ``` -------------------------------- ### Configure tmpfs for Docker persistence Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Example of adding a tmpfs mount to docker-compose.yml to allow mqtt2prometheus to persist expression state. ```yaml tmpfs: - /var/lib/mqtt2prometheus:uid=65532,gid=65532,mode=0700 ``` -------------------------------- ### Get application URL via HTTPRoute Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Commands to retrieve the application hostname and URL when HTTPRoute is enabled. If hostnames are set, it exports the first hostname; otherwise, it fetches the gateway listener hostname. The URL is printed if a path rule is defined. ```bash export APP_HOSTNAME={{ .Values.httpRoute.hostnames | first }} ``` ```bash export APP_HOSTNAME=$(kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o jsonpath="{.spec.listeners[0].hostname}") ``` ```bash echo "Visit http://$APP_HOSTNAME{{ (first (first .Values.httpRoute.rules).matches).path.value }} to use your application" ``` -------------------------------- ### Get application URL via Ingress Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Prints the HTTP or HTTPS URL for each ingress host and path when ingress is enabled. ```bash http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }} ``` -------------------------------- ### Get application URL via LoadBalancer service Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Commands to retrieve the LoadBalancer service IP and print the application URL. Includes a note that it may take a few minutes for the IP to be available. ```bash export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "helm.fullname" . }} --template "{{ "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}" }}") echo http://$SERVICE_IP:{{ .Values.service.port }} ``` -------------------------------- ### Get application URL via NodePort service Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Commands to retrieve the node port and node IP, then print the application URL when the service type is NodePort. ```bash export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "helm.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT ``` -------------------------------- ### Prometheus metrics output Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Prometheus metrics generated from the example MQTT message. The 'sensor' label is extracted from the topic using the default device_id_regex. ```text temperature{sensor="livingroom",topic="devices/home/livingroom"} 23.2 heat_index{sensor="livingroom",topic="devices/home/livingroom"} 22.92 humidity{sensor="livingroom",topic="devices/home/livingroom"} 51.6 ``` -------------------------------- ### Shelly Plus H&T topic message Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Example of a Shelly Plus H&T device publishing one metric per topic in JSON format. PayloadField can be used to extract the desired value. ```text shellies/shellyplusht-xxx/status/humidity:0 {"id": 0,"rh":51.9} ``` -------------------------------- ### Build the exporter Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Run this command to build the mqtt2prometheus exporter from source. ```bash make build ``` -------------------------------- ### Run MQTT2Prometheus with Docker Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Load the secrets file and run the container with the necessary environment variables and volume mounts. ```SHELL source ~/secrets/mqtt2prom && \ docker run -it \ -e MQTT2PROM_MQTT_USER \ -e MQTT2PROM_MQTT_PASSWORD \ -v "$(pwd)/examples/config.yaml:/config.yaml" \ -p 9641:9641 \ ghcr.io/hikhvar/mqtt2prometheus:latest ``` -------------------------------- ### Create secrets file for Docker Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Create a shell script to export MQTT credentials as environment variables. ```SHELL #!/bin/bash export MQTT2PROM_MQTT_USER="myUser" export MQTT2PROM_MQTT_PASSWORD="superpassword" ``` -------------------------------- ### Command line flags Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Displays the available command line arguments and their default values. ```text Usage of ./mqtt2prometheus: -config string config file (default "config.yaml") -listen-address string listen address for HTTP server used to expose metrics (default "0.0.0.0") -listen-port string HTTP port used to expose metrics (default "9641") -log-format string set the desired log output format. Valid values are 'console' and 'json' (default "console") -log-level value sets the default loglevel (default: "info") -version show the builds version, date and commit -web-config-file string [EXPERIMENTAL] Path to configuration file that can enable TLS or authentication for metric scraping. -treat-mqtt-password-as-file-name bool (default: false) treat MQTT2PROM_MQTT_PASSWORD environment variable as a secret file path e.g. /var/run/secrets/mqtt-credential. Useful when docker secret or external credential management agents handle the secret file. ``` -------------------------------- ### Build Docker image locally Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Builds a local Docker container image for the exporter. ```bash make container ``` -------------------------------- ### Run local Docker container Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Executes the locally built Docker container with a specified configuration file. ```bash docker run -it -v "$(pwd)/config.yaml:/config.yaml" -p 9641:9641 mqtt2prometheus:latest ``` -------------------------------- ### Upgrade existing release Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Upgrade an existing mqtt2prometheus release using helm upgrade. ```bash helm upgrade my-mqtt2prometheus ./helm -f my-values.yaml ``` -------------------------------- ### Publish Shelly temperature message with mqttcli Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/hack/Readme.md Publishes a temperature value to the topic 'shellies/living-room/sensor/temperature' on localhost port 1883. ```bash mqttcli pub --host localhost -p 1883 -t shellies/living-room/sensor/temperature '15' ``` -------------------------------- ### Publish DHT22 sensor data with mqttcli Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/hack/Readme.md Publishes a JSON object with temperature and humidity to the topic 'v1/devices/me/test' on localhost port 1883. ```bash mqttcli pub --host localhost -p 1883 -t v1/devices/me/test -m '{"temperature":"12", "humidity":21}' ``` -------------------------------- ### Configure additional volumes Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Define additional volumes and volumeMounts in values.yaml to mount resources like TLS certificates. ```yaml volumes: - name: certs secret: secretName: mqtt-certs volumeMounts: - name: certs mountPath: /certs readOnly: true ``` -------------------------------- ### Check gateway configuration Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Command to inspect the gateway configuration when using HTTPRoute. Useful for debugging listener and rule settings. ```bash kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o yaml ``` -------------------------------- ### Reference mounted volumes in config Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Reference the mounted volume paths within the mqtt configuration section. ```yaml config: mqtt: server: tcp://mqtt-broker:8883 ca_cert: /certs/ca.pem client_cert: /certs/client.pem client_key: /certs/client-key.pem ``` -------------------------------- ### Access application via ClusterIP port-forward Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Commands to set up port forwarding to access the application when the service type is ClusterIP. Retrieves the pod name and container port, then forwards local port 8080. ```bash export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "helm.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") echo "Visit http://127.0.0.1:8080 to use your application" kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT ``` -------------------------------- ### Enable ServiceMonitor Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Enable the ServiceMonitor resource in values.yaml to support Prometheus Operator. ```yaml serviceMonitor: enabled: true ``` -------------------------------- ### Deploy with Docker Swarm secrets Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md Configure a service in Docker Swarm to use a secret file for the MQTT password by setting the treat-mqtt-password-as-file-name flag. ```docker mqtt_exporter_tasmota: image: ghcr.io/hikhvar/mqtt2prometheus:latest secrets: - mqtt-credential environment: - MQTT2PROM_MQTT_USER=mqtt - MQTT2PROM_MQTT_PASSWORD=/var/run/secrets/mqtt-credential entrypoint: - /mqtt2prometheus - -log-level=debug - -treat-mqtt-password-as-file-name=true volumes: - config-tasmota.yml:/config.yaml:ro ``` -------------------------------- ### Customize ServiceMonitor Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/README.md Customize ServiceMonitor settings such as labels, intervals, and paths. ```yaml serviceMonitor: enabled: true # Add custom labels (useful for Prometheus selectors) labels: prometheus: kube-prometheus # Scrape interval interval: 30s # Scrape timeout scrapeTimeout: 10s # Metrics path path: /metrics ``` -------------------------------- ### Default Prometheus metrics output Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md The resulting Prometheus metrics generated from the sample sensor message using default configuration. ```text temperature{sensor="storage",topic="devices/workshop/storage"} 3.0 heat_index{sensor="storage",topic="devices/workshop/storage"} 15.92 humidity{sensor="storage",topic="devices/workshop/storage"} 34.60 ``` -------------------------------- ### Prometheus metrics with location label Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md The metrics output after applying the relabel_config to include the location label. ```text temperature{sensor="storage", location="workshop", topic="devices/workshop/storage"} 3.0 heat_index{sensor="storage", location="workshop", topic="devices/workshop/storage"} 15.92 humidity{sensor="storage", location="workshop", topic="devices/workshop/storage"} 34.60 ``` -------------------------------- ### Watch LoadBalancer status Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/helm/templates/NOTES.txt Command to watch the LoadBalancer service status until the IP is available. ```bash kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "helm.fullname" . }} ``` -------------------------------- ### JSON message with dot in key Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md JSON message with a dot in the key 'heat.index'. Setting json_parsing.seperator to '/' allows mqtt_name 'computed/heat.index' to address the value. ```json { "computed": { "heat.index":22.92 } } ``` -------------------------------- ### Prometheus relabel_config for location extraction Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md A relabel_config block to extract the location from the topic path and attach it as a label. ```yaml relabel_config: - source_labels: [ "topic" ] target_label: location regex: '/devices/(.*)/.*' action: replace replacement: "$1" ``` -------------------------------- ### JSON message with nested object Source: https://github.com/hikhvar/mqtt2prometheus/blob/master/Readme.md JSON message with a nested 'computed' object. The mqtt_name path 'computed.heat_index' addresses the value 22.92. ```json { "computed": { "heat_index":22.92 } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.