一、简介

Prometheus是最初在SoundCloud上构建的开源系统监视和警报工具包 。自2012年成立以来,许多公司和组织都采用了Prometheus,该项目拥有非常活跃的开发人员和用户社区。现在,它是一个独立的开源项目,并且独立于任何公司进行维护。为了强调这一点并阐明项目的治理结构,Prometheus2016年加入了 Cloud Native Computing Foundation,这是继Kubernetes之后的第二个托管项目

Prometheus 时间序列数据库

Prometheus是一个开源的完整监控解决方案,其对传统监控系统的测试和告警模型进行了彻底的颠覆,形成了基于中央化的规则计算、统一分析和告警的新模型。 相比于传统监控系统Prometheus具有以下优点:

易于管理

Prometheus核心部分只有一个单独的二进制文件,不存在任何的第三方依赖(数据库,缓存等等)。唯一需要的就是本地磁盘,因此不会有潜在级联故障的风险

监控服务的内部运行状态

Prometheus鼓励用户监控服务的内部状态,基于Prometheus丰富的Client库,用户可以轻松的在应用程序中添加对Prometheus的支持,从而让用户可以获取服务和应用内部真正的运行状态

强大的数据模型

所有采集的监控数据均以指标(metric)的形式保存在内置的时间序列数据库当中(TSDB)。所有的样本除了基本的指标名称以外,还包含一组用于描述该样本特征的标签

每一条时间序列由指标名称(Metrics Name)以及一组标签(Labels)唯一标识。每条时间序列按照时间的先后顺序存储一系列的样本值。

表示维度的标签可能来源于你的监控对象的状态,比如code=404或者content_path=/api/path。也可能来源于的你的环境定义,比如environment=produment。基于这些Labels我们可以方便地对监控数据进行聚合,过滤,裁剪

强大的查询语言PromQL

Prometheus内置了一个强大的数据查询语言PromQL。 通过PromQL可以实现对监控数据的查询、聚合。同时PromQL也被应用于数据可视化(如Grafana)以及告警当中

高效

对于监控系统而言,大量的监控任务必然导致有大量的数据产生。而Prometheus可以高效地处理这些数据,对于单一Prometheus Server实例而言它可以处理:数以百万的监控指标、每秒处理数十万的数据点

可扩展

Prometheus是如此简单,因此你可以在每个数据中心、每个团队运行独立的Prometheus Sevrer。Prometheus对于联邦集群的支持,可以让多个Prometheus实例产生一个逻辑集群,当单实例Prometheus Server处理的任务量过大时,通过使用功能分区(sharding)+联邦集群(federation)可以对其进行扩展

易于集成

使用Prometheus可以快速搭建监控服务,并且可以非常方便地在应用程序中进行集成。目前支持: Java, JMX, Python, Go,Ruby, .Net, Node.js等等语言的客户端SDK,基于这些SDK可以快速让应用程序纳入到Prometheus的监控当中,或者开发自己的监控数据收集程序。同时这些客户端收集的监控数据,不仅仅支持Prometheus,还能支持Graphite这些其他的监控工具

同时Prometheus还支持与其他的监控系统进行集成:Graphite, Statsd, Collected, Scollector, muini, Nagios等

Prometheus社区还提供了大量第三方实现的监控数据采集支持:JMX, CloudWatch, EC2, MySQL, PostgresSQL, Haskell, Bash, SNMP, Consul, Haproxy, Mesos, Bind, CouchDB, Django, Memcached, RabbitMQ, Redis, RethinkDB, Rsyslog等等

可视化

Prometheus Server中自带了一个Prometheus UI,通过这个UI可以方便地直接对数据进行查询,并且支持直接以图形化的形式展示数据。同时Prometheus还提供了一个独立的基于Ruby On Rails的Dashboard解决方案Promdash。最新的Grafana可视化工具也已经提供了完整的Prometheus支持,基于Grafana可以创建更加精美的监控图标。基于Prometheus提供的API还可以实现自己的监控可视化UI

开放性

通常来说当我们需要监控一个应用程序时,一般需要该应用程序提供对相应监控系统协议的支持。因此应用程序会与所选择的监控系统进行绑定。为了减少这种绑定所带来的限制。对于决策者而言要么你就直接在应用中集成该监控系统的支持,要么就在外部创建单独的服务来适配不同的监控系统

而对于Prometheus来说,使用Prometheus的client library的输出格式不止支持Prometheus的格式化数据,也可以输出支持其它监控系统的格式化数据,比如Graphite

因此你甚至可以在不使用Prometheus的情况下,采用Prometheus的client library来让你的应用程序支持监控数据采集

 架构图

Prometheus通过直接或者短时jobs中介网关收集监控数据,在本地存储所有收集到的数据,并且通过定义好的rules产生新的时间顺序数据,或者发送警报。Promdash或者其他使用API的clients可以将采集到的数据可视化;在真实环境中可以使用固态硬盘进行存储数据

组件

Prometheus Server 可以通过静态配置管理监控目标,也可以配合使用Service IDiscovery的方式动态管理监控目标,并从这些监控目标中获取数据;用于收集和存储时间序列数据
Client Library 客户端库,为需要监控的服务生成相应的 metrics 并暴露给 Prometheus server。当 Prometheus serverpull 时,直接返回实时状态的 metrics
Push Gateway 主要用于短期的 jobs。由于这类 jobs 存在时间较短,可能在 Prometheuspull 之前就消失了。为此,这次 jobs 可以直接向 Prometheus server 端推送它们的 metrics。这种方式主要用于服务层面的 metrics,对于机器层面的 metrices,需要使用 node exporter
Exporters 用于暴露已有的第三方服务的 metricsPrometheus
Alertmanager Prometheus server 端接收到 alerts 后,会进行去除重复数据,分组,并路由到对收的接受方式,发出报警。常见的接收方式有:电子邮件,pagerdutyOpsGenie, webhook

场景

适用场景:Prometheus 适用于记录文本格式的时间序列,它既适用于以机器为中心的监控,也适用于高度动态的面向服务架构的监控。在微服务的世界中,它对多维数据收集和查询的支持有特殊优势。Prometheus 是专为提高系统可靠性而设计的,它可以在断电期间快速诊断问题,每个 Prometheus Server 都是相互独立的,不依赖于网络存储或其他远程服务。当基础架构出现故障时,你可以通过 Prometheus 快速定位故障点,而且不会消耗大量的基础架构资源

不适用场景:Prometheus 非常重视可靠性,即使在出现故障的情况下,你也可以随时查看有关系统的可用统计信息。如果你需要百分之百的准确度,例如按请求数量计费,那么 Prometheus 不太适合你,因为它收集的数据可能不够详细完整。这种情况下,你最好使用其他系统来收集和分析数据以进行计费,并使用 Prometheus 来监控系统的其余部分

二、安装Prometheus

系统 IP 主机名
CentOS 7.4 192.168.2.4 promethes
CentOS 7.4 192.168.2.5 node1
CentOS 7.4 192.168.2.6 node2

下载链接:poromethes

1、安装部署Prometheus


[root@promethes ~]# yum -y install ntpdate
......
[root@promethes ~]# systemctl start ntpdate
[root@promethes ~]# ntpdate time.nist.gov
10 Jan 21:50:47 ntpdate[3224]: adjust time server 132.163.97.3 offset -0.016673 sec
[root@promethes ~]# ls p*
prometheus-2.32.1.linux-amd64.tar.gz                 [root@poromethes ~]# tar xf prometheus-2.32.1.linux-amd64.tar.gz
.............
....
[root@promethes ~]# mv prometheus-2.32.1.linux-amd64/ /usr/local/prometheus
[root@promethes ~]# cd /usr/local/prometheus
[root@promethes ~]# useradd -M -s /sbin/nologin prometheus
[root@promethes ~]# mkdir data
[root@promethes ~]# chown -R prometheus:prometheus /usr/local/prometheus/             

编写启动脚本

[root@promethes ~]# vim /usr/lib/systemd/system/prometheus.service
[Unit]
Description=Prometheus
After=network.target[Service]
User=prometheus
Group=prometheus
WorkingDirectory=/usr/local/prometheus
ExecStart=/usr/local/prometheus/prometheus
[Install]
WantedBy=multi-user.target保存[root@promethes ~]# systemctl daemon-reload
[root@promethes ~]# systemctl start prometheus
[root@promethes ~]# netstat -lntp | grep prometheus
tcp6       0      0 :::9090                 :::*                    LISTEN      50691/prometheus    

 上方警告解决方式:同步时间即可

2、安装infuxdb

因存储数据的大小受限制和扩展不便需要使用influxdb作为后端数据库来存储数据

 下载时间序列数据库:https://dl.influxdata.com/influxdb/releases/influxdb-1.7.8.x86_64.rpm


[root@promethes ~]# yum localinstall influxdb-1.7.8.x86_64.rpm
................
[root@promethes ~]# cp /etc/influxdb/influxdb.conf  /etc/influxdb/influxdb.conf.bf
[root@promethes ~]# systemctl start influxdb
[root@promethes ~]# influx
Connected to http://localhost:8086 version 1.7.8
InfluxDB shell version: 1.7.8
>
> show databases;
name: databases
name
----
_internal
> create database prometheus;
> show databases;
name: databases
name
----
_internal
prometheus
> exit                [root@promethes ~]# cp /usr/local/prometheus/prometheus.yml /usr/local/prometheus/prometheus.yml.bf
[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml            #加到最前面
remote_write:- url: "http://localhost:8086/api/v1/prom/write?db=prometheus"
remote_read:- url: "http://localhost:8086/api/v1/prom/read?db=prometheus"          # my global config
.....................
.........
.
保存[root@promethes ~]# systemctl restart prometheus

验证是否保存到infuxdb数据库中需要安装node Exporter


[root@promethes ~]# influx
Connected to http://localhost:8086 version 1.7.8
InfluxDB shell version: 1.7.8
> show databases;
name: databases
name
----
_internal
prometheus
> use prometheus
Using database prometheus
> show MEASUREMENTS;               #查看是否有数据
name: measurements
name
----
go_gc_duration_seconds
go_gc_duration_seconds_count
go_gc_duration_seconds_sum
go_goroutines
go_info
..........................
...................
............

如果没有数据说明 prometheus没有获取到数据;可以删除data文件然后重启prometheus服务在进行查看

2.1、 prometheus 配置文件

指标说明

1、Prometheusscrape_interval规则周期性从监控目标上收集数据,然后将数据存储到本地存储上
2、scrape_interval可以设定全局也可以设定单个metrics
3、Prometheusevaluation_interval规则周期性对告警规则做计算,然后更新告警状态
4、evaluation_interval只有设定在全局

配置块
global 全局配置
alerting 告警配置
rule_files 规则文件配置
scrape_configs 拉取配置
remote_read、remote_write 远程读写配置/2.2.1

注意: 不做配置

2.1.1、global全局配置

[ scrape_interval: <duration> | default = 1m ]            #默认抓取周期,单位ms、smhdwy;每15s采集一次数据,默认1分钟[ scrape_timeout: <duration> | default = 10s ]            #拉取超时时间[ evaluation_interval: <duration> | default = 1m ]        #估算规则的默认周期;每15秒计算一次规则,默认1分钟# external systems (federation, remote storage, Alertmanager).external_labels:                                          #和外部系统通信时为时间序列或警情(Alert)强制添加的标签列表[ <labelname>: <labelvalue> ... ][ query_log_file: <string> ]                              # 记录PromQL查询的日志文件

2.1.2、alerting告警配置


alerting:                                                   # Alertmanager相关配置alert_relabel_configs:[ - <relabel_config> ... ]alertmanagers:[ - <alertmanager_config> ... ]

2.1.3、rule_files规则文件配置

指定prometheus加载的任何规则的位置,从所有匹配的文件中读取规则和告警。目前没有规则


rule_files:                                                 # 规则文件列表[ - <filepath_glob> ... ]

2.1.4、scrape_configs拉取配置

指定prometheus监控哪些资源。默认会拉取prometheus本身的时间序列数据,通过http://localhost:9090/metrics进行拉取
一个scrape_config指定一组目标和参数,描述如何拉取它们。在一般情况下,一个拉取配置指定一个作业。在高级配置中,这可能会改变
可以通过static_configs参数静态配置目标,也可以使用支持的服务发现机制之一动态发现目标。
此外,relabel_configs在拉取之前,可以对任何目标及其标签进行修改


scrape_configs:
job_name: <job_name>[ scrape_interval: <duration> | default = <global_config.scrape_interval> ]      #拉取频率[ scrape_timeout: <duration> | default = <global_config.scrape_timeout> ]        #拉取超时时间[ metrics_path: <path> | default = /metrics ]                                    #拉取的http路径#honor_labels 控制prometheus处理已存在于收集数据中的标签与prometheus将附加在服务器端的标签("作业"和"实例"标签、手动配置的目标标签和由服务发现实现生成的标签)之间的冲突
#如果 honor_labels 设置为 "true",则通过保持从拉取数据获得的标签值并忽略冲突的服务器端标签来解决标签冲突
#如果 honor_labels 设置为 "false",则通过将拉取数据中冲突的标签重命名为"exported_<original-label>"来解决标签冲突(例如"exported_instance"、"exported_job"),然后附加服务器端标签
#注意,任何全局配置的 "external_labels"都不受此设置的影响。在与外部系统的通信中,只有当时间序列还没有给定的标签时,它们才被应用,否则就会被忽略
[ honor_labels: <boolean> | default = false ]#honor_timestamps 控制prometheus是否遵守拉取数据中的时间戳
#如果 honor_timestamps 设置为 "true",将使用目标公开的metrics的时间戳
#如果 honor_timestamps 设置为 "false",目标公开的metrics的时间戳将被忽略
[ honor_timestamps: <boolean> | default = true ][ scheme: <scheme> | default = http ]              #配置用于请求的协议params:                                            #可选的http url参数[ <string>: [<string>, ...] ]basic_auth:                                        #在每个拉取请求上配置 username 和 password 来设置 Authorization 头部,password 和 password_file 二选一[ username: <string> ][ password: <secret> ][ password_file: <string> ][ bearer_token: <secret> ]                         #在每个拉取请求上配置 bearer token 来设置 Authorization 头部,bearer_token 和 bearer_token_file 二选一[ bearer_token_file: /path/to/bearer/token/file ]          #在每个拉取请求上配置 bearer_token_file 来设置 Authorization 头部,bearer_token_file 和 bearer_token 二选一tls_config:                                        #配置拉取请求的TLS设置[ <tls_config> ] [ proxy_url: <string> ]                            #可选的代理URLazure_sd_configs:                                  #Azure服务发现配置列表[ - <azure_sd_config> ... ] consul_sd_configs:                                 #Consul服务发现配置列表[ - <consul_sd_config> ... ]dns_sd_configs:                                    #DNS服务发现配置列表[ - <dns_sd_config> ... ]ec2_sd_configs:                                    #EC2服务发现配置列表[ - <ec2_sd_config> ... ]openstack_sd_configs:                              #OpenStack服务发现配置列表[ - <openstack_sd_config> ... ]file_sd_configs:                                   #file服务发现配置列表[ - <file_sd_config> ... ]gce_sd_configs:                                    #GCE服务发现配置列表[ - <gce_sd_config> ... ]kubernetes_sd_configs:                             #Kubernetes服务发现配置列表[ - <kubernetes_sd_config> ... ]marathon_sd_configs:                               #Marathon服务发现配置列表[ - <marathon_sd_config> ... ]nerve_sd_configs:                                  #AirBnB's Nerve服务发现配置列表[ - <nerve_sd_config> ... ]serverset_sd_configs:[ - <serverset_sd_config> ... ]                  #Zookeeper Serverset服务发现配置列表triton_sd_configs:[ - <triton_sd_config> ... ]                     #Triton服务发现配置列表static_configs:[ - <static_config> ... ]                        #静态配置目标列表relabel_configs:[ - <relabel_config> ... ]                       #目标relabel配置列表metric_relabel_configs:                            #metric relabel配置列表[ - <relabel_config> ... ]#每次拉取样品的数量限制
#metric relabelling之后,如果有超过这个数量的样品,整个拉取将被视为失效。0表示没有限制
[ sample_limit: <int> | default = 0 ]

2.1.5、remote_read/remote_write远程读写配置

将数据源与prometheus分离


remote_write:                 #与远程写功能相关的设置[ - <remote_write> ... ]remote_read:                  #与远程读功能相关的设置[ - <remote_read> ... ]

3、在全部服务器上部署Node Exporter

下载:  node_exporter


[root@node1 ~]# tar xf node_exporter-1.3.1.linux-amd64.tar.gz
[root@node1 ~]# mv node_exporter-1.3.1.linux-amd64 /usr/local/node_exporter
[root@node1 ~]# useradd -M -s /sbin/nologin prometheus
[root@node1 ~]# chown -R prometheus:prometheus /usr/local/node_exporter
[root@node1 ~]# cd /usr/local/node_exporter/
[root@node1 node_exporter]# ls
LICENSE  node_exporter  NOTICE[root@node1 node_exporter]# ./node_exporter
.........................
..退出 Ctrl + c

 访问 192.168.2.5:9100  节点服务器

 编写启动脚本


[root@node1 ~]# vim /usr/lib/systemd/system/node_exporter.service
[Unit]
Description=node_exporter
After=network.target[Service]
Type=simple
User=prometheus
Group=prometheus
ExecStart=/usr/local/node_exporter/node_exporter      #注意启动脚本位置--web.listen-address=:9100 --web.telemetry-path=/metrics --log.level=info --log.format=logfmt
Restart=always[Install]
WantedBy=multi-user.target保存[root@node1 ~]# systemctl daemon-reload
[root@node1 ~]# systemctl start node_exporter
[root@node1 ~]# netstat -lntp | grep node_exporter
tcp6       0      0 :::9100                 :::*                    LISTEN      94837/node_exporter 

查看方法一:以下是监控获取的数据


[root@node1 ~]# curl http://localhost:9100/metrics | head              % Total    % Received % Xferd  Average Speed   Time    Time     Time  CurrentDload  Upload   Total   Spent    Left  Speed
100 67784    0 67784    0     0  4730k      0 --:--:-- --:--:-- --:--:-- 5091k
# HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 0
go_gc_duration_seconds{quantile="0.25"} 0
go_gc_duration_seconds{quantile="0.5"} 0
go_gc_duration_seconds{quantile="0.75"} 0
go_gc_duration_seconds{quantile="1"} 0
go_gc_duration_seconds_sum 0
go_gc_duration_seconds_count 0
# HELP go_goroutines Number of goroutines that currently exist.
(23) Failed writing body
HELP 解释以下内容
TYPE 类型

方法二:http://192.168.2.5:9100

4、修改prometheus 配置文件进行采集node信息


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.....
..
scrape_configs:- job_name: "prometheus"static_configs:- targets: ['localhost:9090']- job_name: "node"static_configs:- targets: ['192.168.2.4:9100','192.168.2.5:9100','192.168.2.6:9100']          保存[root@promethes ~]# systemctl restart prometheus             [root@promethes ~]# cd /usr/local/prometheus/
[root@promethes prometheus]# rm -rf data        #删除data数据目录;以防后期查看数据查看不到
[root@promethes prometheus]# systemctl restart prometheus

 访问:192.168.2.4:9090   在Status 中→选择 Targets

 部署的 node exporter 状态是 UP,说明运行正常

显示绿色是已经安装了node exporter,其他未安装的显示为红色

5、使用 PromQL 查询监控数据

Prometheus UI 是 Prometheus 内置的一个可视化管理界面,通过 Prometheus UI 用户可以轻松的了解 Prometheus 当前的配置,监控任务运行状态。通过Graph面板,用户还能直接使用PromQL实时查询监控数据

切换到Graph面板,用户可以使用PromQL 表达式查询特定监控指标的监控数据

 promQLPrometheus自定义的一套强大的数据查询语言,除了使用监控指标作为查询关键字以外,还内置了大量的函数,帮助用户进一步对时序数据进行处理

例:使用 rate()函数,可以计算在单位时间内样本数据的变化情况即增长率,因此通过函数我们可以近似的通过CPU使用时间的利用率

忽略是哪一个CPU的,使用without表达式,将标签CPU去除后聚合数据

6、 实例和任务

Prometheus 中,将任意一个独立的数据源(target)称之为实例(instance)。包含相同类型的实例的集合称之为任务(job

当前在每一个Job中主要使用了静态配置(static_configs)的方式定义监控目标。除了静态配置每一个Job的采集Instance地址以外,Prometheus还支持与DNSConsulE2C、Kubernetes 等进行集成实现自动发现Instance实例,并从这些Instance上获取监控数据

prometheus的数据模型

Prometheus 所有采集的监控数据均以指标(metric)的形式保存在内置时间序列的数据库当中(TSDB):属于同一指标名称,同一标签集合的、有时间戳标记的数据流。除了存储的时间序列,Prometheus 还可以根据查询请求产生临时的、衍生的时间序列作为返回结果

在时间序列中的每一个点称为一个样本(sample),样本由三部分组成

指标(metric) 指标名称和描述当前样本特征的 labelsets
时间戳(timestamp) 一个精确到毫秒的时间戳
样本值(value) 一个 folat64 的浮点型数据表示当前样本的值

每一条时间序列由指标名称(Metrics Name)以及一组标签(键值对)唯一标识。其中指标的名称(metric name)可以反映被监控样本的含义

指标类型

Prometheus 的客户端库中提供了四种核心的指标类型。但这些类型只是在客户端库(客户端可以根据不同的数据类型调用不同的 API 接口)和在线协议中,实际在 Prometheus server 中并不对指标类型进行区分,而是简单地把这些指标统一视为无类型的时间序列

Counter

一种累加的 metric,典型的应用如:请求的个数,结束的任务数, 出现的错误数等等

Gauge

一种常规的 metric,典型的应用如:温度,运行的 goroutines 的个数,可以任意加减

Histogram

柱状图类型,典型的应用如:请求持续时间,响应大小,可以对观察结果采样,分组及统计

Summary

类似于 Histogram, 典型的应用如:请求持续时间,响应大小,提供观测值的 countsum 功能,提供百分位的功能,即可以按百分比划分跟踪结果

7、配置文件案例

1、 给target 添加标签


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
..........
.......static_configs:- targets: ["localhost:9090"]labels:name: linuxUUID: 7.4保存[root@promethes ~]# systemctl restart prometheus          

2、file_sd_configs

[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
..........
.......
rule_files:# - "first_rules.yml"# - "second_rules.yml"# A scrape configuration containing exactly one endpoint to scrape:
# Here it's 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'.static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles:- "/usr/local/prometheus/conf/node-dis.yml"保存

独立文件配置

[root@promethes ~]# mkdir /usr/local/prometheus/conf
[root@promethes ~]# vim /usr/local/prometheus/conf/node-dis.yml- targets: ["192.168.2.4:9100","192.168.2.5:9100","192.168.2.6:9100"]#或者这样配置- targets: - "192.168.2.4:9100"labels: hostname: node
- targets: - "192.168.2.5:9100"labels: hostname: node1
- targets: - "192.168.2.6:9100"labels: hostname: node2保存[root@promethes ~]# systemctl restart prometheus

通过file_fd_files 配置后我们可以在不重启prometheus的前提下, 修改对应的采集文件(node_dis.yml), 在特定的时间内(refresh_interval)prometheus会完成配置信息的载入工作

3、consul_sd_file

由于consul的配置需要有consul的服务提供, 这里简单部署下consul的服务

下载地址:consul


[root@promethes ~]# unzip consul_1.11.1_linux_amd64.zip
Archive:  consul_1.11.1_linux_amd64.zipinflating: consul                  [root@promethes ~]# mv consul /usr/local/bin/
[root@promethes ~]# mkdir /etc/consul.d
[root@promethes ~]# vim /etc/consul.d/prometheus-node.json
{"addresses": {"http": "0.0.0.0","https": "0.0.0.0"},"services": [{"name": "prometheus-node","tags": ["prometheus","node"],"port": 9100}]}保存[root@promethes ~]# consul agent -dev -config-dir=/etc/consul.d   启动

打开web管理界面 192.169.2.4:8500,查看相应的服务信息

可以看到有2service , 其中prometheus-node是我们定义的service

3.1、和prometheus集成


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.........
...static_configs:- targets: ["localhost:9090"]- job_name: "node"consul_sd_configs:- server: 'localhost:8500'services:- prometheus-node保存 ========>注释之前配置的内容[root@promethes ~]# systemctl restart prometheus                

我们通过api接口给该service添加一个节点, 看看是否可以同步过来

                在node1上 查看UUID
——————————————--
[root@node1 ~]# cat /sys/class/dmi/id/product_uuid
84B24D56-7615-AEC7-934B-DCCA1103FD69      —————————————————————— 在promethes 上添加节点[root@promethes ~]# vim node.json
{             "id":"84B24D56-7615-AEC7-934B-DCCA1103FD69",      #修改UUID"Node": "node1","Address": "192.168.2.5",                         #修改地址"Service":{"Port": 9100,"ID": "prometheus-node","Service": "prometheus-node"}
}               保存——————————————————————
[root@promethes ~]# curl -XPUT -d@node.json  127.0.0.1:8500/v1/catalog/register
true

在consul和prometheus的web中查看

4、relabel_config

重新标记是一个功能强大的工具,可以在目标的标签集被抓取之前重写它,每个采集配置可以配置多个重写标签设置,并按照配置的顺序来应用于每个目标的标签集
目标重新标签之后,以 开头的标签将从标签集中删除的
如果使用只需要临时的存储临时标签值的,可以使用 _tmp 作为前缀标识

relabel的action 类型
replace 对标签和标签值进行替换
keep 满足特定条件的实例进行采集,其他的不采集
drop 满足特定条件的实例不采集,其他的采集
labeldrop 对抓取的实例特定标签进行删除
labelkeep 对抓取的实例特定标签进行保留,其他的标签删除

4.1、测试action

测试前,同步下配置文件


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.........
........static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles:- "/usr/local/prometheus/conf/node-dis.yml"          保存

[root@promethes ~]# vim /usr/local/prometheus/conf/node-dis.yml               - targets: - "192.168.2.4:9100"labels: __hostname__: node__businees_line__: "line_A"__region_id__: "cn-beijing"__availability_zone__: "123"
- targets: - "192.168.2.5:9100"labels: __hostname__: node1__businees_line__: "line_B"__region_id__: "cn-beijing"__availability_zone__: "123"
- targets: - "192.168.2.6:9100"labels: __hostname__: node2__businees_line__: "line_C"__region_id__: "cn-beijing"__availability_zone__: "123"修改内容 保存

查看target信息

因我们的 label 都是以 __ 开头的,目标重新标签之后,以 __ 开头的标签将从标签集中删除的

4.2、relabel设置

将labels中的__hostname__替换为 name


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
..............
...........static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles:- "/usr/local/prometheus/conf/node-dis.yml"relabel_configs:- source_labels:- "__hostname__"regex: "(.*)"target_label: "nodename"action: replacereplacement: "$1"保存[root@promethes ~]# systemctl restart prometheus              
         ——————————————————说明relabel_configs:- source_labels:- "__hostname__"regex: "(.*)"target_label: "nodename"action: replacereplacement: "$1"source_labels指定我们需要处理的源标签
target_labels指定了我们要replace后的标签名字
action指定relabel动作,这里使用replace替换动作regex去匹配源标签(__hostname__)的值,"(.*)"代表__hostname__这个标签是什么值都匹配的
replacement指定的替换后的标签(target_label)对应的数值。采用正则引用方式获取的

 查看target信息

 4.3、keep

修改配置文件

[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.................
.........static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles:- "/usr/local/prometheus/conf/node-dis.yml"relabel_configs:- source_labels:- "__hostname__"regex: "(node2)"action: keep保存[root@promethes ~]# systemctl start prometheus

注意:如果发现没有启动说明配置文件有问题仔细查看配置文件确保不少一个空格标点符号

 actionkeep,只要source_labels的值匹配regex(node00)的实例才能会被采集。 其他的实例不会被采集

4.4、drop

在上面的基础上,修改action: keepaction:drop

      action: drop          [root@promethes ~]# systemctl restart prometheus               

actiondrop,其实和keep是相似的, 不过是相反的, 只要source_labels的值匹配regex(node)的实例不会被采集。 其他的实例会被采集

 4.5、labelkeep


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.................
.........static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles:- "/usr/local/prometheus/conf/node-dis.yml"relabel_configs:- source_labels:- "__hostname__"regex: "(.*)"target_label: "Name"action: replacereplacement: "$1"- source_labels:- "__businees_line__"regex: "(.*)"target_label: "line"action: replacereplacement: "$1"- source_labels:- "__address__"regex: "(.*)"target_label: "IP"action: replacereplacement: "$1"保存[root@promethes ~]# systemctl restart prometheus

 4.6、labeldrop


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.................
.........static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles:- "/usr/local/prometheus/conf/node-dis.yml"relabel_configs:- source_labels:- "__hostname__"regex: "(.*)"target_label: "Name"action: replacereplacement: "$1"- source_labels:- "__businees_line__"regex: "(.*)"target_label: "line"action: replacereplacement: "$1"- source_labels:- "__address__"regex: "(.*)"target_label: "IP"action: replacereplacement: "$1"- regex: "(Name|IP)"action: labeldrop保存

8、Prometheus promQL查询语言

Prometheus提供了一种名为PromQL (Prometheus查询语言)的函数式查询语言,允许用户实时选择和聚合时间序列数据。表达式的结果既可以显示为图形,也可以在Prometheus的表达式浏览器中作为表格数据查看,或者通过HTTP API由外部系统使用

修改配置文件

[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml# my global config
global:scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.# scrape_timeout is set to the global default (10s).# Alertmanager configuration
alerting:alertmanagers:- static_configs:- targets:# - alertmanager:9093# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:# - "first_rules.yml"# - "second_rules.yml"# A scrape configuration containing exactly one endpoint to scrape:
# Here it's 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'.static_configs:- targets: ["localhost:9090"]- job_name: "node"file_sd_configs:- refresh_interval: 1mfiles: - "/usr/local/prometheus/conf/node-dis.yml"
remote_write:- url: "http://localhost:8086/api/v1/prom/write?db=prometheus"remote_read:- url: "http://localhost:8086/api/v1/prom/read?db=prometheus"保存

[root@promethes ~]# vim /usr/local/prometheus/conf/node-dis.yml          - targets: - "192.168.2.4:9100"labels: __datacenter__: data__hostname__: node__businees_line__: "line1"__region_id__: "cn-beijing"__availability_zone__: "A"
- targets: - "192.168.2.5:9100"labels: __datacenter__: data2__hostname__: node1__businees_line__: "line2"__region_id__: "cn-beijing"__availability_zone__: "B"
- targets: - "192.168.2.6:9100"labels: __datacenter__: data3__hostname__: node2__businees_line__: "line3"__region_id__: "cn-beijing"__availability_zone__: "C"        保存[root@promethes ~]# systemctl restart prometheus          

时序查询

1、查询特定metric_name


node_forks_total    #节点的forks的总次数

2、带标签的查询


node_forks_total{instance="192.168.2.5:9100"}          

3、多标签查询


node_forks_total{instance="192.168.2.5:9100",job="node"}     

4、查询2分钟的时序数值


node_forks_total{instance="192.168.2.5:9100",job="node"}[2m]        

 5、 正则匹配


node_forks_total{instance=~"192.168.2.*:9100",job="node"}             

 6、子查询


rate(node_cpu_seconds_total{cpu="0",instance="192.168.2.5:9100",job="node",#过去的10分钟内,每分钟计算下过去5分钟的一个速率值,一个采集10m/1m一共10个值

复杂查询

1、计算内存使用百分比


node_memory_MemFree_bytes / node_memory_MemTotal_bytes  * 100              

2、获取所有实例的内存使用百分比前2个


topk(2,node_memory_MemFree_bytes / node_memory_MemTotal_bytes  * 100 )              

实用查询案例

1、获取cpu核心个数


count by (instance) ( count by (instance,cpu) (node_cpu_seconds_total{mode="system"}) )               计算所有的实例cpu核心数


count by (instance) ( count by (instance,cpu) (node_cpu_seconds_total{mode="system",instance="192.168.2.5:9100"}))               计算单个实例的

2、 计算内存使用率


(1 - (node_memory_MemAvailable_bytes{instance=~"192.168.2.5:9100"} / (node_memory_MemTotal_bytes{instance=~"192.168.2.5:9100"})))* 100

3、 计算根分区使用率


100 - ((node_filesystem_avail_bytes{instance="192.168.2.5:9100",mountpoint="/",fstype=~"ext4|xfs"} * 100) / node_filesystem_size_bytes {instance=~"192.168.2.5:9100",mountpoint="/",fstype=~"ext4|xfs"})             

4、  预测磁盘空间

(1-  node_filesystem_avail_bytes{fstype=~"ext4|xfs",mountpoint="/"}/ node_filesystem_size_bytes{fstype=~"ext4|xfs",mountpoint="/"}) * 100 >= 85     and (predict_linear(node_filesystem_avail_bytes[6h],3600 * 24) < 0)                         整体分为 2个部分, 中间用and分割, 前面部分计算根分区使用率大于85的, 后面计算根据近6小时的数据预测接下来24小时的磁盘可用空间是否小于0

9、Prometheus 常见表达式

1、收集内存使用率

node_memory_MemTotal_bytes        #主机上的总内存node_memory_MemFree_bytes         #主机上的空闲内存node_memory_Buffers_bytes         #缓冲区缓存上的内存node_memory_Cached_bytes          #页面缓存中的内存

计算使用内存的百分比

(总内存-(空闲内存-缓冲区+缓存))/ 总内存 * 100


round((node_memory_MemTotal_bytes-(node_memory_MemFree_bytes-node_memory_Buffers_bytes+node_memory_Cached_bytes))/node_memory_MemTotal_bytes * 100)                         

2、收集cpu

1 、收集cpu 利用率:使用irate 的函数,用于计算距离向量正宗时间序列每秒瞬时增长率 ,瞬时增长率


irate(node_cpu_seconds_total{instance='192.168.2.5:9100'}[5m])          

2、avg 平均使用率


avg(irate(node_cpu_seconds_total{job='node',mode='idle'}[5m])) * 100          node:节点根据自己的job进行查询    

3 、平均使用百分比


100 - avg(irate( node_cpu_seconds_total{job='node',mode='idle'}[5m])) * 100      node:节点根据自己的job进行查询       

3、磁盘使用率

1、磁盘使用率百分比 ,空闲的

空闲的空间 / 总空间

node_filesystem_files_free{mountpoint='/',device='/dev/mapper/centos-root',job='node'} / node_filesystem_size_bytes{mountpoint='/',device='/dev/mapper/centos-root',job='node'} * 100node:节点根据自己的job进行查询

2、剩余的磁盘使用率


100 - node_filesystem_files_free{mountpoint='/',device='/dev/mapper/centos-root'}/node_filesystem_size_bytes{mountpoint='/',device='/dev/mapper/centos-root'} * 100                              node:节点根据自己的job进行查询

4、磁盘io

1、io 五分钟的增长率


irate(node_disk_io_time_seconds_total[5m])            

2、五分钟之内的平均值


avg(irate(node_disk_io_time_seconds_total[5m])) * 100                 

3、磁盘io 空闲百分比


100 -(avg(irate(node_disk_io_time_seconds_total[5m])) * 100)                

5、网络

1、网卡 五分钟内的增长率


node_network_receive_bytes_total{device=~'ens33|lo'}[5m]              ens33:修改为自己的网卡名称

2、五分钟之内的平均值


round(irate(node_network_receive_bytes_total{device=~'ens33|lo'}[5m])/1024)                                   

10、常用函数

官方地址:Query functions | Prometheus

常用函数

1、rate函数(速率函数)

rate() 函数是专门搭配counter数据类型使用函数,功能是取counter在这个时间段中平均每秒的增量

1.1、获取网卡1m每秒流量平均


rate(node_network_receive_bytes_total[1m])                          

1.2、只看ens33网卡1m每秒流量平均(即所有服务器ens33)


rate(node_network_receive_bytes_total{device='ens33'}[1m])                       

1.3、只看莫一台服务器ens33网卡1m每秒流量平均 (可以通过,instance,job等修饰进行精确匹配)


rate(node_network_receive_bytes_total{device='ens33',instance='192.168.2.5:9100',job='node'}[1m])                

2、irate函数

irate(v range-vector)计算范围向量中时间序列的每秒即时增长​​率。这基于最后两个数据点。单调性中断(例如由于目标重启而导致的计数器重置)会自动调整

简单说irate就是用于计算速率


irate(node_cpu_seconds_total{cpu="0",instance="192.168.2.5:9100",job='node',mode='idle'}[1m])                          

3、increase函数

increase() 函数表示某段时间内数据的增量;获取数据比较粗糙的时候 类似于5m10m甚至更长时间取样推荐使用increase()

rate() 函数则表示某段时间内数据的平均值;获取数据比较精细的时候 类似于1m取样推荐使用rate()


increase(node_network_receive_bytes_total{device='ens33'}[1m])                                       

4、sum函数

sum()函数就是求和函数;当使用sum后是将所有的监控的服务器的值进行取和,所以在看某一台时需要进行拆分

拆分常用方法
1、by increase() 
2、by (cluster_name)  属于自定义标签不是标准标签,我们可以手动将不痛功能的服务器进行分组展示


sum(rate(node_network_receive_bytes_total{device='ens33'}[1m]))                   

5、topk函数

topk() 函数的定义是:取前面x位的最高值

 Gauge类型使用方式


topk(5,node_cpu_seconds_total)                排在前5位的服务器

Counter类型使用方式必须加rate/increase才有意义


topk(3,rate(node_cpu_seconds_total[5m]))                 

6、count函数

count() 是找出当前或者历史数据中某个key的数值大于或小于某个值的统计

count(node_netstat_Tcp_CurrEstab > 20)                  

11、配合Grafana使用

1、安装Grafana

 下载:Grafana

 或者直接下载到虚拟机


wget https://dl.grafana.com/enterprise/release/grafana-enterprise-8.3.3-1.x86_64.rpm                            
[root@promethes ~]# rm -rf /etc/yum.repos.d/influxdb.repo
[root@promethes ~]# yum localinstall grafana-enterprise-8.3.3-1.x86_64.rpm
...................
.........
[root@promethes ~]# find / -iname 'grafana'       #查看配置文件
/etc/grafana
/var/lib/grafana
/var/log/grafana
/usr/share/grafana
/usr/share/grafana/public/app/plugins/datasource/grafana           [root@promethes ~]# find / -iname 'grafana-server.service' #查看启动脚本
/usr/lib/systemd/system/grafana-server.service          [root@promethes ~]# systemctl restart grafana-server
[root@promethes ~]# netstat -anput|grep 3000
tcp6       0      0 :::3000                 :::*                    LISTEN      12947/grafana-serve 

2、WEB页面配置

访问:192.168.2.4:3000

首次登录会引导你修改密码的

本次实验使用的模板下载地址:node-exporter

如需要其他模板到官方下载地址下载: Grafana官方模板下载    如下图

下载完后解压找到文件:node-exporter-full.json

 进入后会显示以下内容

 导入模板方法有3种这里就使用一种方法

 下面模板下载链接:node-exporter.json

12、Prometheus  AlertManager

Prometheus的报警系统中,是分为2个部分的, 规则是配置是在prometheus中的, prometheus组件完成报警推送给alertmanager的, alertmanager然后管理这些报警信息,包括静默、抑制、聚合和通过电子邮件、on-call通知系统和聊天平台等方法发送通知

1、安装和部署alertmanager

prometheus的所有套件都是比较简单的,这里进行简单部署

下载: alertmanager

如果上方下载不管用到官方页面进行下载:prometheus


[root@promethes ~]# ls al*
alertmanager-0.23.0.linux-amd64.tar.gz[root@promethes ~]# tar xf alertmanager-0.23.0.linux-amd64.tar.gz
[root@promethes ~]# mv alertmanager-0.23.0.linux-amd64 /usr/local/prometheus/alertmanager
[root@promethes ~]# useradd -M -s /sbin/nologin prometheus          #--如果已有用户就不要创建了
[root@promethes ~]# chown prometheus:prometheus /usr/local/prometheus/alertmanager -R
[root@promethes ~]# vim /usr/lib/systemd/system/alertmanager.service                    [Unit]
Description=alertmanager
After=network.target[Service]
User=prometheus
Group=prometheus
WorkingDirectory=/usr/local/prometheus/alertmanager
ExecStart=/usr/local/prometheus/alertmanager/alertmanager  --log.level=debug --log.format=json
# ExecStart=/usr/local/prometheus/alertmanager/alertmanager
[Install]
WantedBy=multi-user.target                保存
——————————————————————————————————————————————————————
[root@promethes system]# systemctl daemon-reload
[root@promethes system]# systemctl restart alertmanager
[root@promethes system]# systemctl status alertmanager
● prometheus.service - PrometheusLoaded: loaded (/usr/lib/systemd/system/prometheus.service; disabled; vendor preset: disabled)Active: active (running) since 二 2022-01-04 21:08:05 CST; 18h agoMain PID: 25049 (prometheus)CGroup: /system.slice/prometheus.service└─25049 /usr/local/prometheus/prometheus1月 05 13:17:59 poromethes prometheus[25049]: ts=2022-01-05T05:17:59.146Z caller=db.go:1279 level=info co...95VJ
1月 05 13:17:59 poromethes prometheus[25049]: ts=2022-01-05T05:17:59.147Z caller=db.go:1279 level=info co...55C3
.............
......
..

2、在prometheus集成alertmanager

部署完成alertmanager后需要告知prometheus告警信息推送的位置

               修改配置文件
[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
..............
.......
.8 alerting:9   alertmanagers:10     - static_configs:11         - targets:12            - 192.168.2.4:9093         #修改
...........
........
......保存

3、创建报警规则


[root@promethes ~]# vim /usr/local/prometheus/prometheus.yml
.......
....15 rule_files:16     - "rules/*rules.yml"17   # - "first_rules.yml"
........
....保存
[root@promethes ~]# mkdir -p /usr/local/prometheus/rules
[root@promethes ~]# vim /usr/local/prometheus/rules/node_rules.yml                groups:- name: node-alertrules:- alert: disk-fullexpr: (1-(node_filesystem_avail_bytes{mountpoint="/",fstype=~"ext4|xfs"} / node_filesystem_size_bytes {mountpoint="/",fstype=~"ext4|xfs"})) * 100 > 50for: 1mlabels:serverity: pageannotations:summary: "{{ $labels.instance }} disk full "description: "{{ $labels.instance }} disk > {{ $value }}  "[root@promethes ~]# systemctl restart prometheus                
Alert 告警规则的名称
expr 基于PromQL表达式告警触发条件,用于计算是否有时间序列满足该条件
for 评估等待时间,可选参数。用于表示只有当触发条件持续一段时间后才发送告警。在等待期间新产生告警的状态为pending
labels 自定义标签,允许用户指定要附加到告警上的一组附加标签
annotations 用于指定一组附加信息,比如用于描述告警详细信息的文字等,annotations的内容在告警产生时会一同作为参数发送到Alertmanager
summary 描述告警的概要信息
description 用于描述告警的详细信息。同时AlertmanagerUI也会根据这两个标签值,显示告警信息

 在web上可以查看到下面的信息

查看当前是否有报警信息

当前磁盘没满,这里进行触发这个报警规则进行测试

 在node1上进行执行以下命令 


[root@node1 ~]# df -h |grep "/$"
/dev/mapper/centos-root   50G  1.4G   49G    3% /[root@node1 ~]# dd if=/dev/zero of=bigfile bs=1M count=40000
记录了40000+0 的读入
记录了40000+0 的写出
41943040000字节(42 GB)已复制,96.1847 秒,436 MB/秒
[root@node1 ~]# df -h  |grep "/$"
/dev/mapper/centos-root   50G   41G  9.6G   81% /

再次查看

 清理文件


[root@node1 ~]# >bigfile
[root@node1 ~]# df -h  |grep "/$"
/dev/mapper/centos-root   50G  1.4G   49G    3% /

上面的消息信息已经从prometheus推送给alertmanager了, 我们已经可以在alertmanagerweb管理界面看到对应的报警信息,但是我们还没有配置如何让alertmanager把这些信息推送我们的社交软件上面去

在poromethes上配置    这里使用qq邮箱进行实验

 QQ邮箱授权码:在QQ邮箱的设置中可以找到

   在promethes机器上进行修改alertmanager.yml配置文件
——————————————————————————————————————————————————————————————
[root@promethes ~]# vim /usr/local/prometheus/alertmanager/alertmanager.yml                                 global:resolve_timeout: 5msmtp_auth_username: "1234567890@qq.com"smtp_auth_password: "这是你的QQ邮箱授权码而不是密码,切记切记"smtp_require_tls: falsesmtp_smarthost: "smtp.qq.com:465"smtp_from: "1234567890@qq.com"
route:group_by: ['alertname']group_wait: 10sgroup_interval: 10srepeat_interval: 1hreceiver: 'jqi'receivers:
- name: 'jqi'email_configs:- send_resolved: trueto: 1234567890@qq.com
inhibit_rules:- source_match:severity: 'critical'target_match:severity: 'warning'equal: ['alertname', 'dev', 'instance']保存[root@promethes ~]# systemctl restart alertmanager                  

 说明

global:  resolve_timeout: 5m     # 经过此时间后,如果尚未更新告警,则将告警声明为已恢复。(即prometheus没有向alertmanager发送告警了)# 配置发送邮件信息smtp_smarthost: 'smtp.qq.com:465'smtp_from: '742899387@qq.com'smtp_auth_username: '742899387@qq.com'smtp_auth_password: 'password'smtp_require_tls: false
——————————————————————————————————————————————————————————————————————————
# 读取告警通知模板的目录
templates:
- '/etc/alertmanager/template/*.tmpl'
——————————————————————————————————————————————————————————————————————————
# 所有报警都会进入到这个根路由下,可以根据根路由下的子路由设置报警分发策略
route:# 先解释一下分组,分组就是将多条告警信息聚合成一条发送,这样就不会收到连续的报警了。# 将传入的告警按标签分组(标签在prometheus中的rules中定义),例如:# 接收到的告警信息里面有许多具有cluster=A 和 alertname=LatencyHigh的标签,这些个告警将被分为一个组group_by: ['alertname', 'cluster', 'service']         #如果不想使用分组,可以这样写group_by: [...]group_wait: 30s                                       #第一组告警发送通知需要等待的时间,这种方式可以确保有足够的时间为同一分组获取多个告警,然后一起触发这个告警信息group_interval: 5m                                    #发送第一个告警后,等待"group_interval"发送一组新告警repeat_interval: 3h                                     # 分组内发送相同告警的时间间隔。这里的配置是每3小时发送告警到分组中。举个例子:收到告警后,一个分组被创建,等待5分钟发送组内告警,如果后续组内的告警信息相同,这些告警会在3小时后发送,但是3小时内这些告警不会被发送# 这里先说一下,告警发送是需要指定接收器的,接收器在receivers中配置,接收器可以是email、webhook、pagerduty、wechat等等。一个接收器可以有多种发送方式# 指定默认的接收器receiver: team-X-mails
——————————————————————————————————————————————————————————————————————————# 下面配置的是子路由,子路由的属性继承于根路由(即上面的配置),在子路由中可以覆盖根路由的配置# 下面是子路由的配置routes:# 使用正则的方式匹配告警标签- match_re:service: ^(foo1|foo2|baz)$                              #这里可以匹配出标签含有service=foo1或service=foo2或service=baz的告警receiver: team-X-mails                                    #指定接收器为team-X-mails# 这里配置的是子路由的子路由,当满足父路由的的匹配时,这条子路由会进一步匹配出severity=critical的告警,并使用team-X-pager接收器发送告警,没有匹配到的告警会由父路由进行处理。routes:- match:severity: criticalreceiver: team-X-pager# 这里也是一条子路由,会匹配出标签含有service=files的告警,并使用team-Y-mails接收器发送告警- match:service: filesreceiver: team-Y-mails# 这里配置的是子路由的子路由,当满足父路由的的匹配时,这条子路由会进一步匹配出severity=critical的告警,并使用team-Y-pager接收器发送告警,没有匹配到的会由父路由进行处理。routes:- match:severity: criticalreceiver: team-Y-pager# 该路由处理来自数据库服务的所有警报。如果没有团队来处理,则默认为数据库团队。- match:# 首先匹配标签service=databaseservice: database# 指定接收器receiver: team-DB-pager# 根据受影响的数据库对告警进行分组group_by: [alertname, cluster, database]routes:- match:owner: team-Xreceiver: team-X-pager# 告警是否继续匹配后续的同级路由节点,默认false,下面如果也可以匹配成功,会向两种接收器都发送告警信息(猜测。。。)continue: true- match:owner: team-Yreceiver: team-Y-pager# 下面是关于inhibit(抑制)的配置,先说一下抑制是什么:抑制规则允许在另一个警报正在触发的情况下使一组告警静音。其实可以理解为告警依赖。比如一台数据库服务器掉电了,会导致db监控告警、网络告警等等,可以配置抑制规则如果服务器本身down了,那么其他的报警就不会被发送出来inhibit_rules:
#下面配置的含义:当有多条告警在告警组里时,并且他们的标签alertname,cluster,service都相等,如果severity: 'critical'的告警产生了,那么就会抑制severity: 'warning'的告警
- source_match:                                #源告警(我理解是根据这个报警来抑制target_match中匹配的告警)severity: 'critical'                       #标签匹配满足severity=critical的告警作为源告警target_match:                                #目标告警(被抑制的告警)severity: 'warning'                        #告警必须满足标签匹配severity=warning才会被抑制。equal: ['alertname', 'cluster', 'service']   #必须在源告警和目标告警中具有相等值的标签才能使抑制生效。(即源告警和目标告警中这三个标签的值相等'alertname', 'cluster', 'service')
————————————————————————————————————————————————————————————# 下面配置的是接收器
receivers:- name: 'team-X-mails'                        #接收器的名称、通过邮件的方式发送email_configs:- to: '1234567890@qq.com'                #发送给哪些人html: '{{ template "email.to.html" . }}'  #HTML模板文件正文send_resolved: true                       #是否通知已解决的警报# 接收器的名称、通过邮件和pagerduty的方式发送、发送给哪些人,指定pagerduty的service_key
- name: 'team-X-pager'email_configs:- to: 'team-X+alerts-critical@example.org'pagerduty_configs:- service_key: <team-X-key># 接收器的名称、通过邮件的方式发送、发送给哪些人
- name: 'team-Y-mails'email_configs:- to: 'team-Y+alerts@example.org'# 接收器的名称、通过pagerduty的方式发送、指定pagerduty的service_key
- name: 'team-Y-pager'pagerduty_configs:- service_key: <team-Y-key># 一个接收器配置多种发送方式
- name: 'ops'webhook_configs:- url: 'http://prometheus-webhook-dingtalk.kube-ops.svc.cluster.local:8060/dingtalk/webhook1/send'send_resolved: trueemail_configs:- to: '1234567890@qq.com'send_resolved: true- to: 'soulchild@soulchild.cn'send_resolved: true

 配置完成上面的操作后进行ping一下百度是否可以通信


[root@promethes ~]# systemctl restart network  #如果配置了确ping不通重启网卡试试

 在node节点上进行测试


[root@node1 ~]# dd if=/dev/zero of=bigfile bs=1M count=40000
记录了40000+0 的读入
记录了40000+0 的写出
41943040000字节(42 GB)已复制,116.25 秒,361 MB/秒

4、自定义报警模板

 修改alertmanager配置文件


[root@promethes ~]# vim /usr/local/prometheus/alertmanager/alertmanager.yml               global:resolve_timeout: 5msmtp_auth_username: "1234567890@qq.com"smtp_auth_password: "这是你的QQ邮箱授权码而不是密码,切记切记"smtp_require_tls: falsesmtp_smarthost: "smtp.qq.com:465"smtp_from: "1234567890@qq.com"
templates:                                                #报警模板
- '/usr/local/prometheus/alertmanager/tamplate/*.tmpl'    #模板位置及文件名
route:group_by: ['alertname']group_wait: 60sgroup_interval: 60srepeat_interval: 1hreceiver: 'jqi'
receivers:
- name: 'jqi'email_configs:- send_resolved: trueto: 1234567890@qq.comhtml: '{{ template "email.html" . }}'                   #指定模板的名称为 email.htmlheaders: { Subject: "[WARN] 报警信息" }                  #自定义主题
inhibit_rules:- source_match:severity: 'critical'target_match:severity: 'warning'equal: ['alertname', 'dev', 'instance']保存

 准备模板


[root@promethes ~]# mkdir -p /usr/local/prometheus/alertmanager/tamplatev
[root@promethes ~]# cd /usr/local/prometheus/alertmanager/tamplate
[root@promethes tamplate]# vim bigfile.tmpl              {{ define "email.html" }}{{ range .Alerts }}<pre>========start==========告警程序: prometheus_alert_email告警级别: {{ .Labels.severity }} 级别告警类型: {{ .Labels.alertname }}故障主机: {{ .Labels.instance }}告警主题: {{ .Annotations.summary }}告警详情: {{ .Annotations.description }}处理方法: {{ .Annotations.console }}触发时间: {{ .StartsAt.Format "2006-01-02 15:04:05" }}========end==========</pre>{{ end }}{{ end }}===========================================            保存
————————————————————————————————————————————————————————————说明
define: 定义模板名称
range: 循环遍历
index: 通过key取值
—————————————————————————————————————————————————————————————[root@promethes ~]# chown -R prometheus:prometheus /usr/local/prometheus/
[root@promethes ~]# systemctl restart prometheus
[root@promethes ~]# systemctl restart alertmanager             [root@promethes ~]# dd if=/dev/zero of=bigfile bs=1M count=40000         

 查看邮箱已经收到报警信息

 自定义模板还不够完善,还需要进一步研究探索

prometheus安装及使用相关推荐

  1. 监控工具—Prometheus—安装部署

    原文作者:虎纠卫 原文地址:监控神器-普罗米修斯Prometheus的安装 目录 步骤1:安装go 语言环境 步骤2:在监控服务器上安装prometheus 步骤3:在系统层用作系统监控 步骤4:安装 ...

  2. Prometheus 安装、部署、出图(使用grafana)

    一.Prometheus安装与部署 注意:gitlab自带Prometheus,并会启动Prometheus服务,所以会冲突,不要将gitlab与Prometheus部署在一起,否则会出现端口冲突问题 ...

  3. 普罗米修斯Prometheus安装和使用

    文章目录 一.prometheus安装 二.AlertManager的使用(邮件告警) 1.原文链接 2.自己操作-prometheus+alertmanager实现CPU的监控报警 3.promet ...

  4. 监控神器普罗米修斯Prometheus安装配置

    一.基础环境 环境/组件 版本 下载地址 操作系统 CentOS 7.3 http://archive.kernel.org/centos-vault/7.3.1611/isos/x86_64/Cen ...

  5. mac m1 prometheus安装与启动

    安装 使用homebrew: brew install prometheus 启动 安装时有提示: 两种启动方式: When run from brew services, prometheus is ...

  6. Prometheus — 安装部署(主机安装)

    目录 文章目录 目录 环境信息 部署 Prometheus Server 部署 Node Exporter 部署 AlertManager 部署 Grafana 添加 Node Exporter 界面 ...

  7. prometheus安装

    1.下载安装包并解压到相关目录 #创建prometheus用户 useradd prometheus cd /home/prometheus wget https://github.com/prome ...

  8. Mac安装prometheus node_exporter

    Mac 安装prometheus brew install prometheus 启动prometheus prometheus --config.file=/usr/local/etc/promet ...

  9. java ini文件_java应用监控之prometheus、node export、grafana安装和配置

    为了与时俱进,介绍基于docker的安装部署,如果想用非docker化部署,可以参考官网教程 对于docker的安装,在cat安装部署已经介绍过了,这里就不再重复了,如果还有不清楚的可以点击这里 do ...

最新文章

  1. 一种注册表沙箱的思路、实现——研究Reactos中注册表函数的实现3
  2. 所谓移动IP是指(58);实现移动IP的关键技术是(59)。【答案】D B
  3. code第一部分数组:第二十二题 偶数次中查找单独出现一次的数
  4. RocketMQ简介、环境搭建
  5. OAuth 2.0攻击方法及案例总结
  6. V210 UART TX 流程
  7. php设置外键约束,关于php:禁用教义外键约束
  8. LeetCode-三数之和
  9. 程序员伪装 AI 编程,竟骗来 2 亿的投资!
  10. 麦克纳姆轮全向移动机器人运动模型及应用分析
  11. eclipse安装maven3
  12. wps for linux alpha 15 语言包,WPS For Linux Alpha 16 发布下载
  13. Python 计算思维训练——数组和曲线绘制练习(一)
  14. BeanUtils.populate的用法
  15. 技术人员谈管理之项目风险规避
  16. 每日分享,一个不错的数据分析实战案例【数据分析可视化】MySQL+Python
  17. 【NEUQ】PJ的情书 【哈夫曼树 】
  18. 数据结构与算法——广度和深度优先搜索
  19. 聚名网:华为申请“燃力红”商标,广告语注册商标需要符合哪些条件呢?
  20. linux的系统监视器图片_用Jetson Nano构建一个价值60美元的人脸识别系统

热门文章

  1. 查验身份证(C语言和Java语言)
  2. 正版软件推荐 - FliTik 翻页时钟 颜值与实力并存工具软件
  3. QQ对话机器人 simsimi接口
  4. 亚信联创 java_亚信联创--java面试题目总结
  5. C++实现已知二叉树前序遍历和中序遍历,求后序遍历
  6. React Native 集成分享第三方登录功能分享第三方登录模块开发(iOS)
  7. 国家数据局成立将带来大数据的五个发展趋势
  8. 学生怎么样充分使用服务器
  9. 《数据库系统概论》期末考试手写笔记汇总+考试注意事项+反思(超全整理总结!!!)
  10. 谈谈我现在毕业后做的工作