Grafana: различия между версиями
м (Добавил метку, что это черновик) |
Admin (обсуждение | вклад) |
||
Строка 1: | Строка 1: | ||
{{Draft}} | {{Draft}} | ||
'''Grafana''' — мультиплатформенное веб-приложение с открытым кодом, отображающее данные в виде графиков, диаграмм, индикаторов, а также другими способами. Конечные пользователи могут создавать сложные панели мониторинга с помощью интерактивного конструктора запросов. Умеет отправлять оповещения (alert). Расширяется с помощью системы плагинов. | |||
Grafana подходит для отображения изменяющихся со временем параметров — например, показаний датчиков, подключенных к [[Wiren Board | контроллеру Wiren Board]]. Так как Grafana сама по себе не является базой данных, для хранения данных используются [https://en.wikipedia.org/wiki/Time_series_database time series databases], такие как InfluxDB и Prometheus. | |||
Grafana можно установить на собственный сервер, либо использовать облачный сервис [https://grafana.com/products/cloud/ Grafana Cloud]. | |||
== Как настроить отображение данных с контроллера Wiren Board в Grafana Cloud == | |||
В состав Grafana Cloud входит собственная база данных, поэтому устанавливать и настраивать базу данных не требуется. | |||
Показания с контроллера Wiren Board будут передаваться по схеме: | |||
MQTT-брокер на контроллере Wiren Board -> [https://www.influxdata.com/time-series-platform/telegraf/ клиент Telegraf] на контроллере Wiren Board -> Grafana Cloud. | |||
=== Регистрация в Grafana Cloud === | |||
# Зарегистрируйтесь по ссылке [https://grafana.com/auth/sign-up/create-user]. | |||
=== Установка и настройка Telegraf на контроллер Wiren Board === | |||
# Установите и запустите Telegraf в соответствии с [https://docs.influxdata.com/telegraf/v1.19/introduction/installation/]: | |||
#: <syntaxhighlight lang="bash"> | |||
apt update && apt install apt-transport-https | |||
wget -qO- https://repos.influxdata.com/influxdb.key | sudo apt-key add - | |||
source /etc/os-release | |||
test $VERSION_ID = "7" && echo "deb https://repos.influxdata.com/debian wheezy stable" | sudo tee /etc/apt/sources.list.d/influxdb.list | |||
test $VERSION_ID = "8" && echo "deb https://repos.influxdata.com/debian jessie stable" | sudo tee /etc/apt/sources.list.d/influxdb.list | |||
test $VERSION_ID = "9" && echo "deb https://repos.influxdata.com/debian stretch stable" | sudo tee /etc/apt/sources.list.d/influxdb.list | |||
test $VERSION_ID = "10" && echo "deb https://repos.influxdata.com/debian buster stable" | sudo tee /etc/apt/sources.list.d/influxdb.list | |||
apt update && apt install telegraf | |||
systemctl start telegraf | |||
</syntaxhighlight> | |||
# Добавьте в <code>/etc/telegraf/telegraf.conf</code> секции для получения данных из MQTT и отправки данных в Grafana Cloud. В секции отправки данных замените логин и пароль на указанные на странице [https://grafana.com/orgs/wiren] в разделе Prometheus - Send metrics. | |||
#: <syntaxhighlight lang="bash"> | |||
[[inputs.mqtt_consumer]] | |||
## Broker URLs for the MQTT server or cluster. To connect to multiple | |||
## clusters or standalone servers, use a seperate plugin instance. | |||
## example: servers = ["tcp://localhost:1883"] | |||
## servers = ["ssl://localhost:1883"] | |||
## servers = ["ws://localhost:1883"] | |||
servers = ["tcp://127.0.0.1:1883"] | |||
## Topics that will be subscribed to. | |||
topics = [ | |||
"/devices/power_status/controls/Vin", | |||
] | |||
## The message topic will be stored in a tag specified by this value. If set | |||
## to the empty string no topic tag will be created. | |||
# topic_tag = "topic" | |||
## QoS policy for messages | |||
## 0 = at most once | |||
## 1 = at least once | |||
## 2 = exactly once | |||
## | |||
## When using a QoS of 1 or 2, you should enable persistent_session to allow | |||
## resuming unacknowledged messages. | |||
# qos = 0 | |||
## Connection timeout for initial connection in seconds | |||
# connection_timeout = "30s" | |||
## Maximum messages to read from the broker that have not been written by an | |||
## output. For best throughput set based on the number of metrics within | |||
## each message and the size of the output's metric_batch_size. | |||
## | |||
## For example, if each message from the queue contains 10 metrics and the | |||
## output metric_batch_size is 1000, setting this to 100 will ensure that a | |||
## full batch is collected and the write is triggered immediately without | |||
## waiting until the next flush_interval. | |||
# max_undelivered_messages = 1000 | |||
## Persistent session disables clearing of the client session on connection. | |||
## In order for this option to work you must also set client_id to identify | |||
## the client. To receive messages that arrived while the client is offline, | |||
## also set the qos option to 1 or 2 and don't forget to also set the QoS when | |||
## publishing. | |||
# persistent_session = false | |||
## If unset, a random client ID will be generated. | |||
# client_id = "" | |||
## Username and password to connect MQTT server. | |||
# username = "telegraf" | |||
# password = "metricsmetricsmetricsmetrics" | |||
## Optional TLS Config | |||
# tls_ca = "/etc/telegraf/ca.pem" | |||
# tls_cert = "/etc/telegraf/cert.pem" | |||
# tls_key = "/etc/telegraf/key.pem" | |||
## Use TLS but skip chain & host verification | |||
# insecure_skip_verify = false | |||
## Data format to consume. | |||
## Each data format has its own unique set of configuration options, read | |||
## more about them here: | |||
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md | |||
data_format = "value" | |||
data_type = "float" | |||
</syntaxhighlight> | |||
#: <syntaxhighlight lang="bash"> | |||
[[outputs.http]] | |||
## URL is the address to send metrics to | |||
url = "https://prometheus-us-central1.grafana.net/api/prom/push" | |||
## HTTP Basic Auth credentials | |||
username = "xxx" # Replace | |||
password = "yyy" # Replace | |||
## Data format to output. | |||
data_format = "prometheusremotewrite" | |||
## Additional HTTP headers | |||
[outputs.http.headers] | |||
Content-Type = "application/x-protobuf" | |||
Content-Encoding = "snappy" | |||
X-Prometheus-Remote-Write-Version = "0.1.0" | |||
</syntaxhighlight> | |||
=== Создание панели с данными от контроллера Wiren Board в Grafana === | |||
== Как настроить отображение данных с контроллера Wiren Board в Grafana на собственном сервере == | |||
На основе https://grafana.com/docs/grafana/latest/installation/debian/ | На основе https://grafana.com/docs/grafana/latest/installation/debian/ | ||
Цель: получить удобный способ для хранения и анализа данных с контроллеров. | Цель: получить удобный способ для хранения и анализа данных с контроллеров. | ||
Средства: Выделенный сервер (если планируется сбор данных с контроллеров через интернет - то с "белым" адресом). | Средства: Выделенный сервер (если планируется сбор данных с контроллеров через интернет - то с "белым" адресом). | ||
=Подготовка к установке= | === Подготовка к установке === | ||
Используем чистый Debian, | Используем чистый Debian, | ||
Добавляем пакеты, ключи | Добавляем пакеты, ключи | ||
Строка 15: | Строка 139: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Установка= | === Установка === | ||
Ставим grafana и БД influxdb: | Ставим grafana и БД influxdb: | ||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> | ||
Строка 30: | Строка 154: | ||
Если статус "Active: active (running)" - то дальнейшая настройка -через веб интерфейс. | Если статус "Active: active (running)" - то дальнейшая настройка -через веб интерфейс. | ||
==influxdb== | ==== influxdb ==== | ||
Создаем базу данных с именем '''mqtt_data''' | Создаем базу данных с именем '''mqtt_data''' | ||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> | ||
Строка 37: | Строка 161: | ||
[[Файл:influx_create_db.png|200px|thumb|right|Создание БД]] | [[Файл:influx_create_db.png|200px|thumb|right|Создание БД]] | ||
==grafana== | ==== grafana ==== | ||
Открываем в браузере http://<serverIP>:3000/ | Открываем в браузере http://<serverIP>:3000/ | ||
[[Файл:Gragana_login_1.png|200px|thumb|right|страница входа]] | [[Файл:Gragana_login_1.png|200px|thumb|right|страница входа]] | ||
Строка 43: | Строка 167: | ||
Сразу меняем пароль. | Сразу меняем пароль. | ||
=запуск и контроль= | === запуск и контроль === | ||
Версия 22:53, 27 июля 2021
Это черновик страницы. Последняя правка сделана 27.07.2021 пользователем Admin. Grafana — мультиплатформенное веб-приложение с открытым кодом, отображающее данные в виде графиков, диаграмм, индикаторов, а также другими способами. Конечные пользователи могут создавать сложные панели мониторинга с помощью интерактивного конструктора запросов. Умеет отправлять оповещения (alert). Расширяется с помощью системы плагинов.
Grafana подходит для отображения изменяющихся со временем параметров — например, показаний датчиков, подключенных к контроллеру Wiren Board. Так как Grafana сама по себе не является базой данных, для хранения данных используются time series databases, такие как InfluxDB и Prometheus.
Grafana можно установить на собственный сервер, либо использовать облачный сервис Grafana Cloud.
Как настроить отображение данных с контроллера Wiren Board в Grafana Cloud
В состав Grafana Cloud входит собственная база данных, поэтому устанавливать и настраивать базу данных не требуется.
Показания с контроллера Wiren Board будут передаваться по схеме:
MQTT-брокер на контроллере Wiren Board -> клиент Telegraf на контроллере Wiren Board -> Grafana Cloud.
Регистрация в Grafana Cloud
- Зарегистрируйтесь по ссылке [1].
Установка и настройка Telegraf на контроллер Wiren Board
- Установите и запустите Telegraf в соответствии с [2]:
apt update && apt install apt-transport-https wget -qO- https://repos.influxdata.com/influxdb.key | sudo apt-key add - source /etc/os-release test $VERSION_ID = "7" && echo "deb https://repos.influxdata.com/debian wheezy stable" | sudo tee /etc/apt/sources.list.d/influxdb.list test $VERSION_ID = "8" && echo "deb https://repos.influxdata.com/debian jessie stable" | sudo tee /etc/apt/sources.list.d/influxdb.list test $VERSION_ID = "9" && echo "deb https://repos.influxdata.com/debian stretch stable" | sudo tee /etc/apt/sources.list.d/influxdb.list test $VERSION_ID = "10" && echo "deb https://repos.influxdata.com/debian buster stable" | sudo tee /etc/apt/sources.list.d/influxdb.list apt update && apt install telegraf systemctl start telegraf
- Добавьте в
/etc/telegraf/telegraf.conf
секции для получения данных из MQTT и отправки данных в Grafana Cloud. В секции отправки данных замените логин и пароль на указанные на странице [3] в разделе Prometheus - Send metrics.[[inputs.mqtt_consumer]] ## Broker URLs for the MQTT server or cluster. To connect to multiple ## clusters or standalone servers, use a seperate plugin instance. ## example: servers = ["tcp://localhost:1883"] ## servers = ["ssl://localhost:1883"] ## servers = ["ws://localhost:1883"] servers = ["tcp://127.0.0.1:1883"] ## Topics that will be subscribed to. topics = [ "/devices/power_status/controls/Vin", ] ## The message topic will be stored in a tag specified by this value. If set ## to the empty string no topic tag will be created. # topic_tag = "topic" ## QoS policy for messages ## 0 = at most once ## 1 = at least once ## 2 = exactly once ## ## When using a QoS of 1 or 2, you should enable persistent_session to allow ## resuming unacknowledged messages. # qos = 0 ## Connection timeout for initial connection in seconds # connection_timeout = "30s" ## Maximum messages to read from the broker that have not been written by an ## output. For best throughput set based on the number of metrics within ## each message and the size of the output's metric_batch_size. ## ## For example, if each message from the queue contains 10 metrics and the ## output metric_batch_size is 1000, setting this to 100 will ensure that a ## full batch is collected and the write is triggered immediately without ## waiting until the next flush_interval. # max_undelivered_messages = 1000 ## Persistent session disables clearing of the client session on connection. ## In order for this option to work you must also set client_id to identify ## the client. To receive messages that arrived while the client is offline, ## also set the qos option to 1 or 2 and don't forget to also set the QoS when ## publishing. # persistent_session = false ## If unset, a random client ID will be generated. # client_id = "" ## Username and password to connect MQTT server. # username = "telegraf" # password = "metricsmetricsmetricsmetrics" ## Optional TLS Config # tls_ca = "/etc/telegraf/ca.pem" # tls_cert = "/etc/telegraf/cert.pem" # tls_key = "/etc/telegraf/key.pem" ## Use TLS but skip chain & host verification # insecure_skip_verify = false ## Data format to consume. ## Each data format has its own unique set of configuration options, read ## more about them here: ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md data_format = "value" data_type = "float"
[[outputs.http]] ## URL is the address to send metrics to url = "https://prometheus-us-central1.grafana.net/api/prom/push" ## HTTP Basic Auth credentials username = "xxx" # Replace password = "yyy" # Replace ## Data format to output. data_format = "prometheusremotewrite" ## Additional HTTP headers [outputs.http.headers] Content-Type = "application/x-protobuf" Content-Encoding = "snappy" X-Prometheus-Remote-Write-Version = "0.1.0"
Создание панели с данными от контроллера Wiren Board в Grafana
Как настроить отображение данных с контроллера Wiren Board в Grafana на собственном сервере
На основе https://grafana.com/docs/grafana/latest/installation/debian/ Цель: получить удобный способ для хранения и анализа данных с контроллеров. Средства: Выделенный сервер (если планируется сбор данных с контроллеров через интернет - то с "белым" адресом).
Подготовка к установке
Используем чистый Debian, Добавляем пакеты, ключи
apt install -y apt-transport-https software-properties-common wget gnupg2 sudo python3-pip
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
apt update
Установка
Ставим grafana и БД influxdb:
apt install -y grafana influxdb influxdb-client
Разрешаем автозапуск, запускаем и проверяем:
apt install -y grafana
systemctl enable grafana-server && systemctl start grafana-server
systemctl status grafana-server
Если статус "Active: active (running)" - то дальнейшая настройка -через веб интерфейс.
influxdb
Создаем базу данных с именем mqtt_data
echo "CREATE DATABASE mqtt_data; show databases;" | influx
grafana
Открываем в браузере http://<serverIP>:3000/
Логин и пароль по умолчанию admin admin. Сразу меняем пароль.