运维监控及可视化工具
Prometheus 是一款强大的开源监控和告警工具,而 Grafana 是一个流行的数据可视化工具,两者结合可以构建完整的监控和可视化解决方案。以下是 Prometheus 的使用、进阶内容详解以及 Grafana 的使用指南。
一、Prometheus 使用详解
1. 核心概念
- 指标(Metric) :
- 时间序列数据,由指标名称和标签(Key-Value对)唯一标识。
- 示例:
http_requests_total{method="GET", status="200"}。
- 样本(Sample) :
- 时间序列数据的具体值,包含时间戳和数值。
- 示例:
http_requests_total{method="GET", status="200"} 1622548800 100。
2. 安装与配置
-
安装 Prometheus:
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz tar -xzf prometheus-2.30.3.linux-amd64.tar.gz cd prometheus-2.30.3.linux-amd64 ./prometheus --config.file=prometheus.yml -
配置文件(prometheus.yml):
global: scrape_interval: 15s # 采集间隔 scrape_configs: - job_name: 'prometheus' static_configs: - targets: ['localhost:9090']
3. 使用 Node Exporter 监控主机
-
安装 Node Exporter:
wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz tar -xzf node_exporter-1.2.2.linux-amd64.tar.gz cd node_exporter-1.2.2.linux-amd64 ./node_exporter -
配置 Prometheus 采集:
yaml
scrape_configs: - job_name: 'node' static_configs: - targets: ['localhost:9100']
4. 使用 PromQL 查询数据
-
基本查询:
promql
# 查询CPU使用率 100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[1m])) * 100) # 查询内存使用率 (node_memory_MemTotal_bytes - node_memory_MemFree_bytes) / node_memory_MemTotal_bytes * 100 -
聚合查询:
promql
# 按实例统计HTTP请求总数 sum(http_requests_total) by (instance) # 计算5分钟内请求速率 rate(http_requests_total[5m])
5. 配置告警规则
-
告警规则文件(alerts.yml):
yaml
groups: - name: example rules: - alert: HighCPUUsage expr: 100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[1m])) * 100) > 80 for: 5m labels: severity: critical annotations: summary: "High CPU usage on {{ $labels.instance }}" description: "CPU usage is above 80% for 5 minutes." -
配置 Prometheus 加载告警规则:
yaml
rule_files: - "alerts.yml"
6. 配置 Alertmanager
-
安装 Alertmanager:
wget https://github.com/prometheus/alertmanager/releases/download/v0.23.0/alertmanager-0.23.0.linux-amd64.tar.gz tar -xzf alertmanager-0.23.0.linux-amd64.tar.gz cd alertmanager-0.23.0.linux-amd64 ./alertmanager -
配置文件(alertmanager.yml):
route: receiver: 'email' receivers: - name: 'email' email_configs: - to: 'admin@example.com' from: 'alertmanager@example.com' smarthost: 'smtp.example.com:587' auth_username: 'user' auth_password: 'password'
二、Prometheus 进阶内容
1. 高可用部署
- 多实例部署 :
- 部署多个 Prometheus 实例,采集相同目标。
- 使用负载均衡器(如 HAProxy)分发查询请求。
- 远程存储 :
- 使用 Thanos 或 Cortex 实现长期存储和全局查询。
2. 长期存储
- Thanos :
- 提供全局查询、数据压缩和长期存储功能。
- 示例架构:
- Sidecar:与 Prometheus 实例集成,上传数据到对象存储。
- Query:提供统一的查询接口。
- Store Gateway:从对象存储读取数据。
- Cortex :
- 提供多租户支持和水平扩展能力。
3. 动态服务发现
-
Kubernetes 服务发现:
yaml
scrape_configs: - job_name: 'kubernetes' kubernetes_sd_configs: - role: pod relabel_configs: - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] action: keep regex: true -
Consul 服务发现:
yaml
scrape_configs: - job_name: 'consul' consul_sd_configs: - server: 'localhost:8500'
4. 自定义 Exporter
-
使用 Prometheus Client Library:
-
示例(Python):
from prometheus_client import start_http_server, Gauge import random import time # 定义指标 temperature = Gauge('temperature_celsius', 'Current temperature in Celsius') def collect_metrics(): while True: temperature.set(random.uniform(20, 30)) time.sleep(10) if __name__ == '__main__': start_http_server(8000) collect_metrics()
-
5. 性能优化
- 减少采集频率 :
- 调整
scrape_interval和evaluation_interval。
- 调整
- 优化 PromQL 查询 :
- 避免高基数标签(如用户ID)。
- 使用
rate()和irate()代替count()。
- 水平扩展 :
- 使用分片(Sharding)将采集任务分配到多个 Prometheus 实例。
三、Grafana 使用详解
1. 安装与配置
-
安装 Grafana:
bash
复制
wget https://dl.grafana.com/oss/release/grafana-8.1.5.linux-amd64.tar.gz tar -xzf grafana-8.1.5.linux-amd64.tar.gz cd grafana-8.1.5 ./bin/grafana-server -
访问 Grafana:
- 浏览器访问
http://localhost:3000,默认用户名和密码为admin/admin。
- 浏览器访问
2. 添加 Prometheus 数据源
- 登录 Grafana。
- 点击左侧菜单的 Configuration → Data Sources → Add data source。
- 选择 Prometheus ,填写 URL(如
http://localhost:9090)。 - 点击 Save & Test。
3. 创建仪表盘
- 点击左侧菜单的 Create → Dashboard。
- 点击 Add new panel。
- 在 Query 选项卡中,选择 Prometheus 数据源,输入 PromQL 查询(如
rate(http_requests_total[1m]))。 - 配置图表类型(如折线图、柱状图)。
- 点击 Apply 保存面板。
4. 使用模板变量
- 在仪表盘设置中,点击 Variables → Add variable。
- 配置变量(如
instance,查询label_values(node_cpu_seconds_total, instance))。 - 在面板查询中使用变量(如
rate(node_cpu_seconds_total{instance="$instance"}[1m]))。
5. 告警与通知
- 在面板设置中,点击 Alert → Create alert。
- 配置告警规则(如
WHEN avg() OF query(A, 1m, now) IS ABOVE 80)。 - 配置通知渠道(如 Email、Slack)。
四、Prometheus + Grafana 最佳实践
- 分层监控 :
- 基础设施层:使用 Node Exporter 监控主机。
- 中间件层:使用 MySQL Exporter、Redis Exporter 等。
- 应用层:自定义指标暴露。
- 统一告警 :
- 使用 Alertmanager 集中管理告警,Grafana 作为可视化补充。
- 长期存储 :
- 使用 Thanos 或 Cortex 存储历史数据,Grafana 查询展示。
五、推荐学习资源
- 官方文档 :
- 书籍 :
- 《Prometheus: Up & Running》:入门与实战指南。
- 《Monitoring with Prometheus》:深入讲解 Prometheus 原理与实践。
- 在线课程 :
- Udemy: "Prometheus and Grafana: The Complete Guide"
- Pluralsight: "Monitoring Systems with Prometheus"
通过以上内容,你可以全面掌握 Prometheus 和 Grafana 的使用方法,并构建高效的监控与可视化系统。
PromQL基础
PromQL(Prometheus Query Language)是 Prometheus 的核心查询语言,用于从时间序列数据库中提取和操作数据。以下是 PromQL 的详细使用指南,涵盖基本查询、聚合操作、函数使用及常见场景示例。
一、PromQL 基础
1. 数据模型
- 时间序列 :
- 由指标名称(Metric Name)和标签(Labels)唯一标识。
- 示例:
http_requests_total{method="GET", status="200"}。
- 样本 :
- 时间序列的具体值,包含时间戳和数值。
- 示例:
http_requests_total{method="GET", status="200"} 1622548800 100。
2. 数据类型
- 瞬时向量(Instant Vector) :
- 某一时刻的时间序列数据。
- 示例:
http_requests_total{method="GET"}。
- 范围向量(Range Vector) :
- 某一时间段内的时间序列数据。
- 示例:
http_requests_total{method="GET"}[5m]。
- 标量(Scalar) :
- 单个数值。
- 示例:
count(http_requests_total)。
二、基本查询
1. 查询瞬时向量
-
查询所有 HTTP 请求总数:
promql
复制
http_requests_total -
查询特定标签的 HTTP 请求:
promql
复制
http_requests_total{method="GET", status="200"}
2. 查询范围向量
-
查询过去 5 分钟的 HTTP 请求:
promql
复制
http_requests_total{method="GET"}[5m]
3. 使用函数
-
计算 HTTP 请求速率:
promql
复制
rate(http_requests_total{method="GET"}[1m]) -
计算 HTTP 请求增量:
promql
复制
increase(http_requests_total{method="GET"}[1h])
三、聚合操作
1. 按标签聚合
-
按方法统计 HTTP 请求总数:
promql
复制
sum(http_requests_total) by (method) -
按方法和状态统计 HTTP 请求总数:
promql
复制
sum(http_requests_total) by (method, status)
2. 全局聚合
-
统计所有 HTTP 请求总数:
promql
复制
sum(http_requests_total) -
统计 HTTP 请求的平均值:
promql
复制
avg(http_requests_total)
3. 分位数
-
计算 HTTP 请求延迟的 95 分位数:
promql
复制
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
四、常见场景示例
1. 监控 CPU 使用率
-
计算 CPU 使用率:
promql
复制
100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[1m])) * 100)
2. 监控内存使用率
-
计算内存使用率:
promql
复制
(node_memory_MemTotal_bytes - node_memory_MemFree_bytes) / node_memory_MemTotal_bytes * 100
3. 监控磁盘 I/O
-
计算磁盘读写速率:
promql
复制
rate(node_disk_read_bytes_total[1m]) rate(node_disk_written_bytes_total[1m])
4. 监控网络流量
-
计算网络接收/发送速率:
promql
复制
rate(node_network_receive_bytes_total[1m]) rate(node_network_transmit_bytes_total[1m])
五、高级查询
1. 子查询
-
计算过去 5 分钟内 HTTP 请求的 1 分钟速率:
promql
复制
rate(http_requests_total[1m])[5m:]
2. 预测磁盘填满时间
-
使用
predict_linear预测磁盘填满时间:promql
复制
predict_linear(node_filesystem_free_bytes{mountpoint="/"}[1h], 3600*24)
3. 多指标计算
-
计算请求成功率:
promql
复制
sum(rate(http_requests_total{status=~"2.."}[1m])) / sum(rate(http_requests_total[1m])) * 100
六、调试与优化
1. 调试查询
- 使用 Prometheus Web UI 的 Graph 或 Console 页面测试查询。
- 使用
explain命令查看查询执行计划(需启用--enable-feature=promql-experimental)。
2. 优化查询
- 避免高基数标签 :
- 高基数标签(如用户ID)会导致查询性能下降。
- 示例:
http_requests_total{user_id="12345"}。
- 使用范围向量函数 :
- 如
rate()和irate(),避免直接查询原始数据。
- 如
七、推荐学习资源
- 官方文档 :
- 书籍 :
- 《Prometheus: Up & Running》:入门与实战指南。
- 《Monitoring with Prometheus》:深入讲解 Prometheus 原理与实践。
- 在线课程 :
- Udemy: "Prometheus and Grafana: The Complete Guide"
- Pluralsight: "Monitoring Systems with Prometheus"
通过以上内容,你可以全面掌握 PromQL 的使用方法,并应用于实际监控场景中