引言
在当今高速发展的云计算时代,对于系统资源的监控变得尤为重要。像 CPU 和内存这样的计算资源,是支撑应用程序运行的基础。一旦这些资源出现瓶颈,将直接影响到应用的性能和稳定性。因此,构建一个有效的监控告警系统,能够实时监测资源使用情况,并在异常发生时及时发出警报,成为了云原生环境中不可或缺的一环。本文将引导您了解如何使用 Prometheus 和 Alertmanager 来构建这样一个监控系统,以实现对 CPU 和内存使用的实时监控和告警。
首先,我们需要了解 Prometheus 是什么。
Prometheus 是什么?

Prometheus
Prometheus 是一款开源的监控系统,它的核心功能包括多维度数据模型、灵活的查询语言以及不依赖分布式存储等。Prometheus 通过 Pull 模式抓取指标数据,这意味着服务需要暴露一个端口提供指标信息,而 Prometheus 服务器则会周期性地从这个端口抓取数据。
Prometheus 的优势
Prometheus 是一个开源的完整监控解决方案,其对传统监控系统的测试和告警模型进行了彻底的颠覆,形成了基于中央化的规则计算、统一分析和告警的新模型。 相比于传统监控系统 Prometheus 具有以下优点:
Prometheus 易于管理
Prometheus 核心部分只有一个单独的二进制文件,不存在任何的第三方依赖(数据库,缓存等等)。唯一需要的就是本地磁盘,因此不会有潜在级联故障的风险。
Prometheus 基于 Pull 模型的架构方式,可以在任何地方(本地电脑,开发环境,测试环境)搭建我们的监控系统。对于一些复杂的情况,还可以使用 Prometheus 服务发现(Service Discovery)的能力动态管理监控目标。
监控服务的内部运行状态
Pometheus 鼓励用户监控服务的内部状态,基于 Prometheus 丰富的 Client 库,用户可以轻松的在应用程序中添加对 Prometheus 的支持,从而让用户可以获取服务和应用内部真正的运行状态。

Alerts

Targets
强大的数据模型
所有采集的监控数据均以指标(metric)的形式保存在内置的时间序列数据库当中(TSDB)。所有的样本除了基本的指标名称以外,还包含一组用于描述该样本特征的标签。
dart
http_request_status{code='200',content_path='/api/path', environment='produment'} => [value1@timestamp1,value2@timestamp2...]
http_request_status{code='200',content_path='/api/path2', environment='produment'} => [value1@timestamp1,value2@timestamp2...]

image
每一条时间序列由指标名称(Metrics Name)以及一组标签(Labels)唯一标识。每条时间序列按照时间的先后顺序存储一系列的样本值。
表示维度的标签可能来源于你的监控对象的状态,比如 code=404 或者 content_path=/api/path。也可能来源于的你的环境定义,比如 environment=produment。基于这些 Labels 我们可以方便地对监控数据进行聚合,过滤,裁剪。
强大的查询语言 PromQL
Prometheus 内置了一个强大的数据查询语言 PromQL。 通过 PromQL 可以实现对监控数据的查询、聚合。同时 PromQL 也被应用于数据可视化(如 Grafana)以及告警当中。

node_cpu_seconds_total
通过 PromQL 可以轻松回答类似于以下问题:
- 在过去一段时间中 95%应用延迟时间的分布范围?
- 预测在 4 小时后,磁盘空间占用大致会是什么情况?
- CPU 占用率前 5 位的服务有哪些?(过滤)
高效
对于监控系统而言,大量的监控任务必然导致有大量的数据产生。而 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。

grafana

主机基础监控
开放性
通常来说当我们需要监控一个应用程序时,一般需要该应用程序提供对相应监控系统协议的支持。因此应用程序会与所选择的监控系统进行绑定。为了减少这种绑定所带来的限制。对于决策者而言要么你就直接在应用中集成该监控系统的支持,要么就在外部创建单独的服务来适配不同的监控系统。
而对于 Prometheus 来说,使用 Prometheus 的 client library 的输出格式不止支持 Prometheus 的格式化数据,也可以输出支持其它监控系统的格式化数据,比如 Graphite。
因此你甚至可以在不使用 Prometheus 的情况下,采用 Prometheus 的 client library 来让你的应用程序支持监控数据采集。
如何利用 Prometheus 来监控 CPU 和内存
在 Prometheus 中,可以通过节点导出器(node_exporter)来收集主机级别的监控指标,包括 CPU 和内存的使用情况。节点导出器是一个官方提供的用于暴露硬件和操作系统级别指标的工具。部署并配置好节点导出器后,Prometheus 就能开始抓取相关的监控数据。
ruby
version: '3'
services:
components-prometheus:
image: prom/prometheus:v2.30.3
container_name: components-prometheus
deploy:
resources:
limits:
cpus: '0.8'
memory: 12G
ports:
- 9090:9090
#privileged: true
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./data:/prometheus
- /app/ca/server/server.crt:/etc/prometheus/server.crt
- /app/ca/server/server.key:/etc/prometheus/server.key
- /app/ca/root/ca.crt:/etc/prometheus/ca.crt
- ./rules:/etc/prometheus/rules
#- /data/prometheus/web-config.yml:/etc/prometheus/web-config.yml
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
depends_on:
- node-exporter
environment:
- TZ=Asia/Shanghai
networks:
- monitoring
components-node-exporter:
image: prom/node-exporter:v1.2.2
container_name: components-node-exporter
#privileged: true
ports:
- 9100:9100
volumes:
- /proc:/host/proc:ro
- /sys:/host/sys:ro
- /:/rootfs:ro
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro
command:
- '--path.procfs=/host/proc'
- '--path.sysfs=/host/sys'
- '--collector.filesystem.ignored-mount-points'
- '^/(sys|proc|dev|host|etc)($$|/)'
networks:
- monitoring
environment:
- TZ=Asia/Shanghai
components-alertmanager:
#volumes:
#- ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml
command:
- '--config.file=/etc/alertmanager/alertmanager.yml'
- '--cluster.advertise-address=10.254.0.192:9093'
ports:
- 9093:9093
image: prom/alertmanager
container_name: components-alertmanager
networks:
- monitoring
volumes:
- /etc/localtime:/etc/localtime
- /etc/timezone:/etc/timezone
- ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml
environment:
- TZ=Asia/Shanghai
components-grafana:
image: grafana/grafana
hostname: grafana
container_name: components-grafana
ports:
- 3000:3000
volumes:
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro
environment:
- TZ=Asia/Shanghai
networks:
- monitoring
networks:
monitoring:
name: "monitoring"
ipam:
config:
- subnet: 172.240.0.0/16
prometheus.yml
yaml
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
#rule
rule_files:
- ./rules/*.rules
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['server_ip:9090']
labels:
instance: prometheus
- job_name: 'node_export'
static_configs:
- targets: ['server_ip:9100']
labels:
instance: node_export
#alarm
alerting:
alertmanagers:
- static_configs:
- targets: ['server_ip:9093']
#- scheme: http
#- timeout: 10s

Metric
然而,仅有监控数据是不够的,我们还需要设置告警机制以便在资源使用达到阈值时得到通知。这就是 Alertmanager 发挥作用的地方。Alertmanager 是 Prometheus 生态中的一个组件,主要用于处理由 Prometheus 发出的告警信息。它可以进行告警去重、分组、路由以及静默等操作,帮助我们更智能地管理告警信息。

image
如何利用 Alertmanager 实现告警
为了实现 CPU 和内存的监控告警,我们需要在 Prometheus 中定义相应的告警规则。这些规则会基于预设的阈值来判断何时触发告警。例如,我们可以设置当 CPU 使用率超过 80%或内存使用超过 70%时发出告警。告警规则的配置非常灵活,可以根据实际需求进行调整。
具体实施步骤如下:
- 部署 Prometheus 和节点导出器。确保 Prometheus 可以抓取到 CPU 和内存的监控数据。
- 在 Prometheus 中配置告警规则,为 CPU 和内存使用设置合理的阈值。
- 部署 Alertmanager,并将其与 Prometheus 集成。
- 配置 Alertmanager 的规则,定义告警的通知方式,如邮件、Slack 或其他即时通讯工具。
- 测试告警机制,确保在资源使用超过阈值时能够收到告警。 alert.rules
yaml
groups:
- name: server-status
rules:
- alert: HighMemoryUsage
expr: (100 - ((node_memory_MemFree_bytes+node_memory_Cached_bytes+node_memory_Buffers_bytes) / node_memory_MemTotal_bytes * 100))>80
for: 1m
labels:
severity: critical
annotations:
summary: 服务器内存告警
description: 服务器内存利用率超过80%
alertmanager.yml
ruby
global:
resolve_timeout: 5m
smtp_smarthost: 'smtp.qq.com:465'
smtp_from: '[email protected]' # 发送告警的邮箱
smtp_auth_username: '[email protected]' #发送告警的邮箱
smtp_auth_password: 'aaaaa' #邮箱授权密码
smtp_require_tls: false
route:
group_by: ['alertname']
group_wait: 10s # 告警等待时间。告警产生后等待10s,如果有同组告警一起发出
group_interval: 5m # 两组告警的间隔时间
repeat_interval: 5m #重复告警的间隔时间,减少相同右键的发送频率 此处为测试设置为5m
receiver: 'email-notifications' # 默认接收者 routes: # 指定那些组可以接收消息
templates:
- '/tmp/prom/alertmanager/template/email.tmpl'
receivers:
- name: 'email-notifications'
email_configs:
- to: '[email protected]'
send_resolved: true
headers: { Subject: " 【监控告警】 {{ .CommonLabels.alertname }} " } #标题
html: '{{ template "email.to.html" .}}'
#from: '用户邮箱@sina.com'
#smarthost: 'smtp.sina.com:25'
#auth_username: '用户邮箱@sina.com'
#auth_password: '密码'
#require_tls: false
email.tmpl
less
{{ define "email.to.html" }}
{{- if gt (len .Alerts.Firing) 0 -}}
<h2>告警</h2>
<table border="5">
<tr><td>报警项</td>
<td>实例</td>
<td>报警详情</td>
<td>报警级别</td>
<td>开始时间</td>
</tr>
{{ range $i, $alert := .Alerts }}
<tr><td>{{ index $alert.Labels "alertname" }}</td>
<td style="color:#32CD32" >{{ index $alert.Labels "instance" }}</td>
<td>{{ index $alert.Annotations "description" }}</td>
<td>{{ $alert.Labels.severity }}</td>
<td style="color:#FF7F50">{{ $alert.StartsAt.Local.Format "2006-01-02 15:04:05" }}</td>
</tr>
{{ end }}
</table>
{{ end }}
{{- if gt (len .Alerts.Resolved) 0 -}}
<h2>已经恢复</h2>
<table border="5">
<tr><td>报警项</td>
<td>实例</td>
<td>报警详情</td>
<td>报警级别</td>
<td>开始时间</td>
<td>恢复时间</td>
</tr>
{{ range $i, $alert := .Alerts }}
<tr><td>{{ index $alert.Labels "alertname" }}</td>
<td style="color:#32CD32">{{ index $alert.Labels "instance" }}</td>
<td>{{ index $alert.Annotations "description" }}</td>
<td>{{ $alert.Labels.severity }}</td>
<td style="color:#FF7F50">{{ $alert.StartsAt.Local.Format "2006-01-02 15:04:05" }}</td>
<td style="color:#FF7F50">{{ $alert.EndsAt.Local.Format "2006-01-02 15:04:05" }}</td>
</tr>
{{ end }}
</table>
{{ end }}{{- end }}

QkdXBVQAQFBSXlhaBkhbQ1JeVAYGBwMNDwYCAQA3MDM0
通过以上步骤,我们就构建了一个简单的云原生监控告警系统,能够针对 CPU 和内存资源的使用情况进行实时监控,并在达到预设阈值时发出告警。这不仅有助于及时发现潜在的性能问题,还能够在一定程度上预防系统的不稳定和服务中断。
总结来说,云原生监控入门并不复杂,只要掌握了正确的工具和配置方法,就能够有效地实现资源的监控和告警。Prometheus 和 Alertmanager 作为云原生生态系统中的优秀工具,它们的结合使用,为我们提供了一种强大且灵活的监控解决方案。随着技术的不断进步,未来的监控系统将会更加智能化,但就目前而言,掌握 Prometheus 和 Alertmanager 的使用,已经足够我们构建一个稳定可靠的云原生监控告警系统。