Shell脚本检测业务数据并推送至Prometheus

使用node_exporter的启动参数 --collector.textfile.directory加载目录下的 .prom文件。

#!/bin/bash

. /etc/profile

DB_HOST=""
DB_USER=""
DB_PASS=""
DB_NAME=""
OUTPUT_FILE="/root/prometheus/monitor_db.prom"


> $OUTPUT_FILE

run_query() {
    local query="$1"
    echo $(mysql -h $DB_HOST -u$DB_USER -p"$DB_PASS" -D $DB_NAME -N -e "$query")
}

giveaway_rightexc_1D_rightsum=$(run_query "
SELECT COUNT(1) FROM (
  SELECT COUNT(*) AS num
  FROM rgt_giveaway_rights_exchange a
  LEFT JOIN rgt_rights_new b ON a.rights_id = b.rights_id
  WHERE b.group_id = 1
    AND a.create_time > SUBDATE(NOW(), INTERVAL 4 HOUR)
    AND a.status = 0
    AND a.rights_id NOT IN (33, 44)
    AND a.type NOT IN (5, 7, 9)
    AND a.tariff_id NOT IN (447, 459)
    AND a.charge_type = 0
  GROUP BY a.rights_phone, a.tariff_id, a.rights_id
  HAVING num > 1
) AS cc;")

giveaway_rightexc_1D_sum=$(run_query "
SELECT COUNT(1) 
FROM rgt_giveaway_rights_exchange a
LEFT JOIN rgt_rights_new b ON a.rights_id = b.rights_id
WHERE b.group_id = 1
  AND a.status = 0
  AND DATE_FORMAT(a.create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d');")

giveaway_rightexc_1H_sum=$(run_query "
SELECT COUNT(1) 
FROM rgt_giveaway_rights_exchange a
WHERE a.tariff_id != 5
  AND a.create_time BETWEEN SUBDATE(NOW(), INTERVAL 1 HOUR) AND NOW()
  AND a.status = 0
  AND a.rights_id NOT IN (33, 44, 89)
  AND a.charge_type = 0
  AND a.type != 9;")

# 输入文件的格式为:指标 当前数据
cat <<EOF >> $OUTPUT_FILE
giveaway_rightexc_1D_rightsum $giveaway_rightexc_1D_rightsum
giveaway_rightexc_1D_sum $giveaway_rightexc_1D_sum
giveaway_rightexc_1H_sum $giveaway_rightexc_1H_sum
EOF