4. Prometheus 监控体系基础:架构、指标模型与数据采集模式
在 Operator 控制器指标与告警对接之前,必须理解 Prometheus 监控体系的核心设计。本章从架构、指标模型、Pull 与 Push 模式三个维度建立基础,为后续 Operator 指标暴露与告警规则编写提供理论支撑。
4.1 Prometheus 整体架构
Prometheus 采用拉取(Pull)为主、推送(Push)为辅的监控数据采集模型。其核心组件包括:
- Prometheus Server:负责指标抓取、存储与查询。
- Exporters:将非原生 Prometheus 格式的指标转换为 Prometheus 可抓取的格式。
- Pushgateway:允许短期任务或无法直接拉取的组件主动推送指标。
- Alertmanager:处理告警去重、分组、静默与通知路由。
- Service Discovery:动态发现目标端点(如 Kubernetes Pod、Service)。
关键理解: Operator 控制器本身就是一个 Exporter,通过
/metrics 端点暴露自身状态指标,Prometheus Server 通过 ServiceMonitor 或 PodMonitor 自动发现并拉取。
4.2 指标模型
Prometheus 所有指标数据都遵循统一的时间序列模型,每个序列由 指标名称 和一组 标签(Label) 唯一标识。
4.2.1 指标格式
<metric_name>{<label_name>="<label_value>", ...} <value> [<timestamp>]
示例:
http_requests_total{method="GET", endpoint="/api/v1", status="200"} 1024 1700000000
4.2.2 指标类型
| 类型 | 说明 | 典型场景 | Operator 示例 |
|---|---|---|---|
| Counter | 只增不减的计数器 | 请求总数、错误总数 | reconcile_total |
| Gauge | 可增可减的瞬时值 | 当前连接数、内存使用量 | reconcile_duration_seconds |
| Histogram | 分桶统计,记录分布 | 请求延迟分布 | reconcile_duration_seconds_bucket |
| Summary | 分位数统计 | 请求延迟 p99 | reconcile_duration_seconds_summary |
最佳实践: Operator 控制器指标命名建议遵循
<namespace>_<subsystem>_<name> 格式,例如 operator_reconcile_total。标签用于区分不同维度(如资源类型、命名空间、状态),避免在指标名称中编码维度信息。
4.3 Pull 模式:Prometheus 默认采集方式
Pull 模式是 Prometheus 的核心设计理念:Prometheus Server 主动向目标端点发起 HTTP GET 请求,获取 /metrics 端点上的指标数据。
4.3.1 Pull 模式工作流程
- 服务发现:Prometheus 通过 Kubernetes API 发现 ServiceMonitor 或 PodMonitor 定义的目标。
- 目标列表生成:根据发现规则生成待抓取的目标端点列表(IP:Port)。
- HTTP 抓取:Prometheus Server 按配置间隔(默认 15s)向每个目标发起
GET /metrics请求。 - 数据解析与存储:解析返回的文本格式指标,按时间序列写入本地存储。
4.3.2 Pull 模式优势
- 健康检查自然集成:抓取失败即表明目标不可用。
- 避免推送风暴:由 Prometheus 控制抓取节奏,不会因目标端突发推送导致过载。
- 安全性:目标端无需开放入站端口以外的网络权限。
4.4 Pushgateway:补充模式
Pushgateway 用于无法直接拉取的场景,例如:
- 短期批处理任务(CronJob)
- 防火墙后的内部组件
- 生命周期极短的 Pod
4.4.1 Push 模式工作流程
- 任务执行完毕后,主动向 Pushgateway 的
/metrics/job/<job_name>推送指标。 - Pushgateway 缓存这些指标,等待 Prometheus Server 拉取。
- Prometheus Server 将 Pushgateway 视为普通目标,定期拉取其缓存的指标。
注意: Pushgateway 不是 Prometheus 的默认模式,滥用会导致指标过期、标签混乱、单点故障。Operator 控制器应优先使用 Pull 模式暴露指标,仅在批处理或无法持久化运行的任务中使用 Pushgateway。
4.5 Pull 与 Push 模式对比
| 维度 | Pull 模式 | Push 模式(Pushgateway) |
|---|---|---|
| 数据流向 | Server → Target | Target → Pushgateway → Server |
| 适用场景 | 长期运行的服务、Operator | 短期任务、批处理 |
| 健康检查 | 抓取失败即表示异常 | 无法直接判断目标状态 |
| 指标时效性 | 实时拉取 | 存在缓存延迟 |
| 扩展性 | 水平扩展良好 | Pushgateway 可能成为瓶颈 |
| Operator 推荐 | 首选 | 仅用于辅助场景 |
4.6 本章小结
- Prometheus 采用 Pull 为主、Push 为辅 的采集模型,Operator 控制器应优先通过
/metrics端点暴露指标。 - 指标模型由 指标名称 + 标签 + 值 + 时间戳 构成,支持 Counter、Gauge、Histogram、Summary 四种类型。
- Pull 模式通过服务发现自动抓取,天然集成健康检查;Pushgateway 作为补充,用于短期任务场景。
- 理解这些基础概念是后续编写 Operator 指标暴露代码、配置 ServiceMonitor 和告警规则的前提。