组件架构图
数据格式
时序
时序 由 名字(Metric) 及一组key/value标签定义,具有相同的名字以及标签属于相同时序。
<-------------------metric-------------------><--timestamp--><-value->
<metric name>{<label name>=<label value>, ...}><--timestamp--><-value->
http_request_total{status="200",method="get"}@1434417560938 =>94355
http_request_total{status="200",method="get"}@1434417560938 =>94390
http_request_total{status="404",method="get"}@1434417560938 =>38472
http_request_total{status="404",method="get"}@1434417560938 =>38544
http_request_total{status="404",method="post"}@1434417560938 =>4785
指标举例
#指标意义注释
#HELP node_cpu_seconds_total Seconds the cpus spent in each mode.
#指标值类型,counter类型表示只增不减
#TYPE node_cpu_seconds_total counter
#指标名表示节点的CPU0的空闲时间共计1.40181324e+06秒。数值从系统开机时算起,重启归零。
node_cpu_seconds_total{cpu="0",mode="idle"} 1.40181324e+06
Prometheus词义解析
- metric:时序名,命名应该具有语义化,表示metric的功能,一般表示一个可以度量的指标,如 http_requests_total, 表示 http 请求总数。(应用名称监测对象数值类型单位),由 ASCII 字符,数字,下划线,冒号组成,必须满足正则表达式 [a-zA-Z:][a-zA-Z0-9_:]*
Metric类型
- 计数器:Counter,累加metric,如请求个数,结束任务数,出现错误数等,只增不减;
- 仪表盘:Gauge,常规metric,如温度,瞬时,与时间没关系,可以任意变化,可任意加减;
- 直方图:Histogram,用于观察结果采样,分组及统计,如:请求持续时间。根据统计区间计算;
- 摘要:Summary,表示一段时间内数据采样结果,不根据统计区间计算,直接存储结果;
- lable:标签:key-value对,一条时间序列不同维度的识别 ,标签可以扩展,提供监控项的识别,方便聚合
- value:样本:按照某个时序以时间维度采集的数据。实际的时间序列,每个序列包括一个float64的值和一个毫秒级的unix 时间戳
部署
Prometheus下载
测试版本:prometheus-2.21.0.linux-amd64.tar.gz
配置prometheus.yml
# global config
global:
scrape_interval: 15s # 监控项数据收集时间间隔,15秒向目标抓取一次数据.默认1min
evaluation_interval: 15s # 规则发现时间间隔. 默认1min
scrape_timeout: 10s # 收集数据超时时间. 默认10s
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
- localhost:9093 #指定 Alertmanager 组件的IP和端口
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "./rules/rule_*.yml"
remote_write:
- url: "http://localhost:8086/api/v1/prom/write?db=prometheus"
# write_relabel_configs:
# - source_labels: [__name__]
# regex: expensive.*
# action: drop
# - url: http://remote2/push
remote_read:
- url: "http://localhost:8086/api/v1/prom/write?db=prometheus"
# read_recent: false/true
# required_matchers:
# job: special
# - url: http://remote3/push
# Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
scrape_interval: 30s #重写全局抓取间隔时间,由15秒重写成30秒
static_configs:
- targets: ['localhost:9090']
#instance: 收集数据的目标端点,一般对应一个进程,即指定其来源,如某个机器
#job: 实现同一功能或目标的一组instance。 如一组机器的集合。
- job_name: 'base'
file_sd_configs:
- files:
- /usr/local/prometheus/node_discovery.json
refresh_interval: 60s
- job_name: 'mysql'
file_sd_configs:
- files:
- /usr/local/prometheus/mysql_discovery.json
refresh_interval: 60s
- job_name: 'openstack'
static_configs:
- targets: ['127.0.0.1:9091']
labels:
instance: gateway
tar -xvzf prometheus-2.21.0.linux-amd64.tar.gz
mv prometheus-2.21.0.linux-amd64 /usr/local/prometheus
检查配置正确性
./promtool check config prometheus.yml
Checking prometheus.yml
SUCCESS: 2 rule files found
Checking rules/rule_mysql.yml
SUCCESS: 5 rules found
Checking rules/rule_node.yml
SUCCESS: 0 rules found
./promtool check rules rules/rule_mysql.yml
Checking rules/rule_mysql.yml
SUCCESS: 5 rules found
启动prometheus
./prometheus --config.file=prometheus.yml &
启动参数:
--config.file=prometheus.yml #指定配置文件
--storage.tsdb.path=/prometheus #指定tsdb路径
--storage.tsdb.retention.time=24h #指定数据存储时间
--web.enable-lifecycle #配置热加载
--storage.tsdb.no-lockfile #如果使用k8s的deployment管理要开启
node_exporter
被监控节点安装node_exporter,获取当前CPU负载、系统负载、内存消耗、硬盘使用量、网络IO等监控项。
#安装
tar -zxvf node_exporter-1.0.1.linux-amd64.tar.gz -C /usr/local/
cd /usr/local; mv node_exporter-1.0.1.linux-amd64 node_exporter-1.0.1
#启动
/usr/local/node_exporter &
#监听
ss -naltp | grep 9100
LISTEN 0 4096 :::9100 :::* users:(("node_exporter",pid=171161,fd=3))
mysqld_exporter
数据库服务节点安装mysqld_exporter,获取mysql所有status、variables信息。
#安装
tar -zxvf mysqld_exporter-0.12.1.linux-amd64.tar.gz -C /usr/local/
mv mysqld_exporter-0.12.1.linux-amd64 mysqld_exporter
#目标服务器授权
GRANT SELECT, PROCESS, REPLICATION CLIENT ON *.* TO 'prometheus'@'IP' IDENTIFIED BY '';
#数据库相关配置
vim .my.cnf
[client]
user=prometheus
password=######## #经过测试,尽量不使用特殊字符
port=####
host=localhost
#启动mysqld_exporter
/root/mysqld_exporter/mysqld_exporter --config.my-cnf=/root/.my.cnf
#查看监听
ss -naltp | grep 9104
LISTEN 0 4096 :::9104 :::* users:(("mysqld_exporter",pid=3010579,fd=3))
Pushgateway
使用场景:
- 自定义监控指标
- 网络限制
tar -zxf pushgateway-1.2.0.linux-amd64.tar.gz -C /usr/local/
cd /usr/local/;mv pushgateway-1.2.0.linux-amd64 pushgateway-1.2.0;cd pushgateway-1.2.0/
#启动pushgateway
./pushgateway --web.enable-admin-api --persistence.file="push_file" &
#配置文件添加job
vim /usr/local/prometheus/prometheus.yml
- job_name: gateway
static_configs:
- targets: ['127.0.0.1:9091']
labels:
instance: gateway
#热加载生效
curl -XPOST http://IP:9090/-/reload
#查看网页
http://IP:9091
API推送metrics
格式:一般标签名采用 instance
http://pustgatewayIP/metrices/job/job名/标签名/标签值
- 单条数据
echo "backup_status `cat /data/galera/backup/mysqldump/dumpdata/\`date +\"%Y%m%d\"\`/full_db.dmp |grep "completed" |wc -l`" | curl --data-binary @- http://IP:9091/metrics/job/backup_node/instance/IP
- 多条数据
#!/bin/bash
#Author:mh
#date:2020/11/17
mysqlbin="/usr/local/mariadb/bin/mysql -uprometheus -p*** -h *** -P ***"
mysqladminbin="/usr/local/mariadb/bin/mysqladmin -uprometheus -p*** -h *** -P ***"
cat <<EOF | curl --data-binary @- http://IP:9091/metrics/job/guizou1/instance/IP*/node/control
# HA/keepalived/httpd/memcaches
service_haproxy `systemctl status haproxy | grep Active | grep -E "running|exited" | wc -l`
service_keepalived `systemctl status keepalived | grep Active | grep -E "running|exited" | wc -l`
service_httpd `systemctl status httpd | grep Active | grep -E "running|exited" | wc -l`
service_memcached `systemctl status memcached | grep Active | grep -E "running|exited" | wc -l`
#OpenStack_Server
service_neutron_server `systemctl status neutron-server | grep Active | grep -E "running|exited" | wc -l`
...
#DB_galera
mysql_up2 `${mysqladminbin} ping | grep -c alive`
mysql_connections `${mysqlbin} -NBe "use information_schema;select count(*) from PROCESSLIST;"`
mysql_galera_status `${mysqlbin} -e "SHOW STATUS LIKE 'wsrep_local_state'" |grep -i 'wsrep_local_state' |awk '{print $2}'`
mysql_galera_cluster_size `${mysqlbin} -e "show status like 'wsrep_cluster_size'"|grep -i 'wsrep_cluster_size' |awk '{print $2}'`
mysql_galera_cluster_conf_id `${mysqlbin} -e "show status like 'wsrep_cluster_conf_id'" |grep -i 'wsrep_cluster_conf_id' |awk '{print $2}'`
mysql_status_com_commit `${mysqlbin} -e "show status like 'com_commit'" |grep -i 'com_commit' |awk '{print $2}'`
mysql_status_com_rollback `${mysqlbin} -e "show status like 'com_rollback'" |grep -i 'com_rollback' |awk '{print $2}'`
mysql_status_com_select `${mysqlbin} -e "show status like 'com_select'" |grep -i 'com_select' |awk '{print $2}'`
mysql_status_com_update `${mysqlbin} -e "show status like 'com_update'" |grep -i 'com_update' |awk '{print $2}'`
mysql_status_com_insert `${mysqlbin} -e "show status like 'com_insert'" |grep -i 'com_insert' |awk '{print $2}'`
mysql_status_com_delete `${mysqlbin} -e "show status like 'com_delete'" |grep -i 'com_delete' |awk '{print $2}'`
EOF
Alertmanager
通过在prometheus.yml配置文件中添加规则的方式,计算触发条件后发出警报
Alert三种状态
- pending:警报被激活,但是低于配置的持续时间【rule里for设置的时间】该状态下不发送报警。
- firing: 警报已被激活,而且超出设置的持续时间。该状态下发送报警。
- inactive:既不是pending也不是firing时
触发一条告警过程
prometheus-->触发阈值-->超出持续时间-->alertmanager-->分组|抑制|静默-->媒体:邮件|钉钉|微信等。
- 分组: 通过route的group_by进行报警分组,多条消息一起发送,将性质类似告警组合成一条告警发出,从而减少告警数量;
- 抑制: 高级别报警抑制低级别报警。减少由于高级别告警引发的系列低级别告警,从而减少告警数量;
- 静默:故障静默(在页面配置),对已知故障在维护修复期间可以确保在接下来的时间内不会在收到同样报警信息。从而减少告警数量。
rule_mysql.yml
更新规则后热加载生效(需要在prometheus启动时加上--web.enable-lifecycle参数)
curl -XPOST http://172.28.8.143:9090/-/reload
配置rule
vim /usr/local/prometheus/rules/rule_mysql.yml
groups:
- name: MySQL #报警分组名称
rules:
- alert: OS is down #报警名称 alertname
expr: up{job="mysql_galera"} == 0 #条件表达式
for: 1m #服务宕机持续时间
labels:
severity: critical #报警级别
annotations: #注释,添加实例
summary: "Instance {{ $labels.instance }} OS is down"
description: "MySQL OS is down. This requires immediate action!"
- alert: MySQL server is down
expr: mysql_up{job="mysql_galera"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Instance {{ $labels.instance }} MySQL is down"
description: "MySQL server is down. This requires immediate action!"
Prometheus-webhook-dingtalk
tar -zxf prometheus-webhook-dingtalk-1.4.0.linux-amd64.tar.gz -C /usr/local/
mv prometheus-webhook-dingtalk-1.4.0.linux-amd64 prometheus-webhook-dingtalk-1.4.0
./prometheus-webhook-dingtalk --config.file=webhook_config.yml --web.enable-lifecycle &
配置 webhook_config.yml
## Request timeout
# timeout: 5s
templates:
- contrib/templates/legacy/template.tmpl
default_message:
title: '{{ template "legacy.title" . }}'
## Targets, previously was known as "profiles"
targets:
webhook1:
url: https://oapi.dingtalk.com/robot/send?access_token=***
# secret for signature
# secret: SEC000000000000000000000
# webhook2:
# url: https://oapi.dingtalk.com/robot/send?access_token=xxxxxx
# webhook_legacy:
# url: https://oapi.dingtalk.com/robot/send?access_token=xxxxxx
# # Customize template content
# message:
# # Use legacy template
# title: '{{ template "legacy.title" . }}'
# text: '{{ template "legacy.content" . }}'
# webhook_mention_all:
# url: https://oapi.dingtalk.com/robot/send?access_token=xxxxxxx
# mention:
# all: true
webhook_mention_users:
url: https://oapi.dingtalk.com/robot/send?access_token=***
#default_message:
# at: { "atMobiles":["17****"] , "isAtAll":"false" }
⚠️ 在电脑端钉钉创建接收告警群
新建群名称-XX业务XX服务告警-->添加机器人-->选择自定义-->获取机器人token
TSDB Admin APIs
⚠️ 需要在启动prometheus 服务时添加参数--web.enable-admin-api 才能使用API
数据备份
curl -XPOST http://localhost:9090/api/v1/admin/tsdb/snapshot
{
"status": "success",
"data": {
"name": "20171210T211224Z-2be650b6d019eb54"
}
}
#快照存储在 <data-dir>/snapshots/20171210T211224Z-2be650b6d019eb54
# skip_head=<bool>: 选择是否跳过备份内存中的数据,默认跳过
# 不跳过内存中的数据,即同时备份内存中的数据
curl -XPOST http://172.28.8.143:9090/api/v1/admin/tsdb/snapshot?skip_head=false
# 跳过内存中的数据
curl -XPOST http://127.0.0.1:9090/api/v2/admin/tsdb/snapshot?skip_head=true
数据恢复
将snapshot中的文件覆盖到data目录下,重启prometheus即可
数据删除
删除一个时间范围内一系列选择的数据,实际数据仍然存在于磁盘上,并在以后的压缩中进行清理。可以通过单击Clean Tombstones端点进行显式清理。
参数
- match[]=<series_selector>: Repeated label matcher argument that selects the series to delete. At least one match[] argument must be provided.
- start=<rfc3339 | unix_timestamp>: Start timestamp.
- end=<rfc3339 | unix_timestamp>: End timestamp.
curl -X POST -g 'http://172.28.8.143:9090/api/v1/admin/tsdb/delete_series?match[]=backup_status&match[]={job="gateway"}'
⚠️ 如果不同时提及开始时间和结束时间,会清除数据库中匹配序列的所有数据。
Clean Tombstones
从磁盘上删除已删除的数据,并清理现有的逻辑删除。删除后可以使用它来释放空间。
curl -XPOST http://localhost:9090/api/v1/admin/tsdb/clean_tombstones
PTSDB
原理
核心:倒排索引+窗口存储Block
数据写入按2h一个窗口,2h内产生的数据存储在Head Block中,每一个块中包含该时间窗口内的所有样本数据(chunks),元数据文件(meta.json)以及索引文件(index),最新写入的数据保存在内存block中, 2小时后写入磁盘。后台线程把2小时的数据最终合并成更大的数据块。
PTSDB内存大小由最小时间周期,采集周期以及时间线数量决定。
防止程序异常而导致数据丢失采取的措施
- WAL机制,即2小时内记录的数据存储在内存中的同时,还会记录一份日志,存储在block下的wal目录中。当程序再次启动时,会将wal目录中的数据写入对应的block中,达到恢复数据效果。
- 删除数据时,删除条目会记录在tombstones 中,而不是立刻删除。
ll /usr/local/prometheus/data
drwxr-xr-x 3 root root 68 Nov 17 07:00 01EQ9MJQBFPPR27ECX56AWPGX4
drwxr-xr-x 3 root root 68 Nov 23 23:00 01EQTSX62XKFRN5JX2JZS334TN
drwxr-xr-x 3 root root 68 Nov 24 17:00 01EQWQPD2BWPNDNZRNTWN3NYDF
drwxr-xr-x 3 root root 68 Nov 25 11:00 01EQYNFZ2KJHHZP9GFFM08P918
drwxr-xr-x 3 root root 68 Nov 25 17:00 01EQZA32A527R17FWN47S4FPGA
drwxr-xr-x 3 root root 68 Nov 25 17:00 01EQZA32XV9173J7ZYN7D74YAS
drwxr-xr-x 3 root root 68 Nov 25 17:57 01EQZD5RWRCFWE8X8M2QWVKRHA
drwxr-xr-x 2 root root 104 Jan 20 14:19 chunks_head
-rw-r--r-- 1 root root 20001 Jan 20 16:44 queries.active
drwxr-xr-x 2 root root 6 Dec 8 14:45 snapshots
drwxr-xr-x 3 root root 4096 Jan 20 14:17 wal
ll 01EQ9MJQBFPPR27ECX56AWPGX4
drwxr-xr-x 2 root root 20 Sep 30 09:00 chunks #000001 保存timeseries数据
-rw-r--r-- 1 root root 157769 Sep 30 09:00 index #通过metric名和labels查找时序数据在chunk文件中的位置
-rw-r--r-- 1 root root 277 Sep 30 09:00 meta.json #配置文件,包含起止时间、包含哪些block
-rw-r--r-- 1 root root 9 Sep 30 09:00 tombstones #删除操作会首先记录到这个文件
测试数据量
运行时间 | 采集频率 | 监控项总量 | 存储占用 |
---|---|---|---|
7d | 10s | 55203 | 6G |
PromQL (Prometheus Query Language)
查询语法
加减乘除:+ - * / % ^
比较运算:== != > < >= <=
逻辑运算:and or
聚合运算:sum min max avg stddev stdvar count topk
内置函数:rate irate abs ceil increse sort sort_desc
时间范围单位 :s/m/h/d/w/y【秒/分/小时/天/周/年】
查询结果类型
瞬时数据 : 包含一组时序,每个时序只有一个点
http_requests_total
区间数据 : 包含一组时序,每个时序有多个点
http_requests_total[5m]
纯量数据 : 只有一个数字,没有时序
count(http_requests_total)
查询举例
#范围查询: 过去1分钟数据
mysql_global_status_aborted_connects{instance="172.x.x.132:9104"}[1m]
#范围查询:查询结果
mysql_global_status_aborted_connects{idc="xxx",instance="172.x.x.132:9104",job="mysql"}
54 @1611124329.273
54 @1611124344.273
54 @1611124359.273
54 @1611124374.273
#比较查询:查询某项监控超过某个数值
mysql_global_status_aborted_connects>20
#比较查询:查询结果
Element Value
mysql_global_status_aborted_connects{idc="xxx",instance="172.x.x.132:9104",job="mysql"} 54
mysql_global_status_aborted_connects{idc="xxx",instance="172.x.x.133:9104",job="mysql"} 5263
Grafana
#[Red Hat, CentOS, RHEL, and Fedora(64 Bit)]
wget https://dl.grafana.com/oss/release/grafana-7.2.2-1.x86_64.rpm
sudo yum install grafana-7.2.2-1.x86_64.rpm -y
systemctl status grafana-server
influxDB简介
InfluxDB特性
- 极简架构:单机版的InfluxDB只需要安装一个binary,即可运行使用,没有任何外部依赖。
- 极强的写入能力: 底层采用自研TSM (Time-Structured Merge Tree) 存储引擎,基于LSM,提供极强写能力以及高压缩率。
- 高效查询:对Tags会进行索引,提供高效检索。
- InfluxQL:提供SQL-Like的查询语言,方便使用
- Continuous Queries: 通过CQ能够支持auto-rollup和pre-aggregation,对常见的查询操作可以通过CQ来预计算加速查询。
名词对比
概念 | MySQL | InfluxDB |
---|---|---|
数据库 | database | database |
表 | table | measurement |
列 | column | Point:tag/field/timestemp(唯一主键) |
Point由时间戳(time)数据(field)和标签(tags)组成。
- time:每条数据记录的时间,也是数据库自动生成的主索引;
- fields:各种记录的值;
- tags:各种有索引的属性。
⚠️
tag 只能为字符串类型,field 类型无限制。
支持连续查询操作:CONTINUOUS QUERY,不支持join。
部署
#rpm安装
wget https://dl.influxdata.com/influxdb/releases/influxdb-1.8.3.x86_64.rpm
yum install -y influxdb-1.8.3.x86_64.rpm
sudo yum localinstall influxdb-1.8.3.x86_64.rpm
systemctl start influxdb.service
ps -ef | grep influx
influxdb 7017 1 0 15:15 ? 00:00:01 /usr/bin/influxd -config /etc/influxdb/influxdb.conf
#tar安装
wget https://dl.influxdata.com/influxdb/releases/influxdb-1.8.3_linux_amd64.tar.gz
tar -zxf influxdb-1.8.3_linux_amd64.tar.gz -C /usr/local/
cd /usr/local/;mv influxdb-1.8.3-1/ influxdb-1.8.3-1
mkdir -p /var/data/influxdb/{meta,data,wal}
#修改配置文件中路径相关设置后启动
/usr/local/influxdb-1.8.3-1/usr/bin/influxd --config /usr/local/influxdb-1.8.3-1/etc/influxdb/influxdb.conf &
netstat -tunlp|grep 8086
tcp6 0 0 :::8086 :::* LISTEN 1731275/influxd
#查看InfluxDB相关命令
ll /usr/local/influxdb-1.8.3-1/usr/bin
influxd 启动influxdb服务器
influx influxdb命令行客户端
influx_inspect 查看工具
influx_stress 压力测试工具
influx_tsm 数据库转换工具(将数据库从b1或bz1格式转换为tsm1格式)
export PATH=/usr/local/influxdb-1.8.3-1/usr/bin:$PATH
#客户端登录
./influx -host XXX -port xx 远程连接服务端
常用命令
#创建库
create database "db_name"
#使用库
use db_name
#输出所有数据库
show databases
#输出所有表
show measurements
#匹配输出表
show measurements ON prometheus_data with measurement =~ /threads*/
#删除数据库
drop database "db_name"
#删除表
drop measurement "measurement_name"
#插入
insert test,host=127.0.0.1,monitor_name=test count=1
#查询
select * from mysql_global_status_wsrep_thread_count order by time desc limit 10;
#⚠️ 时间字段默认显示纳秒时间戳,要输出可读格式,需要指定precision后查询。
#也可以指定参数连接数据库:influx -precision rfc3339
precision rfc3339;
select * from mysql_global_status_wsrep_thread_count order by time desc limit 10;
#查看一个measurement中所有的tag key
show tag keys
#查看一个measurement中所有的field key
show field keys
备份数据库
influxd backup -portable /backup/total
influxd backup -portable -db prometheus /backup/prometheus_data
influxd backup -portable -db prometheus -start 2020-07-27T2:31:57Z -end 2020-07-27T2:32:59Z /backup/prometheus_20200701
恢复数据库
--To restore only the telegraf database (dbname database must not exist):
influxd restore -portable -db dbname path-to-backup
--To Restore the existing database backup to a temporary database.
influxd restore -portable -db dbname -newdb dbname_bak path-to-backup
> USE dbname_bak
> SELECT * INTO dbname..:MEASUREMENT FROM /.*/ GROUP BY *
> DROP DATABASE dbname_bak
集群高可用架构
更新中。