admin管理员组文章数量:1646419
一、前言
Prometheus是由SoundCloud开发的开源监控报警系统和时序列数据库(TSDB),基于Go语言开发,是Google BorgMon监控系统的开源版本。Prometheus在2016年加入了云原生计算基金会,成为继Kubernetes之后的第二个项目。
Prometheus通过多种数学算法能实现强大的监控需求,原生支持K8S服务发现,能监控容器的动态变化。并且结合Grafana能绘出漂亮图形,然后使用alertmanager或Grafana实现报警。它与其他监控相比有以下主要优势:
- 1>数据格式是Key/Value形式,简单、速度快;采用多维数据模型(由指标名称和键/值维集定义的timeseries)
\- 2>timeseries收集是通过HTTP上的拉取(pull mode)模型进行,通过中间网关支持timeseries的推送,通过服务发现或静态配置来发现目标,监控数据的精细程度可达到秒级(数据采集精度高情况下,对磁盘消耗大,存在性能瓶颈,且不支持集群,但可以通过联邦能力进行扩展);,
\- 3>不依赖分布式存储,数据直接保存在本地,单节点是自治的,可独立运行管理,可以不需要额外的数据库配置。但是如果对历史数据有较高要求,可以结合OpenTSDB;支持分层和水平联合。
\- 4> 周边插件丰富,如果对监控要求不是特别严格的话,默认的几个成品插件已经足够使用;支持多种图形和仪表板。
\- 5>本身基于数学计算模型,有大量的函数可用,可以实现很复杂的监控(故学习成本高,需要有一定数学思维,独有的数学命令行很难入门);
\- 6>可以嵌入很多开源工具的内部去进行监控,数据更可信。
- 7>使用PromQL,它是一种强大而灵活的查询语言,PromQL作为Prometheus强大的查询语言,可以灵活地处理监视数据。
【Prometheus的三大局限性】
1.更多地展示的是 趋势性 的监控
Prometheus作为一个基于度量的系统,不适合存储事件或者日志等,它更多地展示的是趋势性的监控。如果用户需要数据的精准性(不足),可以考虑ELK或其他日志架构。另外,APM更适用于链路追踪的场景。
2.Prometheus本地不适合存储大量历史数据存储
Prometheus认为只有**最近的监控数据才有查询的需要,所有Prometheus本地存储的设计初衷只是保存短期**(如一个月)的数据,不会针对大量的历史数据进行存储。如果需要历史数据,则建议:使用Prometheus的远端存储,如:OpenTSDB、M3DB等。
3.成熟度没有 InfluxDB高
Prometheus在集群上不论是采用联邦集群还是采用Improbable开源的Thanos等方案,都没有InfluxDB成熟度高,需要解决很多细节上的技术问题(如耗尽CPU、消耗机器资源等问题),部分互联网公司拥有海量业务,出于集群的原因会考虑对单机免费但是集群收费的InfluxDB进行自主研发。
总之,使用Prometheus前一定要了解它的设计理念:它并不是为了解决大容量事件存储问题,TB级以上数据建议保存到远端TSDB中;它是为运行时正确的监控数据准备的,无法做到100%精准,存在由内核故障、刮擦故障等因素造成的微小误差。
官方地址: https://prometheus.io/,显示最新版本为2.22.0,官方维护的Prometheus组件仅提供预编译的二进制文件和Docker映像,其他的需要去Github上获取。
Github上资源:https://github/prometheus/prometheus/releases;prometheus-2.0说明、相关博客
Prometheus它可使用联合模型(federation mode)进行扩展,该模型使得一个 Prometheus 服务器能够抓取另一个 Prometheus 服务器的数据。这允许创建分层拓扑,其中中央系统或更高级别的 Prometheus 服务器可以抓取已从下级实例收集的聚合数据。你可以将 Prometheus 作为后端,配置 Grafana[5] 来提供数据可视化和仪表板功能。
注: Prometheus Blackbox Exporter 0.17.0及之前版本中存在代码问题漏洞。该漏洞源于网络系统或产品的代码开发过程中存在设计或实现不当的问题。Prometheus Exporter Toolkit 0.7.2及0.8.2之前版本存在未明漏洞,攻击者可利用漏洞伪造请求,以破坏用于缓存哈希计算的内部缓存方式,绕过安全性使用此功能。Prometheus Prometheus <2.24.0存在未授权访问漏洞,攻击者可利用该漏洞获取敏感信息,/api/v1/status/flags的web.enable-admin-api和web-enable-lifecycle如果为True则可以关闭服务或者删除所有的端点。Prometheus 2.7.1之前版本中存在跨站脚本漏洞,该漏洞源于WEB应用缺少对客户端数据的正确验证。攻击者可利用该漏洞执行客户端代码。prometheus agent存在端远程命令执行漏洞,影响版本位置,请升级到最新版。
二、工作原理
Prometheus直接从目标主机 上运行的代理程序(exporter) 中抓取指标,并将收集的样本集中存储在自己服务器上(主要以拉模式为主),也可以使用像 collectd_exporter 这样的插件推送指标,尽管这不是 Promethius 的默认行为,但在主机位于防火墙后面或位于安全策略限制打开端口的某些环境中它可能很有用。另外,后者可通过HTTP协议周期性抓取被监控组件的状态,任意组件只要提供对应的HTTP接口就可以接入监控。不需要任何SDK或者其他的集成过程。这样做非常适合做虚拟化环境监控系统,比如:VM、Docker、Kubernetes等;它以给定的时间间隔从已配置的目标收集指标,评估规则表达式,显示结果,并在发现某些情况为真时触发警报。
2.1、Prometheus的主要构成:
1、服务端
Prometheus服务端以一个进程方式启动,如果不考虑参数和后台运行的话,只需要解压安装包之后运行 ./prometheus脚本即可启动,程序默认监听在9090端口。每次采集到的数据叫做metrics。这些采集到的数据会先存放在内存中,然后定期再写入硬盘,如果服务重新启动的话会将硬盘数据写回到内存中,所以对内存有一定消耗。Prometheus不需要重视历史数据,所以默认只会保留15天的数据。
2、客户端
Prometheus客户端分为pull和push两种方式。如果是pull形式的话则是服务端主动向客户端拉取数据,这样需要客户端上安装exporters(导出器)作为守护进程,官网上也提供了很多exporters可以下载使用,比如使用最多的node_exporters,几乎把系统自身相关数据全部采集了,非常全面,node_exporter默认监听9100端口。
如果是push形式的话客户端需要安装pushgateway插件,然后运需要运维人员用脚本把监控数据组织成键值形式提交给pushgateway,再由它提交给服务端。它适合于现有exporters无法满足需求时,自己灵活定制。
2.2、prometheus 相关核心概念
a)、指标
prometheus 所有的监控指标(Metric) 被统一定义为
<metric name >{
<label name>=<label value>,
...
}
prometheus 的每一个时间序列数据都由metric(指标名称)和它的标签(labels)键值对集合唯一确定指标名称: 说明了指标的含义,例如: tcp_request_total 代表 tcp 的请求总数,指标名称必须由字母、数值下画线或者冒号组成,符合正则表达式,如 [a-zA-Z:][a-zA-Z0-9:]*。标签(label) 则用于过滤和聚合;
b)、数据采集
prometheus 采用pull 方式采集监控数据,和采用push 方式采集监控数据不同,
push 方式: agent 主动上报数据,可以将采集的数据立即上报到监控中心,push 方式本地不会保存采集的数据,agent 本身是无状态的服务,master 需要维护各种agent 状态
pull 方式: master 主动拉取 agent 的数据,周期性采集,采集时间为30s 或者更长时间,
agent 本身需要一定的数据存储能力,master 只负责简单的数据拉取
c)、数据处理
prometheus 支持数据处理,主要包括 relabel 、replace、keep、drop
d)、数据存储
prometheus 支持本地存储和远程存储两种方式;存储估算可采用:磁盘大小 = 保留时间 * 每秒获取样本数 * 样本大小;在保留时间(retention_time_seconds)和样本大小(bytes_per_sample)不变的情况下,如果想减少本地磁盘的容量需求,只能通过减少每秒获取样本数(ingested_samples_per_second)的方式:减少时间序列的数量或增加采集样本的时间间隔,经验表明:减少时间序列的数量效果更明显。
#本地存储:Prometheus 按2小时一个block进行存储,每个block由一个目录组成,该目录里包含:一个或者多个chunk文件(保存时间序列数据)默认每个chunk大小为512M、一个metadata文件、一个index文件(通过metric name和labels查找时间序列数据在chunk 块文件的位置。更多参看:https://prometheus.io/docs/prometheus/latest/storage/
ls ./prometheus-data/01HY* #block下的trunk文件,
./prometheus-data/01HYGKY6FEX64SH3JMY90K9VPS:
chunks index meta.json tombstones
./prometheus-data/01HYH1NMTKTCJPZ3R2W0FYD72H:
chunks index meta.json tombstones
./prometheus-data/01HYH8HC2KZR7CSD3TP3XW8XSC:
chunks index meta.json tombstones
./prometheus-data/01HYH8HC8W0DT37Y4J2856TAC8:
chunks index meta.json tombstones
#每2小时生成一个chunks文件
ll ./prometheus-data/01HY*
./prometheus-data/01HYGKY6FEX64SH3JMY90K9VPS:
总用量 108
drwxr-xr-x 2 prometheus prometheus 4096 5月 23 01:00 chunks
-rw-r--r-- 1 prometheus prometheus 94422 5月 23 01:00 index
-rw-r--r-- 1 prometheus prometheus 552 5月 23 01:00 meta.json
-rw-r--r-- 1 prometheus prometheus 9 5月 23 01:00 tombstones
./prometheus-data/01HYH1NMTKTCJPZ3R2W0FYD72H:
总用量 96
drwxr-xr-x 2 prometheus prometheus 4096 5月 23 05:00 chunks
-rw-r--r-- 1 prometheus prometheus 83985 5月 23 05:00 index
-rw-r--r-- 1 prometheus prometheus 276 5月 23 05:00 meta.json
-rw-r--r-- 1 prometheus prometheus 9 5月 23 05:00 tombstones
./prometheus-data/01HYH8HC2KZR7CSD3TP3XW8XSC:
总用量 96
drwxr-xr-x 2 prometheus prometheus 4096 5月 23 07:00 chunks
-rw-r--r-- 1 prometheus prometheus 83985 5月 23 07:00 index
-rw-r--r-- 1 prometheus prometheus 276 5月 23 07:00 meta.json
-rw-r--r-- 1 prometheus prometheus 9 5月 23 07:00 tombstones
./prometheus-data/01HYH8HC8W0DT37Y4J2856TAC8:
总用量 128
drwxr-xr-x 2 prometheus prometheus 4096 5月 23 07:00 chunks
-rw-r--r-- 1 prometheus prometheus 116905 5月 23 07:00 index
-rw-r--r-- 1 prometheus prometheus 697 5月 23 07:00 meta.json
-rw-r--r-- 1 prometheus prometheus 9 5月 23 07:00 tombstones
#未落盘的内容在WAL里,这是因prometheus为了防止程序崩溃导致数据丢失,采用WAL(write-ahead-log)预写日志机制,启动时会以写入日志(WAL)的方式来实现重播,从而恢复数据;落盘后wal文件内对应的数据删除,生成index, tombstones(删除数据的记录),chunks数据文件00001;数据过期清理时间,默认保存15天,删除数据时,删除条目会记录在独立的tombstone 删除记录文件中,而不是立即从chunk文件删除。
ll ./prometheus-data/wal/
总用量 4464
-rw-r--r-- 1 prometheus prometheus 1540096 5月 23 07:00 00000008
-rw-r--r-- 1 prometheus prometheus 1540096 5月 23 09:00 00000009
-rw-r--r-- 1 prometheus prometheus 1470689 5月 23 10:53 00000010
drwxr-xr-x 2 prometheus prometheus 4096 5月 23 09:00 checkpoint.00000007
#落盘后
ll ./prometheus-data/01HYGKY6FEX64SH3JMY90K9VPS/chunks/
总用量 664
-rw-r--r-- 1 prometheus prometheus 674585 5月 23 01:00 000001
1、本地存储:默认保存15天,原生的TSDB对于大数据量的保存及查询支持不太友好 ,所以并不适用于保存长期的大量数据;另外,该数据库的可靠性也较弱,在使用过程中容易出现数据损坏等故障,且无法支持集群的架构。
2、远程存储:Prometheus提供了remote_write和remote_read的特性,支持将数据存储到远端和从远端读取数据的功能。当配置remote_write特性后,Prometheus会将采集到的指标数据通过HTTP的形式发送给适配器(Adaptor),由适配器进行数据的存入。而remote_read特性则会向适配器发起查询请求,适配器根据请求条件从第三方存储服务中获取响应的数据。
e)、数据查询
prometheus 使用promQL 查询
f)、告警
prometheus 本身不会对报警进行处理、需要借助一个组件alertmanager ,prometheus 会配置alertmanager 地址,这样prometheus 发出的告警记录变可以发送到alertmanager 进行处理。
三、系统架构
如上图所示,在上面流程中,Prometheus通过配置文件中指定的服务发现方式来确定要拉取监控指标的目标(Target),接着从要拉取的目标(应用容器和Pushgateway)发起HTTP请求到特定的端点(Metric Path),将指标持久化至本身的TSDB中,TSDB最终会把内存中的时间序列压缩落到硬盘,除此之外,Prometheus会定期通过PromQL计算设置好的告警规则,决定是否生成告警到Alertmanager,后者接收到告警后会负责把通知发送到邮件或企业内部群聊中。
Prometheus的指标名称:只能由 ASCII 字符、数字、下划线以及冒号组成,而且有一套命名规范:
使用基础Unit(如seconds而非milliseconds)
指标名以application namespace作为前缀,如:
process_cpu_seconds_total
http_request_duration_seconds
用后缀来描述Unit,如:
http_request_duration_seconds
node_memory_usage_bytes
http_requests_total
process_cpu_seconds_total
foobar_build_info
prometheus 组件:
1)prometheus server 端 :负责定时在目标上抓取metrics(指标)数据,每个抓取目标都需要暴露一个http 服务接口用于 prometheus 定时抓取,这种调用监控对象获取监控数据的方式称为pull
2)prometheus client 端: 为需要监控的服务生成相应的 metrics 并暴露给 Prometheus server
3)Push Gateway:主要用于短期的 jobs。由于这类 jobs 存在时间较短,可能在Prometheus 来 pull 之前就消失了。为此,这次 jobs 可以直接向 Prometheus server 端推送它们的 metrics。这种方式主要用于服务层面的 metrics,对于机器层面的 metrices,需要使用 node exporter。
4)Exporters:支持如 HAProxy,StatsD,Graphite,Redis 一类的服务;
5 )Alertmanager:从 Prometheus server 端接收到 alerts 后,会进行去除重复数据,分组,并路由到对收的接受方式,发出报警。常见的接收方式有:电子邮件,pagerduty,OpsGenie, webhook 等。
6)Prometheus Agent Mode(从Prometheus v2.32.0引入使用)—server mode
Prometheus的Agent模式针对远程写入场景进行了优化。该模式中禁用了查询、警报和本地存储,并将其替换为自定义的TSDB WAL(Write-Ahead Logging)。Prometheus Agent 内置在Prometheus中,无需额外的软件,具有prometheus原生的抓取API、相同的语义、相同的配置和服务发现机制。通过Prometheus Agent模式remote write远端存储,实现多个prometheus向同一个prometheus 输出数据(这也是推荐的一种采集模式);Prometheus Agent remote write方案相比较联邦和APIServer方式配置简单,可以解决多集群监控数据冗余问题,同时可在remotewrite中配置**过滤规则,**减轻远端Prometheus数据处理压力。Remote Write支持将k8s集群内Prometheus采集的metrics写到远程存储中,远程存储可以是Prometheus,被写入prometheus需要开启web.enable-remote-write-receiver,表示本prometheus接受来着其他prometheus的远程写入,也可以是其他时序数据库。对于用户,可直接从远端存储中读取数据,并访问全局视图。
采用agent mode有如下好处:
- 高效:agent模式下的TSDB WAL在成功写入后会立即删除原始数据,然后传给远端的prometheus endpoint,,如果远端不可用,本地会临时缓存2个小时的数据到本地磁盘直至远端endpoint可用,因此agent模式下不需要在内存中构建数据块来保存数据,我们也不需要为查询目的维护完整的索引。从本质上讲,代理模式使用的资源只是prometheus服务器在类似情况下所用资源的很小一部分,有效降低了资源耗用,从而采集指标更有效率。
- 更易水平弹性扩展:新Agent模式的一大好处是它能够更容易地实现采集的水平可扩展性。代理模式本质上将发现、抓取和远程写入转移到了单独的微服务中。这使得一个专注于指标采集的操作模型成为可能;于server mode的有状态不同,agent mode基本是无状态的。我们可以部署多个Prometheus代理,并安全地更改指定哪个副本去抓取哪些目标;终,所有样本都将被推送到同一个中央存储器。总之,代理模式下的Prometheus支持基于Prometheus的抓取的简单水平自动缩放功能,从而让我们可以对指标目标的动态变化做出及时反应,减少人工的限制。
--enable-feature= ... Comma separated feature names to enable. Valid options: agent, exemplar-storage, expand-external-labels, memory-snapshot-on-shutdown, promql-at-modifier, promql-negative-offset, remote-write-receiver,
extra-scrape-metrics, new-service-discovery-manager. See https://prometheus.io/docs/prometheus/latest/feature_flags/ for more details.
agent 模式启用:使用prometheus二进制运行时,启用--enable-feature=agent
即可让prometheus运行在agent模式下;更多参看prometheus标志帮助和Prometheus Agent Mode介绍、prometheus-agent-mode,通过检查标志帮助字符串的最后一句,您可以看到哪个标志适用于哪种模式。注:若Prometheus进程启用agent模式,原Prometheus的完整功能,被精简为只有:discovery\scrape\remoteWrite,原server模式下的Query/Alert/Local Storage等功能都不可用。
四、安装部署过程
1)软件下载:
wget https://github/prometheus/prometheus/releases/download/v2.22.0/prometheus-2.22.0.linux-amd64.tar.gz
#最新版
wget https://github/prometheus/prometheus/releases/download/v2.53.1/prometheus-2.53.1.linux-amd64.tar.gz
#windows
wget https://github/prometheus/prometheus/releases/download/v2.48.0/prometheus-2.48.0.windows-amd64.tar.gz
#Linux:2023-11-16发布的最新版,修复多达11个bug和多项功能增强
https://github/prometheus/prometheus/archive/refs/tags/v2.48.0.tar.gz
wget https://github/prometheus/prometheus/releases/download/v2.48.0/prometheus-2.48.0.linux-amd64.tar.gz
wget https://github/prometheus/prometheus/releases/download/v2.48.0/prometheus-web-ui-2.48.0.tar.gz
wget https://github/prometheus/prometheus/releases/download/v2.48.0/sha256sums.txt
2)安装
采用预编译二进制文件或docker映像方式均可
mkdir prometheus
chmod 777 -R prometheus
groupadd prometheus //添加用户,用此账号启动服务
useradd -g prometheus -s /sbin/nologin prometheus
chown -R prometheus:prometheus /usr/local/prometheus/
mkdir -p /home/software/prometheus-data
chown -R prometheus:prometheus /home/software/prometheus-data
touch /usr/lib/systemd/system/prometheus.service //配置prometheus服务,实现开机启动
chown prometheus:prometheus /usr/lib/systemd/system/prometheus.service
vim /usr/lib/systemd/system/prometheus.service
配置Prometheus服务端自启动服务:
[Unit]
Description=Prometheus
Documentation=https://prometheus.io/
After=network.target
[Service]
# Type设置为notify时,服务会不断重启
Type=simple
User=prometheus //注意目录权限,否则会启动失败
# --storage.tsdb.path是可选项,默认数据目录在运行目录的./dada目录中;配启用服务热加载:--web.enable-lifecycle
ExecStart=/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml --storage.tsdb.path=/home/software/prometheus-data --web.enable-lifecycle
Restart=on-failure
ki11mode=process
Execreload=/bin/ki11 -HUP $MAINPID
[Install]
WantedBy=multi-user.target
配置完成后,就可以如下这样启动服务了:
systemctl enable prometheus
systemctl start prometheus
systemctl status prometheus
curl -XPOST http://localhost:9090/-/reload #修改配置文件后热重载服务,前提--web.enable-lifecycl启用,如下所示:
./prometheus --web.enable-lifecycle --config.file=prometheus.yml #之后就可以执行如下命令热加载了
systemctl daemon-reload
systemctl restart prometheus
1> Docker执行:
$ docker run --name prometheus -d -p 127.0.0.1:9090:9090 prom/prometheus
//完成之后,就可访问 http://localhost:9090/。
vim prometheus.yml
global:##全局
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
alerting:##告警配置
alertmanagers:
- static_configs:
- targets: []
scheme: http
timeout: 10s
api_version: v1
scrape_configs:监控配置
- job_name: prometheus
honor_timestamps: true
scrape_interval: 15s
scrape_timeout: 10s
metrics_path: /metrics
scheme: http
static_configs:静态配置
- targets:
- localhost:9090
完成之后:
docker run \
-p 9090:9090 \
-v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
或:
docker run -d -p 9090:9090 -v /root/prometheus:/etc/prometheus --name prometheus prom/prometheus
2> 二进制方式:
tar -zxvf prometheus-2.22.0.linux-amd64.tar.gz -C /usr/local/
cd /usr/local
mv prometheus-2.22.0.linux-amd64/ prometheus
cd prometheus/
ls #其中,data目录是默认数据库存储位置,除非启动时使用--storage.tsdb.path=/path重新指定
console_libraries consoles data LICENSE NOTICE prometheus prometheus-data prometheus.yml promtool static
./prometheus --version
修改prometheus.yml文件,配置启动ip:vim prometheus.yml
#Prometheus全局配置
global:
scrape_interval: 15s #采集数据间隔,默认15秒。该配置可配置在每个job_name中
evaluation_interval: 15s #监控规则评估频率,比如设置了内存使用大于70%发出报警的规则,然后每15秒来执行一次这个规则
#Prometheus告警设置
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
#监控配置
scrape_configs:
- job_name: 'prometheus-server' #定义一个监控组,其下可以有多个实例配置,这里用于监控prometheus自身
static_configs:
- targets: ['localhost:9090'] #节点的地址,可以写多个地址
- job_name: 'www_server' #定义另一个监控组
static_configs:
- targets: ['10.160.2.107:9100','192.168.1.100:9100'] #组内多个被监控主机
labels: #自定义标签,可以通过标签对查询数据进行分组管理
idc:beijing #将上面2个主机打上idc标签,值为beijing
# params: #过滤器
# collect[]:
# - cpu #只采集CPU数据
####使用正则替换标签
# - job_name: 'mysql_node'
# static_configs:
# - targets: ['10.160.2.110:9100','192.168.1.111:9100']
# metric_relable_configs: #通过正则重命名标签
# - action: replace #replace替换是默认动作。此外还有keep(只采集匹配标签的实例)、drop(不采集匹配正则的实例)、labelkeep\labeldrop(对标签进行过滤处理而非实例)等动作
# source_labels: ['job'] #原标签,job是默认就会产生的标签,这里job标签的值是mysql_node
# regex: (.*) #正则匹配,这里匹配job标签内的内容,也就是node
# replacement: beijing #替换成什么内容,如果写$1就是将正则里的内容拿过来
# target_label: idc #把替换到的内容赋值给idc标签
# - action: labeldrop #删除标签
# regex: job #把原有的job标签删除不显示
remote_write:
- url: "http://localhost:9201/write"
remote_read:
- url: "http://localhost:9201/read"
修改:
job_name: 'prometheus'
metrics_path defaults to '/metrics'
scheme defaults to 'http'.
static_configs:
- targets: ['10.173.10.12:9090']
检查配置文件:protool check config prometheus.yml
启动服务:nohup ./prometheus --config.file=prometheus.yml &S
或者详细点:
./prometheus --config.file="/usr/local/prometheus-2.16.0.linux-amd64/prometheus.yml" \
--web.listen-address="0.0.0.0:9090" \
--storage.tsdb.path="/data/prometheus" \
--storage.tsdb.retention.time=15d --web.enable-lifecycle &
选项说明:
–config.file=“/usr/local/prometheus/prometheus.yml” #指定配置文件路径
–web.listen-address=“0.0.0.0:9090” #指定服务端口
–storage.tsdb.path=“/data/prometheus” #指定数据存储路径
–storage.tsdb.retention.time=15d #数据保留时间
–collector.systemd #开启systemd的服务状态监控,开启后在WEB上可以看到多出相关监控项
–collector.systemd.unit-whitelist=(sshd|nginx).service #对systemd具体要监控的服务名
–web.enable-lifecycle #开启热加载配置
注意: 配置文件检查没有问题后就可以启动服务了,服务默认监听在9090端口。如果不加任何参数,监控数据会存放在/usr/local/prometheus/data下,那些一长串一长串的文件夹都是已经写入到磁盘中的历史数据。写入磁盘前的数据是放在内存中的,如果发生断电等情况就会使用硬盘中的数据进行恢复。抓取 /metrics 的间隔秒数控制了时间序列数据库的粒度。这在配置文件中定义为 scrape_interval 参数,默认情况下设置为 60 秒。在 scrape_configs 部分中为每个抓取作业设置了目标。每个作业都有自己的名称和一组标签,可以帮助你过滤、分类并更轻松地识别目标。一项作业可以有很多目标。
另外,prometheus可有采用两种热加载方式运行,一个是直接用kill命令发送HUP信号,一个是开启web.enable-lifecycle选项后使用curl命令:
A:kill -HUP
pidof prometheus
B:curl -X POST http://localhost:9090/-/reload
3)访问prometheus web页面:
浏览器打开: http://localhost:9090/graph
在上述页面打开:http://localhost:9090/graph 或打击graph切到,然后表达式里输入:prometheus_target_interval_length_seconds后单击执行,prometheus就会输出一组时序指标,都是采集间隔这个指标,而后根据不同的延迟百分比打了不同的标签以示区分,效果如下:
如果只想查看99%分位数统计的延迟率,可单击或执行:prometheus_target_interval_length_seconds{quantile="0.99"}
;执行count(prometheus_target_interval_length_seconds)
可查看当前指标的统计指标数量;执行:rate(prometheus_tsdb_head_chunks_created_total[1m])可查看prometheus采集指标是每秒chunk创建的速率;更多参看:官网expression说明。
在Status菜单下,Configuration,Rule,Targets等,在Statu–>Configuration展示prometheus.yml的配置,Statu–>Targets展示监控具体的监控目标:
4) Prometheus 查询
转到 Prometheus 服务器上的 http://localhost:9090/graph。你将看到一个查询编辑器和两个选项卡:“Graph” 和 “Console”。
Prometheus 将所有数据存储为时间序列,使用指标名称标识每个数据。例如,指标 node_filesystem_avail_bytes 显示可用的文件系统空间。指标的名称可以在表达式框中使用,以选择具有此名称的所有时间序列并生成即时向量。如果需要,可以使用选择器和标签(一组键值对)过滤这些时间序列,例如:node_filesystem_avail_bytes{fstype=“ext4”}
过滤时,你可以匹配“完全相等”(=)、“不等于”(!=),“正则匹配”(=)和“正则排除匹配”(!)。以下示例说明了这一点:
要过滤 node_filesystem_avail_bytes 以显示 ext4 和 XFS 文件系统:node_filesystem_avail_bytes{fstype=~“ext4|xfs”}
要排除匹配:node_filesystem_avail_bytes{fstype!=“xfs”}
还可以使用方括号得到从当前时间往回的一系列样本。你可以使用 s 表示秒,m 表示分钟,h 表示小时,d 表示天,w 表示周,而 y 表示年。使用时间范围时,返回的向量将是范围向量。
例如,以下命令生成从五分钟前到现在的样本:node_memory_MemAvailable_bytes[5m]
Prometheus 还包括了高级查询的功能,例如:
100 * (1 - avg by(instance)(irate(node_cpu_seconds_total{job=‘webservers’,mode=‘idle’}[5m])))
请注意标签如何用于过滤作业和模式。指标 node_cpu_seconds_total 返回一个计数器,irate()函数根据范围间隔的最后两个数据点计算每秒的变化率(意味着该范围可以小于五分钟)。要计算 CPU 总体使用率,可以使用 node_cpu_seconds_total 指标的空闲(idle)模式。处理器的空闲比例与繁忙比例相反,因此从 1 中减去 irate 值。要使其为百分比,请将其乘以 100。
5)部署监控端组件: node_exporter
Node_exporter收集机器的系统数据,这里采用prometheus官方提供的exporter,除node_exporter外,官方还提供consul,memcached,haproxy,mysqld等exporter。这里在prometheus服务和 node节点部署相关服务。更多参看:官网node-exporter监控linux主机、exporter说明和使用。
利用第三方源:
对于Centos/RHEL 7:
curl -Lo /etc/yum.repos.d/_copr_ibotty-prometheus-exporters.repo https://copr.fedorainfracloud/coprs/ibotty/prometheus-exporters/repo/epel-7/ibotty-prometheus-exporters-epel-7.repo
对于Centos/RHEL 8:
curl -Lo /etc/yum.repos.d/_copr_ibotty-prometheus-exporters.repo https://copr.fedorainfracloud/coprs/ibotty/prometheus-exporters/repo/epel-8/ibotty-prometheus-exporters-epel-8.repo
执行:yum install node_exporter
或者:github上下载:
wget https://github/prometheus/node_exporter/releases/download/v1.0.1/node_exporter-1.0.1.linux-amd64.tar.gz
tar -zxvf node_exporter-1.0.1-rc.0.linux-amd64.tar.gz -C /usr/local/
cd /usr/local/
mv node_exporter-1.0.1-rc.0.linux-amd64 node_exporter
设置用户(节点):
groupadd prometheus
useradd -g prometheus -s /sbin/nologin prometheus
chown -R prometheus:prometheus /usr/local/node_exporter
监控节点上配置自启动服务:
vim /usr/lib/systemd/system/node_exporter.service
//如果没有就创建一个该文件
[Unit]
Description=node_exporter
Documentation=https://prometheus.io/
Requires=network.target remote-fs.target
After=network.target #或network.target remote-fs.target
[Service]
Type=simple
User=prometheus
Group=prometheus
ExecStart=/usr/local/node_exporter/node_exporter -web.listen-address-0.0.0.0:9100
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
完成后就可启动服务了:
systemctl enable node_exporter
systemctl start node_exporter
对于Windows:
wget https://github/prometheus-community/windows_exporter/releases/download/v0.14.0/windows_exporter-0.14.0-amd64.exe
wget https://github/prometheus-community/windows_exporter/releases/download/v0.14.0/windows_exporter-0.14.0-amd64.msi
插件安装完成后,访问http://ip:9182/metrics 验证
6)prometheus 升级
#只要我们没有使用任何标记为实验性/不稳定的功能,对主要版本的升级通常无需任何操作调整,损坏原服务的风险很小。任何重大更改都将在过程中标记为CHANGE,附:Grafana升级参考:https://grafana/docs/grafana/latest/upgrade-guide/
#版本验证
prometheus -version #需升级到2.53.1
prometheus, version 2.47.0 (branch: HEAD, revision: efa34a5840661c29c2e362efa76bc3a70dccb335)
build user: root@409eb5e6b30c
build date: 20230906-10:20:07
go version: go1.21.0
platform: linux/amd64
tags: netgo,builtinassets,stringlabels
promtool --version #promtool命令可以将旧规则文件转换为新格式,promtool update rules file-name.rules
#关停所有关联服务
systemctl stop prometheus
systemctl stop alertmanager.service
systemctl stop blackbox.service
systemctl stop grafana-server.service
#下载新版本
curl -LO https://github/prometheus/prometheus/releases/download/v2.53.1/prometheus-2.53.1.linux-amd64.tar.gz
wget https://github/prometheus/prometheus/releases/download/v2.53.1/prometheus-2.53.1.linux-amd64.tar.gz
#验证:2234aa0f66d9f9b854144f6faaaed72a316df7a680d9dad7cb48e49a6fa5332c
sha256sum -c sha256sums.txt 2>&1 | grep OK
tar xvf prometheus-2.53.1.linux-amd64.tar.gz
#替换
cp prometheus-2.53.1.linux-amd64/{prometheus,promtool} /usr/local/bin
chown prometheus:prometheus /usr/local/bin/{prometheus,promtool}
cp -r prometheus-2.17.2.linux-amd64/{consoles,console_libraries} /etc/prometheus/
chown -R prometheus:prometheus /etc/prometheus
#修改配置:旧版本只读旧数据,新版本采集读系新数据,且读取旧版本数据
#编辑旧版本的服务文件修改端口为别的,尤其1.x升级到2.x时,因Prometheus2.0中的新时间序列数据库tsdb与Prometheus 1.x不兼容,这意味着您无法使用Prometheus 2从Prometheus 1.x实例中读取数据,且需要将1.x Prometheus至少升级到版本1.8.2,删除1.x Prometheus中的所有配置文件,除了external_labels,旧的Prometheus仅作为数据存储存在
vi /etc/systemd/system/prometheus1.service
……
ExecStart=/usr/local/bin/prometheus1
-config.file /etc/prometheus1/prometheus.yml
-storage.local.path /var/lib/prometheus1/
-web.listen-address ":9089" #这里将默认的9090修改为9089
编辑新版本的 prometheus.yml,增加
...
remote_read:
- url: http://localhost:9089/api/v1/read #对应读旧版本的
#2.0中,备份老的prometheus的数据,一般在/var/lib/prometheus下,或你的目录下的./data目录,实际不备份也可以,2.x的新版本会自动读取原数据目录,自动加载
ls -l /var/lib/prometheus
#拷贝老的监控数据到新的prometheus, Prometheus 1.8 to Prometheus 2.0 参考:https://prometheus.io/docs/prometheus/latest/migration/;2.0以后可以直接读取
#用新的二进制文件,手动启动验证
caller=dir_locker.go:77 level=warn component=tsdb msg="A lockfile from a previous execution already existed. It was replaced" file=/data1/prometheus/data/lock
ts=2024-08-08T06:56:15.985Z caller=head.go:626 level=info component=tsdb msg="Replaying on-disk memory mappable chunks if any"
ts=2024-08-08T06:56:16.454Z caller=head.go:713 level=info component=tsdb msg="On-disk memory mappable chunks replay completed" duration=469.181643ms
ts=2024-08-08T06:56:16.454Z caller=head.go:721 level=info component=tsdb msg="Replaying WAL, this may take a while"
ts=2024-08-08T06:56:16.706Z caller=head.go:758 level=info component=tsdb msg="WAL checkpoint loaded"
ts=2024-08-08T06:56:17.809Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8840 maxSegment=8846
ts=2024-08-08T06:56:19.441Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8841 maxSegment=8846
ts=2024-08-08T06:56:21.099Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8842 maxSegment=8846
ts=2024-08-08T06:56:22.777Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8843 maxSegment=8846
ts=2024-08-08T06:56:24.494Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8844 maxSegment=8846
ts=2024-08-08T06:56:26.207Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8845 maxSegment=8846
ts=2024-08-08T06:56:26.208Z caller=head.go:793 level=info component=tsdb msg="WAL segment loaded" segment=8846 maxSegment=8846
ts=2024-08-08T06:56:26.208Z caller=head.go:830 level=info component=tsdb msg="WAL replay completed" checkpoint_replay_duration=252.403757ms wal_replay_duration=9.501267318s wbl_replay_duration=197ns chunk_snapshot_load_duration=0s mmap_chunk_replay_duration=469.181643ms total_replay_duration=10.222982797s
ts=2024-08-08T06:56:26.242Z caller=main.go:1169 level=info fs_type=EXT4_SUPER_MAGIC
ts=2024-08-08T06:56:26.242Z caller=main.go:1172 level=info msg="TSDB started"
ts=2024-08-08T06:56:26.242Z caller=main.go:1354 level=info msg="Loading configuration file" filename=/data1/prometheus/prometheus.yml
ts=2024-08-08T06:56:26.248Z caller=main.go:1391 level=info msg="updated GOGC" old=100 new=75
ts=2024-08-08T06:56:26.248Z caller=main.go:1402 level=info msg="Completed loading of configuration file" filename=/data1/prometheus/prometheus.yml totalDuration=6.203364ms db_storage=1.867µs remote_storage=1.904µs web_handler=856ns query_engine=1.912µs scrape=4.831708ms scrape_sd=165.459µs notify=40.346µs notify_sd=21.084µs rules=34.415µs tracing=12.033µs
ts=2024-08-08T06:56:26.248Z caller=main.go:1133 level=info msg="Server is ready to receive web requests."
ts=2024-08-08T06:56:26.248Z caller=manager.go:164 level=info component="rule manager" msg="Starting rule manager..."
ts=2024-08-08T06:56:33.880Z caller=compact.go:576 level=info component=tsdb msg="write block" mint=1723017600000 maxt=1723024800000 ulid=01J4RCCPJDQC6HX2HRTSKYGS3A duration=2.570418263s ooo=false
ts=2024-08-08T06:56:33.927Z caller=head.go:1355 level=info component=tsdb msg="Head GC completed" caller=truncateMemory duration=44.262507ms
ts=2024-08-08T06:56:35.817Z caller=compact.go:576 level=info component=tsdb msg="write block" mint=1723024800100 maxt=1723032000000 ulid=01J4RCCS5ECDWY7F1DRQKF6ZR4 duration=1.851291704s ooo=false
#检查启动文件
[Unit]
Description=Prometheus Service
After=network.target
[Service]
ExecStart=/data1/prometheus/prometheus \
--config.file=/data1/prometheus/prometheus.yml \
--web.read-timeout=5m \
--web.max-connections=10 \
--storage.tsdb.retention=15d \
--storage.tsdb.path=/data1/prometheus/data \
--query.max-concurrency=20 \
--query.timeout=2m
User=root
[Install]
WantedBy=multi-user.target
#启动
systemctl daemon-reload
systemctl start prometheus
systemctl enable prometheus
systemctl start alertmanager.service
systemctl start blackbox.service
systemctl start grafana-server.service
#验证
prometheus — version
五、常见监控配置
5.1、Grafana添加仪表盘
这里我们使用现成的模板导入即可,GitHub上面很多人开发了dashboards模板,官方社区上也有很多开源的dashboards模板,我们只需要把模板的额JSON文件导入到grafana即可,参看官网免费的dashboards模板。
5.2、Grafana之服务端口检测
这里我们采用prometheus的Blackbox 采集器,它支持通过 HTTP、HTTPS、DNS、TCP、ICMP 和 gRPC 对目标监测点进行黑盒探测(黑盒监控即以用户的身份测试服务的外部可见性,即我们只关注某个功能端口,某个特定点,而不关注服务运行的细节;黑盒监控相较于白盒监控最大的不同在于黑盒监控是以故障为导向当故障发生时,黑盒监控能快速发现故障,而白盒监控则侧重于主动发现或者预测潜在的问题。一个完善的监控目标是要能够从白盒的角度发现潜在问题,能够在黑盒的角度快速发现已经发生的问题)。主要检测:
- HTTP 测试
定义 Request Header 信息
判断 Http status / Http Respones Header / Http Body 内容- TCP 测试
业务组件端口状态监听
应用层协议定义与监听- ICMP 测试
主机探活机制- POST 测试
接口联通性- SSL 证书过期时间
方法2:请查看Python脚本监控;
1)软件安装
软件下载:https://github/prometheus/blackbox_exporter/releases/download/v0.22.0/blackbox_exporter-0.22.0.linux-amd64.tar.gz
组件地址:https://github/prometheus/blackbox_exporter
目标主机部署blackbox_exporter:
tar -zxvf blackbox_exporter-0.22.0.linux-amd64.tar.gz -C /usr/local/
mv blackbox_exporter-0.22.0.linux-amd64 blackbox_exporter
cd /usr/local/blackbox_exporter
mv blackbox_exporter /usr/sbin/
mkdir -p /etc/blackbox
cp blackbox.yml /etc/blackbox/
useradd -M prometheus -s /sbin/nologin
chown -R prometheus:prometheus /etc/blackbox/
#配置自启动脚本:
vim /usr/lib/systemd/system/blackbox_exporter.service //修改如下
[Unit]
Description=blackbox_exporter
After=network.target
[Service]
User=prometheus
Group=prometheus
ExecStart=/usr/sbin/blackbox_exporter \
--config.file=/etc/blackbox/blackbox.yml
Restart=on-failure
[Install]
WantedBy=multi-user.target
完成后:
systemctl daemon-reload
systemctl enable blackbox_exporter.service
systemctl start blackbox_exporter.service
netstat -tanlp | grep 9115 #查看exporter监听端口
ps -ef |grep blackbox_exporter |grep -v grep |awk '{print $2}' | xargs kill -9 #停止服务
【权限配置】Linux需要ping权限及CAP_NET_RAW权限(使用root作为监控账户,忽略该步骤),配置如下:
vim /etc/sysctl.conf
net.ipv4.ping_group_range = 0 2147483647 #允许anyone都能ping
#配置CAP_NET_RAW权限(允许使用原始套接字)
setcap cap_net_raw+ep blackbox_exporter
#验证
getcap blackbox_exporter
2)Prometheus中配置采集任务
vim /usr/local/prometheus/prometheus.yml
# prometheus.yml
# Prometheus monitor server port config.
global:
scrape_interval: 15s #采集超时时长,更细的超时设置可通过blackbpx的timeout参数来配置
evaluation_interval: 15s
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# 网站监控
- job_name: 'Http_status'
metrics_path: /probe
params:
module: [http_2xx] ##检查HTTP 200响应
static_configs:
- targets: ['http://你的url']
labels:
instance: http_status
group: web
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- target_label: __address__
#replacement: 172.18.1.56:9115 #blackbox的地址和监听端口
replacement: https://$1/ # 替换probe URL为https://ip:443/样式
# ping 检测
- job_name: 'ping_'
metrics_path: /probe
params:
module: [icmp]
static_configs:
- targets: ['122.18.1.23']
labels:
instance: 'ping_status'
group: 'icmp'
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- target_label: __address__
replacement: 172.18.1.56:9115
# 端口监控
- job_name: 'port_status'
metrics_path: /probe //注意这里,否则会报:"INVALID" is not a valid start token错误
params:
module: [tcp_connect]
static_configs:
- targets: ['172.18.1.1:2181','172.18.1.1:61616','172.18.1.1:11211']
labels:
instance: 'port_status'
group: 'port'
labels:
instance: '172.18.1.1'
tags: 'service1'
- targets: ['172.18.1.2:3306']
labels:
instance: '172.18.1.2'
tags: 'service_name'
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: 172.18.1.56:9115
完成后执行:
cd /usr/local/prometheus/
./promtool check config prometheus.yml //检查配置文件是否正确
systemctl restart prometheus //或者没关闭的话直接热加载也行
curl -XPOST http://localhost:9090/-/reload #重载服务
可能报错:
3)配置grafana仪表盘
grafana-cli plugins install grafana-piechart-panel #如果使用饼图,9965模板需要饼图
systemctl restart grafana-server.service
仪表盘可采用11992或直接下载json文件后导入(需要Prometheus blackbox_exporter v0.16.0),grafana模板操作参考。运行 blackbox_exporter 时,需要用户提供探针的配置信息,这些配置信息可能是一些自定义的 http 头信息,也可能是探测时需要的一些 tls 配置,也可能是探针本身的验证行为。在 blackbox_exporter 每一个探针配置称为一个 module,并且以 yaml 配置文件的形式提供给 blackbox_exporter 。每一个 module 主要包含以下配置内容,包括探针类型(prober)、验证访问超时时间(timeout)、以及当前探针的具体配置项;
ID:5990 使用 blackbox exporter 和 prometheus 监控和设置所有 ping 到您服务器的警报。
ID:9965,支持Grafana 8,基于blackbox_exporter 0.19.0设计;采用图表+曲线图方式展示TCP,ICMP,HTTPS的服务状态,各阶段请求延时,HTTPS证书信息等;优化展示效果,支持监控目标的分组、分类级联展示,多服务同时对比展示。grafana 8.3.6、8.3.7、8.4.7 版本测试正常,如果导入出现异常,请先更新到以上版本grafana。模板json下载;
ID:14603:站点可用性监控
ID:3662+2, prometheus自我监控
ID:14750 主机-链路追踪
ID:7587
ID:13587
ID:6436、15873、10408、12275
ID:16292
4)Blackbox_export.yml样例文件参考
modules:
http_2xx_example:
prober: http
timeout: 5s
http:
valid_http_versions: ["HTTP/1.1", "HTTP/2.0"]
valid_status_codes: [] # Defaults to 2xx
method: GET
headers:
Host: vhost.example
Accept-Language: en-US
Origin: example
no_follow_redirects: false
fail_if_ssl: false
fail_if_not_ssl: false
fail_if_body_matches_regexp:
- "Could not connect to database"
fail_if_body_not_matches_regexp:
- "Download the latest version here"
fail_if_header_matches: # Verifies that no cookies are set
- header: Set-Cookie
allow_missing: true
regexp: '.*'
fail_if_header_not_matches:
- header: Access-Control-Allow-Origin
regexp: '(\*|example\)'
tls_config:
insecure_skip_verify: false
preferred_ip_protocol: "ip4" # defaults to "ip6"
ip_protocol_fallback: false # no fallback to "ip6"
http_with_proxy:
prober: http
http:
proxy_url: "http://127.0.0.1:3128"
skip_resolve_phase_with_proxy: true
http_post_2xx:
prober: http
timeout: 5s
http:
method: POST
headers:
Content-Type: application/json
body: '{}'
http_basic_auth_example:
prober: http
timeout: 5s
http:
method: POST
headers:
Host: "login.example"
basic_auth:
username: "username"
password: "mysecret"
http_custom_ca_example:
prober: http
http:
method: GET
tls_config:
ca_file: "/certs/my_cert.crt"
http_gzip:
prober: http
http:
method: GET
compression: gzip
http_gzip_with_accept_encoding:
prober: http
http:
method: GET
compression: gzip
headers:
Accept-Encoding: gzip
tls_connect:
prober: tcp
timeout: 5s
tcp:
tls: true
tcp_connect_example:
prober: tcp
timeout: 5s
imap_starttls:
prober: tcp
timeout: 5s
tcp:
query_response:
- expect: "OK.*STARTTLS"
- send: ". STARTTLS"
- expect: "OK"
- starttls: true
- send: ". capability"
- expect: "CAPABILITY IMAP4rev1"
smtp_starttls:
prober: tcp
timeout: 5s
tcp:
query_response:
- expect: "^220 ([^ ]+) ESMTP (.+)$"
- send: "EHLO prober\r"
- expect: "^250-STARTTLS"
- send: "STARTTLS\r"
- expect: "^220"
- starttls: true
- send: "EHLO prober\r"
- expect: "^250-AUTH"
- send: "QUIT\r"
irc_banner_example:
prober: tcp
timeout: 5s
tcp:
query_response:
- send: "NICK prober"
- send: "USER prober prober prober :prober"
- expect: "PING :([^ ]+)"
send: "PONG ${1}"
- expect: "^:[^ ]+ 001"
icmp_example:
prober: icmp
timeout: 5s
icmp:
preferred_ip_protocol: "ip4"
source_ip_address: "127.0.0.1"
dns_udp_example:
prober: dns
timeout: 5s
dns:
query_name: "www.prometheus.io"
query_type: "A"
valid_rcodes:
- NOERROR
validate_answer_rrs:
fail_if_matches_regexp:
- ".*127.0.0.1"
fail_if_all_match_regexp:
- ".*127.0.0.1"
fail_if_not_matches_regexp:
- "www.prometheus.io.\t300\tIN\tA\t127.0.0.1"
fail_if_none_matches_regexp:
- "127.0.0.1"
validate_authority_rrs:
fail_if_matches_regexp:
- ".*127.0.0.1"
validate_additional_rrs:
fail_if_matches_regexp:
- ".*127.0.0.1"
dns_soa:
prober: dns
dns:
query_name: "prometheus.io"
query_type: "SOA"
dns_tcp_example:
prober: dns
dns:
transport_protocol: "tcp" # defaults to "udp"
preferred_ip_protocol: "ip4" # defaults to "ip6"
query_name: "www.prometheus.io"
5.3、Mysql监控
模板ID:7362;下载地址:https://github/percona/grafana-dashboards/archive/refs/heads/main.zip,配置参考:mysql采集指标-flags、mysqld_exporter、
1)软件下载:https://prometheus.io/download/
#现场使用0.14b版本
wget https://github/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
#0.11版本,其他版本会出现可能grafana无法展示图形
https://github/prometheus/mysqld_exporter/releases/download/v0.11.0/mysqld_exporter-0.11.0.linux-amd64.tar.gz
#exporter依赖go环境,go软件下载
wget https://studygolang/dl/golang/go1.13.linux-amd64.tar.gz
tar -xvf go1.13.linux-amd64.tar.gz -C /usr/local/
echo "export PATH=$PATH:/usr/local/go/bin" >> /etc/profile
source /etc/profile
#验证,现场版本1.17.8
go version
2)配置启动
tar xf prometheus-2.37.0.linux-amd64.tar.gz
mv prometheus-2.37.0.linux-amd64 mysqld_exporter
cd mysqld_exporter/
#mysql创建监控账户,因MySQL_exporter部署在mysql本地,只需localhost访问即可
#权限参考:CREATE USER 'exporter'@'localhost' IDENTIFIED BY 'XXXXXXXX' WITH MAX_USER_CONNECTIONS 3;
#GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'localhost';
Mysql> grant select,replication client,process ON *.* to 'prometheus'@'localhost' identified by '12345678';
Query OK, 0 rows affected (0.000 sec)
Mysql> flush privileges;
Query OK, 0 rows affected (0.000 sec)
vim /usr/local/mysqld_exporter/.myf #新增
[client]
user=prometheus
password=12345678
#启动mysql_exporter代理,默认监听9104
nohup ./mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter/.myf &
#其他启动参数说明
# 选择采集innodb
--collect.info_schema.innodb_cmp
# innodb存储引擎状态
--collect.engine_innodb_status
# 指定配置文件
--config.my-cnf="/etc/myf"
#指定监听端口
--web.listen-address=":9200"
#添加自启动
vi /usr/lib/systemd/system/mysql_exporter.service
[Unit]
Description=https://prometheus.io
[Service]
Restart=on-failure
ExecStart=/usr/local/mysql_exporter/mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter/.myf
[Install]
WantedBy=multi-user.targe
#完成后就可
systemctl daemon-reload
systemctl restart mysql_exporter.service
3)prometheus服务端配置
# 监控业务mysql
- job_name: "mysqld"
static_configs:
- targets: ['172.16.12.20:9104','172.16.12.19:9104']
labels:
instance: mysql_monitor
#sd方式采集
- job_name: mysqls # To get metrics about the mysql exporter’s targets
file_sd_configs:
- files:
- /usr/local/prometheus/sd/mysql-instances.json
metrics_path: /probe
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
# The mysqld_exporter host:port
replacement: localhost:9104
- source_labels: [auth_module]
target_label: __param_auth_module
- action: labeldrop
regex: auth_module
#自动发现规则
vim /usr/local/prometheus/sd/mysql-instances.json #配置如下
[
{
"targets": ["172.17.3.1:3306"],
"labels": {
"app": "MySQL",
"modes": "Primary DB system",
"auth_module": "client"
}
},
{
"targets": ["172.17.3.2:3306"],
"labels": {
"app": "MySQL",
"modes": "Read replica",
"auth_module": "client" # 为每个MySQL指定认证模块
}
}
]
#为上述自动发现规则配置client权限
vim /usr/local/mysqld_exporter/config/config.my-cnf #增加client段
[client]
user=exporter
password='xxxxxx'
完成后重载:curl -XPOST http://localhost:9090/-/reload
本地验证:curl http://127.0.0.1:9104/probe?target=172.17.3.2:3306
4)验证
5.4、web监控:http+https
1)配置文件示例:
#web监控
- job_name: "web_status"
metrics_path: /probe
#scheme: https
#tls_config:
# insecure_skip_verify: true
params:
module: [http_2xx]
static_configs:
- targets: ['https://172.16.12.21:446/dialup/','https://172.16.12.22:446/dialup/']
labels:
instance: web_status
group: web
tags: '业务门户'
relabel_configs:
- source_labels: [__address__] #通过将__address__(当前目标地址)写入__param_target标签来创建一个label
target_label: __param_target #监控目标 www.baidu,作为__address__的value
- source_labels: [__param_target]
target_label: url ##将监控目标与URL创建一个label
- target_label: __address__
replacement: 172.16.12.50:9115
完成后验证配置文件语法:./promtool check config ./prometheus.yml
2)blackbox_exporter.yml示例
modules:
http_2xx:
prober: http
http:
valid_status_codes: [] # 有效的状态码,默认为200,也可以自己定义,比如你的站点304也可能是正常的
method: GET # http使用get请求
fail_if_body_not_matches_regexp: [] # 对返回结果进行正则匹配,如果未匹配成功则认为失败
tls_config:
insecure_skip_verify: true #跳过安全提示
http_post_2xx:
prober: http
http:
method: POST
tcp_connect:
prober: tcp
3)效果验证:
curl http://172.16.12.50:9115/probe?target=https://xxx:446/dialup/\&module=http_2xx\&debug=true //输出如下
Logs for the probe:
ts=2022-08-23T04:11:23.241875569Z caller=main.go:352 module=http_2xx target=https://xxx:446/dialup/ level=info msg="Beginning probe" probe=http timeout_seconds=119.5
ts=2022-08-23T04:11:23.241989713Z caller=http.go:338 module=http_2xx target=https://xxx:446/dialup/ level=info msg="Resolving target address" target=xxx ip_protocol=ip6
ts=2022-08-23T04:11:23.242006767Z caller=http.go:338 module=http_2xx target=https://xxx:446/dialup/ level=info msg="Resolved target address" target=xxx ip=xxxx
ts=2022-08-23T04:11:23.242086827Z caller=client.go:252 module=http_2xx target=https://xxx:446/dialup/ level=info msg="Making HTTP request" url=https://xxxx:446/dialup/ host=xxx:446
ts=2022-08-23T04:13:22.742123571Z caller=main.go:144 module=http_2xx target=https://xxx:446/dialup/ level=error msg="Error for HTTP request" err="Get \"https://xxx:446/dialup/\": context deadline exceeded"
ts=2022-08-23T04:13:22.742203496Z caller=main.go:144 module=http_2xx target=https://xxx:446/dialup/ level=info msg="Response timings for roundtrip" roundtrip=0 start=2022-08-23T12:11:23.242147554+08:00 dnsDone=2022-08-23T12:11:23.242147554+08:00 connectDone=2022-08-23T12:13:22.742173222+08:00 gotConn=0001-01-01T00:00:00Z responseStart=0001-01-01T00:00:00Z tlsStart=0001-01-01T00:00:00Z tlsDone=0001-01-01T00:00:00Z end=0001-01-01T00:00:00Z
ts=2022-08-23T04:13:22.742250097Z caller=main.go:352 module=http_2xx target=https://xxx:446/dialup/ level=error msg="Probe failed" duration_seconds=119.50034233
Metrics that would have been returned:
# HELP probe_dns_lookup_time_seconds Returns the time taken for probe dns lookup in seconds
# TYPE probe_dns_lookup_time_seconds gauge
probe_dns_lookup_time_seconds 1.3798e-05
# HELP probe_duration_seconds Returns how long the probe took to complete in seconds
# TYPE probe_duration_seconds gauge
probe_duration_seconds 119.50034233
# HELP probe_failed_due_to_regex Indicates if probe failed due to regex
# TYPE probe_failed_due_to_regex gauge
probe_failed_due_to_regex 0
# HELP probe_http_content_length Length of http content response
# TYPE probe_http_content_length gauge
probe_http_content_length 0
# HELP probe_http_duration_seconds Duration of http request by phase, summed over all redirects
# TYPE probe_http_duration_seconds gauge
probe_http_duration_seconds{phase="connect"} 0
probe_http_duration_seconds{phase="processing"} 0
probe_http_duration_seconds{phase="resolve"} 1.3798e-05
probe_http_duration_seconds{phase="tls"} 0
probe_http_duration_seconds{phase="transfer"} 0
# HELP probe_http_redirects The number of redirects
# TYPE probe_http_redirects gauge
probe_http_redirects 0
# HELP probe_http_ssl Indicates if SSL was used for the final redirect
# TYPE probe_http_ssl gauge
probe_http_ssl 0
# HELP probe_http_status_code Response HTTP status code
# TYPE probe_http_status_code gauge
probe_http_status_code 0
# HELP probe_http_uncompressed_body_length Length of uncompressed response body
# TYPE probe_http_uncompressed_body_length gauge
probe_http_uncompressed_body_length 0
# HELP probe_http_version Returns the version of HTTP of the probe response
# TYPE probe_http_version gauge
probe_http_version 0
# HELP probe_ip_addr_hash Specifies the hash of IP address. It's useful to detect if the IP address changes.
# TYPE probe_ip_addr_hash gauge
probe_ip_addr_hash 1.810237746e+09
# HELP probe_ip_protocol Specifies whether probe ip protocol is IP4 or IP6
# TYPE probe_ip_protocol gauge
probe_ip_protocol 4
# HELP probe_success Displays whether or not the probe was a success
# TYPE probe_success gauge
probe_success 0
Module configuration:
prober: http
http:
ip_protocol_fallback: true
method: GET
tls_config:
insecure_skip_verify: true
follow_redirects: true
enable_http2: true
tcp:
ip_protocol_fallback: true
icmp:
ip_protocol_fallback: true
ttl: 64
dns:
ip_protocol_fallback: true
recursion_desired: true
4)效果:
5)其他参考:
- job_name: 'http_status' # 配置job名
metrics_path: /probe # 定义metric获取的路径
params:
module: [http_2xx] # 这里就是我们在black_exporter中定义的模块名
file_sd_configs: # 因需要监控的地址很多,我们这里将所有地址独立出来,后面会介绍该文件
- files:
- '/etc/prometheus/etc.d/job_web.yaml'
refresh_interval: 30s # 30秒刷新一次,当有新的监控地址时,会自动加载进来不需要重启
relabel_configs:
- source_labels: [__address__] # 当前target的访问地址,比如监控百度则为 https://baidu
target_label: __param_target # __param是默认参数前缀,target为参数,这里可以理解为把__address__ 的值赋给__param_target,若监控百度,则target=https://baidu
- source_labels: [__param_target]
target_label: instance # 可以理解为把__param_target的值赋给instance标签
- target_label: __address__
replacement: 172.16.12.50:9115 # web监控原本的target为站点的地址,但Prometheus不是直接去请求该地址,而是去请求black_exporter,故需要把目标地址替换为black_exporter的地址
- targets:
- https://www.baidu/
labels:
env: pro
app: web
project: 百度
desc: 百度生产
- targets:
- https://blog.csdn/
labels:
env: test
app: web
project: CSDN
desc: 测试验证
not_200: yes # 这个自定义标签是为了标识某些地址在正常情况下不是返回200状态码
alermanager配置
groups:
- name: web
rules:
- alert: Web访问异常
expr: probe_http_status_code{not_200 != "yes" } != 200
for: 30s
annotations:
summary: Web 访问异常{{ $labels.instance }}
labels:
Severity: '严重'
- alert: Web访问响应响应时间>3s
expr: probe_duration_seconds >= 3
for: 30s
annotations:
summary: Web 响应异常{{ $labels.instance }}
labels:
Severity: '警告'
- alert: 证书过期时间<30天
expr: probe_ssl_earliest_cert_expiry-time()< 3600*24*30
annotations:
summary: Web 证书将在30天后过期 {{ $labels.instance }}
labels:
Severity: '提醒'
- alert: 证书过期时间<7天
expr: probe_ssl_earliest_cert_expiry-time()< 3600*24*7
annotations:
summary: Web 证书将在30天后过期 {{ $labels.instance }}
labels:
Severity: '严重'
- alert: 证书过期时间<1天
expr: probe_ssl_earliest_cert_expiry-time()< 3600*24*1
annotations:
summary: Web 证书将在30天后过期 {{ $labels.instance }}
labels:
Severity: '灾难'
附:其他参考
1、告警发送邮箱
vim /etc/grafana/grafana.ini # 找到smtp关键字,如下所示
#################################### SMTP / Emailing ##########################
[smtp]
enabled = true # 改成true
host = smtp.exmail.qq:465 # 发送服务器地址和端口,如果使用qq邮箱的话
user = # 这里填写发件邮箱
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
password = # 这里填写发件邮箱密码或授权密码
;cert_file =
;key_file =
skip_verify = true # 改成true
from_address = # 这里填写发件邮箱
;from_name = Grafana
# EHLO identity in SMTP dialog (defaults to instance_name)
;ehlo_identity = dashboard.example
# SMTP startTLS policy (defaults to 'OpportunisticStartTLS')
;startTLS_policy = NoStartTLS
更过参考:1;
2、prometheus配置文件标准示例参考
# my global config
global:
scrape_interval: 15s
evaluation_interval: 30s
# scrape_timeout is set to the global default (10s).
external_labels:
monitor: codelab
foo: bar
rule_files:
- "first.rules"
- "my/*.rules"
remote_write:
- url: http://remote1/push
name: drop_expensive
write_relabel_configs:
- source_labels: [__name__]
regex: expensive.*
action: drop
oauth2:
client_id: "123"
client_secret: "456"
token_url: "http://remote1/auth"
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
- url: http://remote2/push
name: rw_tls
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
headers:
name: value
remote_read:
- url: http://remote1/read
read_recent: true
name: default
enable_http2: false
- url: http://remote3/read
read_recent: false
name: read_special
required_matchers:
job: special
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
scrape_configs:
- job_name: prometheus
honor_labels: true
# scrape_interval is defined by the configured global (15s).
# scrape_timeout is defined by the global default (10s).
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
file_sd_configs:
- files:
- foo/*.slow.json
- foo/*.slow.yml
- single/file.yml
refresh_interval: 10m
- files:
- bar/*.yaml
static_configs:
- targets: ["localhost:9090", "localhost:9191"]
labels:
my: label
your: label
relabel_configs:
- source_labels: [job, __meta_dns_name]
regex: (.*)some-[regex]
target_label: job
replacement: foo-${1}
# action defaults to 'replace'
- source_labels: [abc]
target_label: cde
- replacement: static
target_label: abc
- regex:
replacement: static
target_label: abc
authorization:
credentials_file: valid_token_file
tls_config:
min_version: TLS10
- job_name: service-x
basic_auth:
username: admin_name
password: "multiline\nmysecret\ntest"
scrape_interval: 50s
scrape_timeout: 5s
body_size_limit: 10MB
sample_limit: 1000
metrics_path: /my_path
scheme: https
dns_sd_configs:
- refresh_interval: 15s
names:
- first.dns.address.domain
- second.dns.address.domain
- names:
- first.dns.address.domain
relabel_configs:
- source_labels: [job]
regex: (.*)some-[regex]
action: drop
- source_labels: [__address__]
modulus: 8
target_label: __tmp_hash
action: hashmod
- source_labels: [__tmp_hash]
regex: 1
action: keep
- action: labelmap
regex: 1
- action: labeldrop
regex: d
- action: labelkeep
regex: k
metric_relabel_configs:
- source_labels: [__name__]
regex: expensive_metric.*
action: drop
- job_name: service-y
consul_sd_configs:
- server: "localhost:1234"
token: mysecret
services: ["nginx", "cache", "mysql"]
tags: ["canary", "v1"]
node_meta:
rack: "123"
allow_stale: true
scheme: https
tls_config:
ca_file: valid_ca_file
cert_file: valid_cert_file
key_file: valid_key_file
insecure_skip_verify: false
relabel_configs:
- source_labels: [__meta_sd_consul_tags]
separator: ","
regex: label:([^=]+)=([^,]+)
target_label: ${1}
replacement: ${2}
- job_name: service-z
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
authorization:
credentials: mysecret
- job_name: service-kubernetes
kubernetes_sd_configs:
- role: endpoints
api_server: "https://localhost:1234"
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
basic_auth:
username: "myusername"
password: "mysecret"
- job_name: service-kubernetes-namespaces
kubernetes_sd_configs:
- role: endpoints
api_server: "https://localhost:1234"
namespaces:
names:
- default
basic_auth:
username: "myusername"
password_file: valid_password_file
- job_name: service-kuma
kuma_sd_configs:
- server: http://kuma-control-plane.kuma-system.svc:5676
- job_name: service-marathon
marathon_sd_configs:
- servers:
- "https://marathon.example:443"
auth_token: "mysecret"
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
- job_name: service-nomad
nomad_sd_configs:
- server: 'http://localhost:4646'
- job_name: service-ec2
ec2_sd_configs:
- region: us-east-1
access_key: access
secret_key: mysecret
profile: profile
filters:
- name: tag:environment
values:
- prod
- name: tag:service
values:
- web
- db
- job_name: service-lightsail
lightsail_sd_configs:
- region: us-east-1
access_key: access
secret_key: mysecret
profile: profile
- job_name: service-azure
azure_sd_configs:
- environment: AzurePublicCloud
authentication_method: OAuth
subscription_id: 11AAAA11-A11A-111A-A111-1111A1111A11
resource_group: my-resource-group
tenant_id: BBBB222B-B2B2-2B22-B222-2BB2222BB2B2
client_id: 333333CC-3C33-3333-CCC3-33C3CCCCC33C
client_secret: mysecret
port: 9100
- job_name: service-nerve
nerve_sd_configs:
- servers:
- localhost
paths:
- /monitoring
- job_name: 0123service-xxx
metrics_path: /metrics
static_configs:
- targets:
- localhost:9090
- job_name: badfederation
honor_timestamps: false
metrics_path: /federate
static_configs:
- targets:
- localhost:9090
- job_name: 測試
metrics_path: /metrics
static_configs:
- targets:
- localhost:9090
- job_name: httpsd
http_sd_configs:
- url: "http://example/prometheus"
- job_name: service-triton
triton_sd_configs:
- account: "testAccount"
dns_suffix: "triton.example"
endpoint: "triton.example"
port: 9163
refresh_interval: 1m
version: 1
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
- job_name: digitalocean-droplets
digitalocean_sd_configs:
- authorization:
credentials: abcdef
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
- job_name: dockerswarm
dockerswarm_sd_configs:
- host: http://127.0.0.1:2375
role: nodes
- job_name: service-openstack
openstack_sd_configs:
- role: instance
region: RegionOne
port: 80
refresh_interval: 1m
tls_config:
ca_file: valid_ca_file
cert_file: valid_cert_file
key_file: valid_key_file
- job_name: service-puppetdb
puppetdb_sd_configs:
- url: https://puppetserver/
query: 'resources { type = "Package" and title = "httpd" }'
include_parameters: true
port: 80
refresh_interval: 1m
tls_config:
ca_file: valid_ca_file
cert_file: valid_cert_file
key_file: valid_key_file
- job_name: hetzner
relabel_configs:
- action: uppercase
source_labels: [instance]
target_label: instance
hetzner_sd_configs:
- role: hcloud
authorization:
credentials: abcdef
- role: robot
basic_auth:
username: abcdef
password: abcdef
- job_name: service-eureka
eureka_sd_configs:
- server: "http://eureka.example:8761/eureka"
- job_name: scaleway
scaleway_sd_configs:
- role: instance
project_id: 11111111-1111-1111-1111-111111111112
access_key: SCWXXXXXXXXXXXXXXXXX
secret_key: 11111111-1111-1111-1111-111111111111
- role: baremetal
project_id: 11111111-1111-1111-1111-111111111112
access_key: SCWXXXXXXXXXXXXXXXXX
secret_key: 11111111-1111-1111-1111-111111111111
- job_name: linode-instances
linode_sd_configs:
- authorization:
credentials: abcdef
- job_name: uyuni
uyuni_sd_configs:
- server: https://localhost:1234
username: gopher
password: hole
- job_name: ionos
ionos_sd_configs:
- datacenter_id: 8feda53f-15f0-447f-badf-ebe32dad2fc0
authorization:
credentials: abcdef
- job_name: vultr
vultr_sd_configs:
- authorization:
credentials: abcdef
alerting:
alertmanagers:
- scheme: https
static_configs:
- targets:
- "1.2.3.4:9093"
- "1.2.3.5:9093"
- "1.2.3.6:9093"
tracing:
endpoint: "localhost:4317"
client_type: "grpc"
headers:
foo: "bar"
timeout: 5s
compression: "gzip"
tls_config:
cert_file: valid_cert_file
key_file: valid_key_file
insecure_skip_verify: true
3、Grafana+AlertManager告警
![在这里插入图片描述](https://i-blog.csdnimg/blog_migrate/bacf49db61639388cf42fa6275061676.png#pic_center #pic_center =1000x)
![在这里插入图片描述](https://i-blog.csdnimg/blog_migrate/f00ed9d4438bb2875a5af0341b182e50.png#pic_center #pic_center =1000x)
1)AlertManager安装(默认端口9093)
软件下载地址:https://prometheus.io/download/#alertmanager
wget https://github/prometheus/alertmanager/releases/download/v0.24.0/alertmanager-0.24.0.darwin-amd64.tar.gz
tar xvfz alertmanager-0.24.0.darwin-amd64.tar.gz
mv alertmanager-0.24.0.darwin-amd64 alertmanager
cd alertmanager
./alertmanager --config.file=alertmanager.yml
启动后,浏览器访问:http:// alertmanager IP:9093
2)编写告警规则的yml文件(放在Prometheus下)
cd /usr/local/prometheus
touch alertmanager_rules.yml
vim alertmanager_rules.yml
配置示例如下:
groups:
- name: blackbox_network_stats
rules:
- alert: 'url服务探测失败' #//告警名称
expr: probe_success == 0 #告警的判定条件
for: 60s # 满足告警条件持续时间多久后,才会发送告警
labels: # 标签项
severity: high
alertinfo: push_blackbox_alert
annotations: # 解析项,详细解释告警信息
summary: "{{$labels.host}}:{{$labels.port}}:{{ $labels.instance }}探测失败" #可以显示故障机ip端口
description: "url探测失败,请检查业务是否正常!!!"
summary: "Node down"
- name: base-monitor-rule
rules:
- alert: NodeCpuUsage #告警名称
expr: (100 - (avg by (instance) (irate(node_cpu_seconds_total{job=~".*",mode="idle"}[5m])) * 100)) > 10
for: 1m
labels:
service_name: test
level: warning
annotations:
description: "{{$labels.instance}}: CPU usage is above 10% (current value is: {{ $value }}"
默认的配置:
global:
resolve_timeout: 5m
smtp_from: 'xxx@xxx'
smtp_smarthost: 'smtp.exmail.qq:465'
smtp_auth_username:
smtp_auth_password: 'xxx'
smtp_require_tls: false
smtp_hello: 'Alert'
templates:
- 'template/*.tmpl'
route:
group_by: ['alertname']
group_wait: 10s
group_interval: 10s
repeat_interval: 10m
receiver: 'email.tech'
receivers:
- name:
webhook_configs:
- url: '127.0.0.1:8060/dingtalk/tech1/send' ## dingding webhook
send_resolved: true
email_configs:
- to: 'userxxx1@xxx,user2xxxx@xxx' # 多个用户用逗号隔开
headers: {Subject: "异常报警"}
inhibit_rules:
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: [, 'dev', 'instance']
从上可知, Alertmanager的配置主要包含两个部分:
路由(route)和接收器(receivers)。 所有的告警信息都会从配置中的顶级路由(route)进入路由树,根据路由规则将告警信息发送给相应的接收器。在配置文件中使用route定义了顶级的路由,路由是一个基于标签匹配规则的树状结构。所有的告警信息从顶级路由开始,根据标签匹配规则进入到不同的子路由,并且根据子路由设置的接收器发送告警。
3)prometheus配置文件中开启引用AlertManager配置文件
vim ./prometheus.yml #将注释打开,并配置alertmanager所在ip端口,加上告警规则的yml文件
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
- 172.16.1.5:9093 #解注释
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "alertmanagers_rules.yml"
完成后重启prometheus服务:./prometheus --config.file=prometheus.yml --web.enable-lifecycle &
或curl -X POST http://localhost:9090/-/reload
4)验证:
浏览器访问: http://Prometheus IP:9090/alerts #注意prometheus强制使用的是UTC时间,我们实际的时间是UTC增加8小时就是异常出现的时间,grafana显示时间采用本地时间(北京时间);另外,alertmanager_rules.yml中alert的值要与grafana告警设置的告警名一致
5)编辑grafana配置文件
vim /etc/grafana/grafana.ini
#################################### SMTP / Emailing ##########################
[smtp]
# 开启邮件通道
enabled = true
# 配置邮件服务器
host = smtp.exmail.qq:25
# 发件用户名和密码
user = xxx
password = ********
from_address = xxx
from_name = xxx
另外可参考:配置飞书告警通知;
4、GPE(Grafana、Prometheus、Exporter)+Consul(服务注册和发现)
Consul被设计为对DevOps群体和应用开发者友好,他非常适合现代的、可伸缩的基础设施。Consul有多个组件,但是整体来看,它是你基础设施中用于发现和配置服务的一个工具。它提供如下几个关键功能:
- 服务发现: Consul的某些客户端可以提供一个服务,例如api或者mysql,其它客户端可以使用Consul去发现这个服务的提供者。使用DNS或者HTTP,应用可以很容易的找到他们所依赖的服务。
\- 健康检查: Consul客户端可以提供一些健康检查,这些健康检查可以关联到一个指定的服务(服务是否返回200 OK),也可以关联到本地节点(内存使用率是否在90%以下)。这些信息可以被一个操作员用来监控集群的健康状态,被服务发现组件路由时用来远离不健康的主机。
\- 键值存储: 应用可以使用Consul提供的分层键值存储用于一些目的,包括动态配置、特征标记、协作、leader选举等等。通过一个简单的HTTP API可以很容易的使用这个组件。
\- 多数据中心: Consul对多数据中心有非常好的支持,这意味着Consul用户不必担心由于创建更多抽象层而产生的多个区域。
本文标签: 过程系部prometheus
版权声明:本文标题:Prometheus监控系部署配置过程 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1729455565a1201611.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论