
Содержимое
Установку и настройку рассмотрим на примере с тремя узлами

На всех узлах используется ОС Linux Debian 10.
Устанавливаем на «Monitoring» необходимый пакет приложений. Для чего в консоли выполняем следующие действия. Все команды выполняются от имени суперпользователя.
apt-get update
apt-get install curl apt-transport-https bridge-utils ssl-cert
добавляем ключи для репозиториев Influxdb и Grafana:
curl -sL https://repos.influxdata.com/influxdb.key | apt-key add —
curl -sL https://packages.grafana.com/gpg.key | apt-key add —
и добавляем сами репозитории:
i /etc/apt/sources.list
#Grafana
deb https://packages.grafana.com/oss/deb stable main
#influxdata.com
deb https://repos.influxdata.com/debian buster stable
Устанавливаем и стартуем
apt-get update
apt-get install telegraf influxdb grafana
systemctl enable influxdb
systemctl start influxdb
systemctl enable grafana-server.service
systemctl start grafana-server
systemctl enable telegraf
systemctl start telegraf
По умолчанию grafana «слушает» порт 3000, адрес 127.0.0.1, для доступа из вне рекомендуется использовать nginx
Устанавливаем nginx
apt-get install nginx
создаем конфигурационный файл:
vi /etc/nginx/sites-available/grafana
server {
listen IP_ADDRESS:443 ssl;
listen IP_ADDRESS:80;
server_name GRAFANA_DOMAIN;
error_log /var/log/nginx/error.log;
include snippets/snakeoil.conf;
add_header Strict-Transport-Security «max-age=31536000»;
add_header Content-Security-Policy «img-src https: data:; upgrade-insecure-requests»;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers kEECDH+AES128:kEECDH:kEDH:-3DES:kRSA+AES128:kEDH+3DES:DES-CBC3-SHA:!RC4:!aNULL:!
eNULL:!MD5:!EXPORT:!LOW:!SEED:!CAMELLIA:!IDEA:!PSK:!SRP:!SSLv2;
ssl_prefer_server_ciphers on;
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
real_ip_header CF-Connecting-IP;
location / {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_pass_request_headers on;
proxy_set_header Connection «keep-alive»;
proxy_store off;
proxy_pass http://127.0.0.1:3000;
gzip on;
gzip_proxied any;
gzip_types *;
}
}
Включаем конфигурационный файл и рестартуем nginx
ln -s /etc/nginx/sites-available/grafana /etc/nginx/sites-enabled/
service nginx restart
открываем в браузере и завершаем настройку.
Прежде всего создаем туннели между сервером мониторинга и серверами шлюзов и нод.
Добавляем интерфейсы в конфигурационный файл сервера мониторинга /etc/network/interfaces
vi /etc/network/interfaces
auto br1
iface br1 inet static
address 10.10.0.1/24
bridge_ports vxlan1 vxlan2
auto vxlan1
iface vxlan1 inet manual
pre-up /sbin/ip link add vxlan1 type vxlan id 1 remote REMOTE_IP local LOCAL_IP dstport 4789
post-down ip link del vxlan1
auto vxlan2
iface vxlan2 inet manual
pre-up /sbin/ip link add vxlan2 type vxlan id 2 remote REMOTE_IP local LOCAL_IP dstport 4789
post-down ip link del vxlan2
поднимаем интерфейсы:
ifup br1
ifup vxlan1
ifup vxlan2
На сервере шлюзов добавляем интерфейс
vi /etc/network/interfaces
auto vxlan1
iface vxlan1 inet static
address 10.10.0.2/24
pre-up /sbin/ip link add vxlan1 type vxlan id 1 remote MONITOR_IP local LOCAL_IP dstport 4789
post-down ip link del vxlan1
Поднимаем и проверяем
ifup vxlan1
ping 10.10.0.1
В случае корректной настройки мы должны увидеть ответы от хоста 10.10.0.1
На сервере нод
vi /etc/network/interfaces
auto vxlan2
iface vxlan2 inet static
address 10.10.0.3/24
pre-up /sbin/ip link add vxlan2 type vxlan id 2 remote MONITOR_IP local LOCAL_IP dstport 4789
post-down ip link del vxlan2
Поднимаем и проверяем
ifup vxlan2
ping 10.10.0.1
Вносим изменения в конфигурационный файл /etc/influxdb/influxdb.conf в секции
[http] bind-address = «10.10.0.1:8086»
и в основной части файла
# Bind address to use for the RPC service for backup and restore.
bind-address = «10.10.0.1:8088»
рестартуем
service influxdb restart
Переходим к настройке telegraf
Открываем конфигурационный файл /etc/telegraf/telegraf.conf и в секции [[outputs.influxdb]] прописываем
urls = [«http://10.10.0.1:8086»] # required
сохраняем и рестартуем
service telegraf restart
повторяем действия для установки и настройки на остальных серверах
Этих действий достаточно для мониторига основных показателей серверов (CPU, RAM, DISK).
Рассмотрим создание дашборда, графика и настройки оповещений на примере диска.
Открываем grafana и добавляем новый источник данных





Сохраняем и проверяем, после чего создаем дашборд

и панель

Далее выбираем источник данных, в нашем случае он один и выбран автоматически. Создаем запрос. В поле host-имени выбираем ту машину с которой мы получаем метрику для графиков. Также выбираем и прочие параметры — на рисунке ниже выделены поля в которые необходимо внести изменения Аналогично создаются графики для CPU, RAM.

Переходим к настройкам оповещений
Создаем канал


Указываем имя канала, тип (из выпадающего списка выбираем необходимый) и заполняем соответствующие поля.

Возвращаемся к нашему графику и создаем правила для оповещений


Создание правил мониторинга для шлюзов
Переходим на сервер с шлюзами, устанавливаем telegraf (описание выше) и создаем директорию для скриптов.
mkdir /usr/local/telegraf
Рассмотрим на примере скрипта для шлюза ethereum
создаем скрипт
vi /usr/local/telegraf/gw-eth.sh
#!/bin/bash
gwip=10.0.0.22
host=`hostname`
curl_opt=’-k -m 10 —connect-timeout 3 -s’
ip=10.7.0.2
port=8546
logi=
password=
block=`curl $curl_opt -X POST —header «Content-Type: application/json» —data ‘{«jsonrpc»:»2.0″,»method»:»eth_blockNumber»,»params»:[],»id»:83}’ $ip:
$port|jq ‘.result’|tr -d \»|perl -pe ‘s/(0x)?[0-9a-f]{5,}/hex $&/ge’`
if [ «$block» = «null» ] || [ «$block» = » ]; then
block=0
fi
json=$(curl -s $gwip:3016/status)
ar=( $(echo $json | jq ‘.allowProcessing’|sed ‘/[{}]/d’) )
dt=( $(echo $json | jq ‘.operationTicks’|sed ‘/[{}]/d’) )
curblock=$(echo $json | jq ‘.blockchain.dest.currentBlock’)
asset=$(echo $json | jq ‘.asset’)
curdate=$(echo $json | jq ‘.timestamp’| tr -d \»)
curdate=`date -d$curdate +%s`
lastBlockDate=$(echo $json | jq ‘.blockchain.dest.lastBlockDate’ | tr -d \»)
lastBlockDate=`date -d$lastBlockDate +%s`
diffblock=$((block-curblock))
i=0
n=0
len=${#ar[@]}
echo -n «gatewaystat,host=$host,asset=$asset currentBlock=$curblock,diffblock=$diffblock,nodeblock=$block,»
for (( i=0; i<$len; i=$(($i + 2)) )) do n=$(($i + 1)) a=( $(sed 's/[\":]//g' <<< "${ar[$i]}") ) b=( $(sed 's/[\":,]//g' <<< "${ar[$n]}") ) if [[ "$b" == "true" ]] then b=1 else b=0 fi echo -n "$a=$b," done i=0 n=0 len=${#dt[@]} for (( i=0; i<$len; i=$(($i + 2)) )) do n=$(($i + 1)) a=( $(sed 's/[\":]//g' <<< "${dt[$i]}") ) b=( $(sed 's/[\",]//g' <<< "${dt[$n]}" | tr -d \") ) b=`date -d$b +%s` echo -n "$a-diff=$(($curdate-$b))," done echo -n "ok=1"
где,
gwip — ip шлюза,
ip — ip ноды,
port — RPC порт ноды,
logi, password — логин, пароль (при необходимости) для авторизации на ноде,
block — запрос к ноде, для получения текущего блока
Делаем скрипт исполняемым
chmod +x /usr/local/telegraf/gw-eth.sh
и проверяем
/usr/local/telegraf/gw-eth.sh
если все внесенные данные верны то должны получить следующий результат:
gatewaystat,host=test-gw,asset=»ETH»
currentBlock=12824912,diffblock=0,nodeblock=12824912,allowSearchOutgoingWithdrawConfirmations=
1,allowSearchOutgoingWithdrawTransactions=1,allowSearchOutgoingDepositTransactions=1,allowMerge
RequiredDepositTransactionsProcessing=1,allowSearchIncomingDepositTransactions=1,allowSearchInco
mingDepositTransactions-diff=21,allowMergeRequiredDepositTransactionsProcessingdiff=10,allowSearchOutgoingDepositTransactions-diff=10,allowSearchOutgoingWithdrawTransactionsdiff=10,allowSearchOutgoingWithdrawConfirmations-diff=10,ok=1
Добавляем скрипт в конфигурационный файл telegraf
[[inputs.exec]] commands = [«/usr/local/telegraf/gw-eth.sh»] timeout = «5s»
interval = «1m»
data_format = «influx»
и рестартуем его
service telegraf restart
Возращаемся в grafana и создаем графики для мониторинга этого шлюза

Запросы для создания графиков:
SELECT difference(mean(«currentBlock»)) FROM «gatewaystat» WHERE («host» = ‘test-gbldeploy-gw’ AND»asset» = ‘»ETH»‘) AND time >= now() — 6h and time <= now() GROUP BY time(30m) fill(null);SELECT mean("currentBlock") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("nodeblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("diffblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null) SELECT difference(mean("currentBlock")) FROM "gatewaystat" WHERE ("host" = 'test-gbldeploy-gw' AND "asset" ='"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(30m) fill(null);SELECT mean("currentBlock") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("nodeblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("diffblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null) SELECT difference(mean("currentBlock")) FROM "gatewaystat" WHERE ("host" = 'test-gbldeploy-gw' AND "asset" ='"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(30m) fill(null);SELECT mean("currentBlock") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("nodeblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("diffblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null) SELECT difference(mean("currentBlock")) FROM "gatewaystat" WHERE ("host" = 'test-gbldeploy-gw' AND "asset" ='"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(30m) fill(null);SELECT mean("currentBlock") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("nodeblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("diffblock") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null)
Создаем оповещения по первому запросу (а) newblock (30m) — это количество новых блоков которые получила нода за последние 30 минут, при нулевом значении необходимо проверить работоспособность ноды. И по последнему запросу (d) — разница между количеством блоков которые получила нода и какое обработал шлюз, при большой разнице необходимо обратить внимание на работу шлюза. Запросы b и c носят информативный характер.

Создадим еще один график для мониторинга параметров шлюза

запросы:
SELECT difference(mean(«allowMergeRequiredDepositTransactionsProcessing-diff»)) FROM «gatewaystat» WHERE («host» = ‘test-gbl-deploy-gw’ AND «asset» = ‘»ETH»‘) AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchIncomingDepositTransactions-diff") FROM "gatewaystat" WHERE ("host" ='test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingDepositTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawConfirmations-diff") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null) SELECT difference(mean("allowMergeRequiredDepositTransactionsProcessing-diff")) FROM "gatewaystat" WHERE ("host" ='test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m)fill(null);SELECT mean("allowSearchIncomingDepositTransactions-diff") FROM "gatewaystat" WHERE ("host" ='test-gbldeploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECTmean("allowSearchOutgoingDepositTransactionsdiff") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw'AND"asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECTmean("allowSearchOutgoingWithdrawConfirmations-diff") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND"asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECTmean("allowSearchOutgoingWithdrawTransactionsdiff") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND"asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null)SELECTdifference(mean("allowMergeRequiredDepositTransactionsProcessing-diff")) FROM "gatewaystat" WHERE ("host" = 'testgbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECTmean("allowSearchIncomingDepositTransactions-diff") FROM "gatewaystat" WHERE ("host" ='test-gbl-deploy-gw' AND"asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECTmean("allowSearchOutgoingDepositTransactionsdiff") FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND"asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawConfirmations-diff") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null) SELECT difference(mean("allowMergeRequiredDepositTransactionsProcessing-diff")) FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchIncomingDepositTransactions-diff") FROM "gatewaystat" WHERE ("host" ='test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingDepositTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawConfirmations-diff") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null) SELECT difference(mean("allowMergeRequiredDepositTransactionsProcessing-diff")) FROM "gatewaystat" WHERE ("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchIncomingDepositTransactions-diff") FROM "gatewaystat" WHERE ("host" ='test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingDepositTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawConfirmations-diff") FROM "gatewaystat" WHERE ("host"= 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now()GROUP BY time(1m) fill(null);SELECT mean("allowSearchOutgoingWithdrawTransactionsdiff") FROM "gatewaystat" WHERE("host" = 'test-gbl-deploy-gw' AND "asset" = '"ETH"') AND time >= now() — 6h and time <= now() GROUP BY time(1m) fill(null)
И правила для алармов:

Аналогично создаются графики и оповещения для остальных шлюзов создаем скрипт для каждого шлюза, но следует учитывать следующее, что переменные gwip,ip, port, logi, password,block индивидульны для каждого скрипта.Ниже указаны параметры block для основных шлюзов
BCH
block=`curl $curl_opt -u $logi:$password —data-binary ‘{«jsonrpc»: «1.0»,
«id»:»curltest», «method»: «getblockchaininfo», «params»: [] }’ -H ‘content-type:
text/plain;’ http://$ip:$port/ |jq ‘.res
ult.blocks’`BTC
block=`curl $curl_opt -u $logi:$password —data-binary ‘{«jsonrpc»: «1.0»,
«id»:»curltest», «method»: «getblockchaininfo», «params»: [] }’ -H ‘content-type:
text/plain;’ http://$ip:$port/ |jq ‘.result.blocks’`DASH
block=`curl $curl_opt -u $logi:$password —data-binary ‘{«jsonrpc»: «1.0»,
«id»:»curltest», «method»: «getblockchaininfo», «params»: [] }’ -H ‘content-type:
text/plain;’ http://$ip:$port/ |jq ‘.result.blocks’`DOGE
block=`curl $curl_opt -u $logi:$password —data-binary ‘{«jsonrpc»: «1.0»,
«id»:»curltest», «method»: «getinfo», «params»: [] }’ -H ‘content-type: text/plain;’
http://$ip:$port/ |jq ‘.result.blocks’`LTC
block=`curl $curl_opt -u $logi:$password —data-binary ‘{«jsonrpc»: «1.0»,
«id»:»curltest», «method»: «getblockchaininfo», «params»: [] }’ -H ‘content-type:
text/plain;’ http://$ip:$port/ |jq ‘.result.blocks’`TRX
block=`curl $curl_opt https://api.trongrid.io/wallet/getnodeinfo|jq ‘.solidityBlock’
|awk -F , {‘print $1’}|awk -F : {‘print $2’}`ZCASH
block=`curl $curl_opt -u $logi:$password —data-binary ‘{«jsonrpc»: «1.0»,
«id»:»curltest», «method»: «getblockchaininfo», «params»: [] }’ -H ‘content-type:
text/plain;’ http://$ip:$port/ |jq ‘.result.blocks’
Графики статуса депозитных адресов шлюзов

В отличии от предыдущего графика скрипт этого графика расположен на сервере
мониторинга. Поэтому также как и на сервере шлюза создаем директорию для скриптов
mkdir /usr/local/telegraf
vi /usr/local/telegraf/gw-scrooge-monitor.sh
#!/bin/bash
host=’monitor’
arr=( $( curl -s https://gw-scrooge.cryptoplat.io/gateway/pay/get_coins |jq ‘.
[]|.walletType, .backingCoin, .symbol, .depositAllowed, .status’ ) )
i=0
n=0
len=${#arr[@]}
echo -n «scroogedep,host=$host,blockchain=»scrooge» »
for (( i=0; i<$len; i=$(($i + 5)) )) do n=$(($i + 1)) a=( $(sed 's/[\":]//g' <<< "${arr[$i]}") ) b=( $(sed 's/[\":,]//g' <<< "${arr[$n]}") ) n=$(($n + 1)) c=( $(sed 's/[\":,]//g' <<< "${arr[$n]}") ) n=$(($n + 1)) d=( $(sed 's/[\":,]//g' <<< "${arr[$n]}") ) n=$(($n + 1)) e=( $(sed 's/[\":,]//g' <<< "${arr[$n]}") ) if [ "$d" = "false" ] || [ "$d" = "null" ] ; then continue fi if [ "$e" = "false" ] || [ "$e" = "null" ] ; then continue fi result=`curl --connect-timeout 15 -m 15 -s -H "Content-Type: application/json" -d '{"walletType":"'$a'","inputCoinType":"'$b'","outputCoinType":"'$c'","account":"testfaucet","user_id":"1.2.1 38"}' -X POST https://gw-scrooge.cryptoplat.io/gateway/pay/get_user_address|jq '.inputAddress'` status=1 if [ "$result" = "null" ] || [ "$result" = '' ] ; then status=0 fi echo -n "$c=$status," done echo -n "ok=1"
делаем его исполняемым
chmod +x /usr/local/telegraf/gw-scrooge-monitor.sh
проверяем, вывод скрипта:
/usr/local/telegraf/gw-scrooge-monitor.sh
scroogedep,host=monitor,blockchain=scrooge
TUSDT=1,BTC=1,XMR=1,BCH=1,DASH=1,TRX=1,DOGE=1,ZCASH=1,USDT=1,LTC=1,ETH=1,ok=1
В данном случае каждый шлюз возвращает статус получения адреса депозита (1-ок, 0-
ошибка)
Строим график. Запрос —
SELECT mean(*) AS «Scrooge» FROM «scroogedep» WHERE («host» = ‘monitor’ AND
«blockchain» = ‘scrooge’) AND $timeFilter GROUP BY time(15m) fill(null)
И правила для оповещения

Создаем скрипт для проверки нод
vi /usr/local/telegraf/scrooge-last-block.sh
#!/bin/bash
node=$1
hostname=`hostname`
block=`curl -k —connect-timeout 3 -s —header «Content-Type: application/json» —header
«accept:application/json» -d ‘{«jsonrpc»: «2.0», «method»: «get_dynamic_global_properties», «params»:
[[«»]], «id»: 1}’ https://$node/ws|jq ‘.result.head_block_number’`
echo «scrooge,host=$hostname block$node=$block»
проверяем
/usr/local/telegraf/scrooge-last-block.sh node1-scrooge.cryptoplat.io
вывод
scrooge,host=monitor blocknode1-scrooge.cryptoplat.io=1242197
т.е. последний блок который нода получил — это 1242197
Добавляем скрипт в телеграф для всех трех нод
[[inputs.exec]] commands = [
«/usr/local/telegraf/scrooge-last-block.sh node1-scrooge.cryptoplat.io»
] timeout = «10s»
interval = «1m»
data_format = «influx»
[[inputs.exec]] commands = [
«/usr/local/telegraf/scrooge-last-block.sh node2-scrooge.cryptoplat.io»
] timeout = «10s»
interval = «1m»
data_format = «influx»
[[inputs.exec]] commands = [
«/usr/local/telegraf/scrooge-last-block.sh node3-scrooge.cryptoplat.io»
] timeout = «10s»
interval = «1m»
data_format = «influx»
Создаем график, добавляем запросы
SELECT difference(mean(«blocknode1-scrooge.cryptoplat.io»)) FROM «scrooge» WHERE («host» = ‘d0cpu-2gb-lon1-01’) AND time >= now() — 6h and time <= now() GROUP BY time(5m) fill(null);SELECT difference(mean("blocknode2-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BYtime(5m) fill(null);SELECT difference(mean("blocknode3-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BYtime(5m) fill(null) SELECT difference(mean("blocknode1-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'd0cpu-2gb-lon1-01') AND time >= now() — 6h and time <= now() GROUP BY time(5m) fill(null);SELECT difference(mean("blocknode2-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BYtime(5m) fill(null);SELECT difference(mean("blocknode3-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BYtime(5m) fill(null) SELECT difference(mean("blocknode1-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'd0cpu-2gb-lon1-01') AND time >= now() — 6h and time <= now() GROUP BY time(5m) fill(null);SELECT difference(mean("blocknode2-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BYtime(5m) fill(null);SELECT difference(mean("blocknode3-scrooge.cryptoplat.io")) FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BYtime(5m) fill(null)
Добавляем оповещения

Результат

на графике мы видим количество блоков полученных каждой нодой за последние 5 минут.
Создаем правило для оповещения

Для построения графика нам необходимо добавить в конфигурационный файл telegraf
/etc/telegraf/telegraf.conf
следующий блок
[[inputs.http_response]] name_override = «scrooge»
address = «https://scrooge.cryptoplat.io»
insecure_skip_verify = false
interval = «1m»
создаем график со следующим запросами
SELECT mean(«http_response_code») FROM «scrooge» WHERE («host» = ‘monitor’) AND time >= now() — 6h and time <= now() GROUP BY time(20s) fill(null);SELECT mean("result_code") FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BY time(20s) fill(null) SELECT mean("http_response_code") FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BY time(20s) fill(null);SELECT mean("result_code") FROM "scrooge" WHERE ("host" = 'monitor') AND time >= now() — 6h and time <= now() GROUP BY time(20s) fill(null)

Создаем правила

Добавляем пользователя telegraf в группу docker:
usermod -aG docker telegraf
Добавляем в файл конфигурации telegraf настройки плагина docker
vi /etc/telegraf/telegraf.conf
[[inputs.docker]] endpoint = «unix:///var/run/docker.sock»
gather_services = false
source_tag = false
container_names = [] container_name_include = [] container_name_exclude = [] timeout = «5s»
perdevice = true
total = false
docker_label_include = [] docker_label_exclude = [] рестартуем telegraf
service telegraf restart
строим график
SELECT mean(«n_containers») FROM «docker» WHERE («host» = ‘test-gbl-deploy-gw’) AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null);SELECT mean("n_containers_running") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null);SELECT mean("n_containers_stopped") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null) SELECT mean("n_containers") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null);SELECT mean("n_containers_running") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null);SELECT mean("n_containers_stopped") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null) SELECT mean("n_containers") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null);SELECT mean("n_containers_running") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null);SELECT mean("n_containers_stopped") FROM "docker" WHERE ("host" = 'test-gbl-deploy-gw') AND time >= now() — 3h and time <= now() GROUP BY time(15s) fill(null)

В данном случае рассматривается вариант с тремя серверами. В реальном использовании масштабируем систему мониторинга — добавляем новые узлы согласно вышеописанному руководству.
Компания Genesis Block – международный системный интегратор и разработчик финтех-решений, систем платежей и процессинга, систем биллинга и программных решений для ЖКХ, блокчейн-решений, веб-сайтов, порталов и мобильных приложений. Под брендом Genesis Block объединены компании, разработчики и сервисы, работающие на рынке с 2010 г. Качество наших сервисов подтверждается международной сертификацией по ISO. Входим в российскую ассоциацию программного обеспечения НП РУССОФТ. Genesis Block является постоянным главным спонсором и спикером на международных банковских и финансовых конференциях IFIN и ВБА (Вся Банковская Автоматизация). Аккредитованная IT-компания Минкомсвязи. Является членом РАКИБ (Российская Ассоциация Криптовалют и Блокчейна). С 2020 компания Genesis Block ведет собственную авторскую передачу на деловом телевидении ПРОБИЗНЕС. Являемся авторизованным официальным интегратором крупнейшей BPM / CRM системы Terrasoft.