Prometheus & Grafana 第 7 小时:深度排错、优化与高级主题

从“告警响了 / 面板空了”出发,沿着指标信号的完整链路定位根因:目标为什么 down、序列为什么爆炸、查询为什么慢、TSDB 为什么吃光内存和磁盘、告警为什么不响或响个不停、Grafana 为什么显示 No data
Prometheus v3.16.0Alertmanager v0.35.0Grafana v13.3.1kube-prometheus-stack 93.3.0按源码核实 2026-11-15
整体学习目标
  • 用 八段链路模型(L1 暴露 → L2 发现 → L3 目标 relabel → L4 抓取 → L5 解析与限制 → L6 存储 → L7 查询与规则 → L8 通知与呈现)把任何一个监控故障定位到具体一段,并知道每段的“观察窗口”(页面、API、自监控指标、命令)。
  • 读懂 Target health 页面上的真实 lastError:connect: connection refused、context deadline exceeded、server returned HTTP status 403 Forbidden、Prometheus 3 新增的 received unsupported Content-Type … and no fallback_scrape_protocol specified for target、sample limit exceeded、label_limit exceeded (…);区分“目标 down”与“目标根本不存在”。
  • 诊断基数爆炸:TSDB Status 页面 / /api/v1/status/tsdb、topk(10, count by (__name__)({__name__=~".+"}))、promtool tsdb analyze;用 sample_limit、label_limit、metric_relabel_configs 与 Operator 的 enforcedSampleLimit 设置护栏。
  • 优化慢 PromQL 与仪表盘:理解“加载样本数 = 序列数 × 每序列样本数”,读懂 query processing would load too many samples into memory 与 query timed out in …,用 recording rule、$__rate_interval、Max data points、缩小选择器解决。
  • 解释 TSDB 内部:head block(内存,默认 2 小时块)、WAL(128 MiB 段、checkpoint)、m-map 的 head chunks、压缩(2h → 6h → 18h…,上限为保留期的 10% 且不超过 31 天)、保留与磁盘;能从日志和指标判断 WAL 回放慢、压缩失败、磁盘写满。
  • 排查告警不触发(规则未加载、for 未满足、表达式无数据、absent() 缺失、Alertmanager 路由/抑制/静默)与告警风暴(分组、group_interval、抑制规则、flapping 与 keep_firing_for)。
  • 排查 Grafana:数据源连通性、Query inspector、$__rate_interval 与 step、模板变量、sidecar 预配、权限与 “Datasource … was not found”。

1 小时时间分配表

#时间模块核心内容动画 / 交互实验(kind 集群 lab + kps,命名空间 faultlab)
0课前准备:故障注入环境部署可控的 faultexp exporter(延迟、Content-Type、序列数、churn、错误率都可用环境变量开关)+ ServiceMonitor + PrometheusRule环境自检清单基线:up{job="faultexp"} == 1
100–06排错方法论:从告警到根因八段链路模型、每段的观察窗口、自监控指标、“先止血再根因”告警 → 链路段定位器同一个告警,三种完全不同的根因
206–13抓取失败:目标 down、超时与服务发现lastError 解读、scrape timeout、Content-Type 回退、ServiceMonitor 选择、relabel 调试、targets/relabel_steps抓取流水线故障模拟器注入 connection refused / 超时 / Content-Type / 选择器不匹配
313–21基数爆炸:标签设计与限制序列 = 标签值组合、TSDB Status、topk(count by (__name__))、churn、sample_limit、label 限制、metric_relabel 丢弃核心动画:基数爆炸对内存与查询的影响user_id 标签爆炸 → sample limit exceeded → 修复
421–28查询性能:慢 PromQL 与仪表盘优化样本加载模型、--query.max-samples、--query.timeout、11,000 点限制、recording rules、查询统计、仪表盘反模式查询成本计算器同一面板优化前后对比
528–35TSDB 内部:head block、WAL、压缩与磁盘head、WAL 段与 checkpoint、m-map chunks、2h 块、压缩层级、保留(时间 / 大小 / 百分比)、乱序样本、磁盘写满核心动画:TSDB head / WAL / compaction强杀 Pod 观察 WAL 回放;读块列表与日志
635–42告警不触发或告警风暴规则未加载、窗口过小、for、absent()、规则评估失败、Alertmanager 分组/抑制/静默、风暴治理告警链路逐段检查器 + 分组计算器写一条“永远不响”的告警并修复;amtool 路由测试
742–50Grafana 排错:数据源、面板与权限请求路径(浏览器 → Grafana 后端 → Prometheus)、Query inspector、step 与 $__rate_interval、变量、sidecar 预配、权限面板请求路径追踪器坏数据源 + 坏变量 + 错 step,逐个修复
850–60综合故障盲盒8 种故障随机注入,只看现象诊断浏览器内故障盲盒 + 交互排障树fault-box.sh random
—课后速查表 · 综合实验8 种故障逐一诊断 + 输出一份监控系统“自监控与护栏”清单结业测验(12 题)综合实验

知识覆盖矩阵 Knowledge Coverage Matrix

目标技能M1M2M3M4M5M6M7M8关键命令 / 页面实验
八段链路定位✓✓✓✓✓✓✓✓up、/targets、/rulesM1 三种根因
抓取与服务发现✓✓···✓·✓/api/v1/targets、relabel_steps、Operator 事件四种抓取故障
基数与 churn··✓✓✓··✓/api/v1/status/tsdb、promtool tsdb analyzeuser_id 爆炸
限制与护栏·✓✓✓···✓sampleLimit、labelLimit、--query.max-samplessample limit
查询与仪表盘性能··✓✓··✓·stats=all、recording rule、$__rate_interval面板优化
TSDB 内部与磁盘··✓·✓··✓promtool tsdb list -r、/status/tsdb/blocksWAL 回放
告警链路✓····✓·✓amtool config routes test、ALERTS永远不响的告警
Grafana 排错✓··✓··✓✓Query inspector、sidecar 日志坏数据源

本课不覆盖的内容(以及在哪里学)

主题为什么不在本课去哪里学
Prometheus 架构、指标类型、PromQL 基础、Grafana 入门基础内容第 1 课
recording/alerting rule 编写、Alertmanager 路由语法、存储规划本课只讲它们出故障时怎么办第 2 课
Azure / AWS 托管 Prometheus 与 Grafana 的排错托管服务的身份与配额问题第 3 课、第 4 课
kube-prometheus-stack 安装、ServiceMonitor/PrometheusRule 编写本课在其之上注入故障第 5 课
Thanos / Mimir、remote_write 调优、SLO 与 burn rate架构层主题第 6 课
Pod 层面的排错(CrashLoopBackOff、OOMKilled 的 Kubernetes 机制)属于 Kubernetes 本身Kubernetes 课
日志与追踪:Loki、Tempo 与 OpenTelemetry第 8 课第 8 课
生产问题 50 例、面试题 50 道第 9 课(可选)第 9 课

如何使用本课件

每个模块的 10 个分页
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。本课实验都在 kind 集群 lab 上进行:kps 在 monitoring,故障注入目标在 faultlab。每个实验都是“注入 → 观察 → 诊断 → 修复 → 复位”。
学习进度
测验得分 ≥ 70% 或点击“标记本模块完成”即计入进度,保存在本浏览器中(禁用本地存储时刷新后清空)。
中文语音
“语音”分页用浏览器 Web Speech API(zh-CN)朗读讲解稿;英文术语用 en-US 发音。没有中文语音包时讲解稿仍可阅读。
版本说明本课以 Prometheus v3.16.0(2026-11-05)为基线,报错原文、参数默认值与指标名对照 v3.16.0 源码(scrape/、model/textparse/、promql/engine.go、tsdb/、web/api/v1/api.go、cmd/prometheus/main.go、cmd/promtool/)核实;Kubernetes 侧使用 kube-prometheus-stack 93.3.0(Prometheus Operator v0.95.2,Prometheus 镜像 v3.16.0-distroless,Alertmanager v0.35.0,Grafana 子 chart 14.4.1 → Grafana 13.3.1)。注意:本课按 2026-11 官方当前主线 Grafana 13.x 编写,12.x 中同名功能的位置可能略有不同。示例输出中的 IP、时间、ULID、数量都是示例值。

模块 0 · 准备:故障注入环境

在第 5 课的 kind 集群 lab + kube-prometheus-stack(release kps)上部署一个“可以被随意搞坏”的 exporter:faultexp。所有故障都通过环境变量或标签开关注入,随时可以复位
课前 ≈ 10 分钟kind · kps 93.3.0本地实验,零费用
前提条件
  • 已完成第 5 课:kind 集群 lab,helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring 已部署,myapp 运行在命名空间 myapp。本课不在 myapp 上注入故障,而是新建命名空间 faultlab,以免破坏前几课的成果。
  • 本机:kubectl、helm、jq、curl;Docker Desktop / Docker Engine 给 kind 至少 4 CPU / 6 GiB 内存(基数实验会让 Prometheus 内存上升几百 MiB)。
  • 没有 kind 也能学大部分内容:第 1、2 课的 Docker Compose 环境 ~/promlab(服务 prometheus:9090、alertmanager:9093、grafana:3000、myapp:5000…)可以完成模块 3–5 的查询、TSDB 与 promtool 实验,命令里的 kubectl exec … -c prometheus -- 换成 docker compose exec prometheus 即可(各模块会单独标注差异)。

步骤 1:检查集群与 kps

kubectl config use-context kind-lab
helm -n monitoring list
kubectl -n monitoring get prometheus,alertmanager
kubectl -n monitoring get pods -l 'app.kubernetes.io/name in (prometheus,alertmanager,grafana)'
Switched to context "kind-lab".
NAME  NAMESPACE   REVISION  UPDATED   STATUS    CHART                          APP VERSION
kps   monitoring  3         ...       deployed  kube-prometheus-stack-93.3.0   v0.95.2
NAME                                                    VERSION   DESIRED   READY   RECONCILED   AVAILABLE   AGE
prometheus.monitoring.coreos.com/kps-kube-prometheus-stack-prometheus   v3.16.0   1   1   True   True   2d
NAME                                                        VERSION   REPLICAS   READY   RECONCILED   AVAILABLE   AGE
alertmanager.monitoring.coreos.com/kps-kube-prometheus-stack-alertmanager   v0.35.0   1   1   True   True   2d
NAME                                                     READY   STATUS    RESTARTS   AGE
alertmanager-kps-kube-prometheus-stack-alertmanager-0    2/2     Running   0          2d
kps-grafana-6d9f8c7b9d-x2lq7                             3/3     Running   0          2d
prometheus-kps-kube-prometheus-stack-prometheus-0        2/2     Running   0          2d

资源名由 kps 的 fullname 推出:release kps + chart kube-prometheus-stack → kps-kube-prometheus-stack。不同版本或自定义 fullnameOverride 时名字会不同,下面的变量都用标签查询得到,不要硬编码。

步骤 2:设置本课通用变量(每个新终端执行一次)

mkdir -p ~/promlab/faultlab
cat > ~/promlab/faultlab/env.sh <<'EOF'
export NS=monitoring FNS=faultlab
export PROM_POD=$(kubectl -n $NS get pod -l app.kubernetes.io/name=prometheus -o jsonpath='{.items[0].metadata.name}')
export AM_POD=$(kubectl -n $NS get pod -l app.kubernetes.io/name=alertmanager -o jsonpath='{.items[0].metadata.name}')
export PROM_CR=$(kubectl -n $NS get prometheus -o jsonpath='{.items[0].metadata.name}')
export P=http://localhost:9090 AM=http://localhost:9093 G=http://localhost:3000
# 便捷函数:即时查询,返回 JSON
pq() { curl -s --data-urlencode "query=$1" "$P/api/v1/query" | jq -c '.data.result[] | [.metric, .value[1]]'; }
EOF
source ~/promlab/faultlab/env.sh && echo "$PROM_POD / $AM_POD / $PROM_CR"
prometheus-kps-kube-prometheus-stack-prometheus-0 / alertmanager-kps-kube-prometheus-stack-alertmanager-0 / kps-kube-prometheus-stack-prometheus

步骤 3:端口转发(Prometheus 9090、Alertmanager 9093、Grafana 3000)

cat > ~/promlab/faultlab/pf.sh <<'EOF'
#!/usr/bin/env bash
# 后台端口转发;./pf.sh stop 结束
pkill -f 'port-forward.*(prometheus-operated|alertmanager-operated|kps-grafana)' 2>/dev/null
[ "${1:-}" = stop ] && exit 0
kubectl -n monitoring port-forward svc/prometheus-operated 9090:9090 >/dev/null 2>&1 &
kubectl -n monitoring port-forward svc/alertmanager-operated 9093:9093 >/dev/null 2>&1 &
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 >/dev/null 2>&1 &
sleep 2; curl -s localhost:9090/-/ready; curl -s localhost:9093/-/ready; echo; curl -s localhost:3000/api/health
EOF
chmod +x ~/promlab/faultlab/pf.sh && ~/promlab/faultlab/pf.sh
# Grafana admin 密码(kps 未设置 adminPassword 时由 chart 随机生成)
kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d; echo
Prometheus Server is Ready.
OK
{
  "database": "ok",
  "version": "13.3.1",
  ...
}
Xq3...(随机密码)

prometheus-operated 与 alertmanager-operated 是 Operator 自动创建的 headless Service,名字固定,比 kps 的 Service 名更稳定。

步骤 4:部署 faultexp(可控故障的 exporter)

faultexp 是一个 40 行的 Python 标准库 HTTP 服务(不需要 pip 安装任何包),它暴露 /metrics,并通过环境变量模拟真实世界的各种“坏 exporter”:

环境变量默认作用(模拟的故障)
DELAY0每次 /metrics 响应前睡眠秒数 → 抓取超时
CTtext/plain; version=0.0.4; charset=utf-8响应的 Content-Type → Prometheus 3 的 Content-Type 严格校验
SERIES0额外输出多少条带 user_id 标签的序列 → 基数爆炸 / sample limit
CHURN01 = session 标签值每 30 秒换一批 → 序列 churn
ERRORS01 = 每秒产生约 2 个 5xx(正常请求约 5/s)→ 错误率告警
apiVersion: v1
kind: Namespace
metadata:
  name: faultlab
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: faultexp-code
  namespace: faultlab
data:
  server.py: |
    import os, time
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    START = time.time()

    def body():
        e = os.environ.get
        up = time.time() - START
        series, churn, errors = int(e("SERIES", "0")), e("CHURN", "0") == "1", e("ERRORS", "0") == "1"
        out = ["# HELP faultexp_up Always 1.", "# TYPE faultexp_up gauge", "faultexp_up 1",
               "# HELP faultexp_http_requests_total HTTP requests.", "# TYPE faultexp_http_requests_total counter",
               'faultexp_http_requests_total{route="/api/orders",status="200"} %d' % int(up * 5),
               'faultexp_http_requests_total{route="/api/orders",status="500"} %d' % (int(up * 2) if errors else 0)]
        if series:
            win = int(time.time() // 30)
            out += ["# HELP faultexp_user_requests_total Requests per user (anti-pattern).",
                    "# TYPE faultexp_user_requests_total counter"]
            for i in range(series):
                sid = "%d-%d" % (win, i) if churn else "s%d" % i
                out.append('faultexp_user_requests_total{user_id="u%d",session="%s"} 1' % (i, sid))
        return ("\n".join(out) + "\n").encode()

    class H(BaseHTTPRequestHandler):
        def send(self, code, data, ct):
            self.send_response(code)
            if ct:
                self.send_header("Content-Type", ct)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            try:
                self.wfile.write(data)
            except BrokenPipeError:
                pass
        def do_GET(self):
            p = self.path.split("?")[0]
            if p == "/healthz":
                return self.send(200, b"ok\n", "text/plain")
            if p != "/metrics":
                return self.send(404, b"not found\n", "text/plain")
            time.sleep(float(os.environ.get("DELAY", "0")))
            self.send(200, body(), os.environ.get("CT", "text/plain; version=0.0.4; charset=utf-8"))
        def log_message(self, *a):
            pass

    ThreadingHTTPServer(("", 8080), H).serve_forever()
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: faultexp
  namespace: faultlab
  labels: {app: faultexp}
spec:
  replicas: 1
  selector:
    matchLabels: {app: faultexp}
  template:
    metadata:
      labels: {app: faultexp}
    spec:
      containers:
        - name: faultexp
          image: python:3.13-alpine
          command: ["python", "-u", "/app/server.py"]
          ports:
            - {name: http, containerPort: 8080}
          readinessProbe:
            httpGet: {path: /healthz, port: http}
          resources:
            requests: {cpu: 20m, memory: 32Mi}
            limits: {memory: 256Mi}
          volumeMounts:
            - {name: code, mountPath: /app}
      volumes:
        - name: code
          configMap: {name: faultexp-code}
---
apiVersion: v1
kind: Service
metadata:
  name: faultexp
  namespace: faultlab
  labels: {app: faultexp}
spec:
  selector: {app: faultexp}
  ports:
    - {name: http, port: 8080, targetPort: http}
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: faultexp
  namespace: faultlab
  labels:
    release: kps                 # kps 默认只选择带这个标签的 ServiceMonitor
spec:
  selector:
    matchLabels: {app: faultexp}
  endpoints:
    - port: http                 # Service 端口的“名字”,不是数字
      path: /metrics
      interval: 15s
      scrapeTimeout: 10s
  sampleLimit: 5000              # 护栏:单次抓取超过 5000 个样本则整次抓取失败
  labelLimit: 20
  labelValueLengthLimit: 200
---
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: faultexp-rules
  namespace: faultlab
  labels:
    release: kps                 # kps 默认的 ruleSelector
spec:
  groups:
    - name: faultexp.rules
      rules:
        - record: job:faultexp_http_requests:rate5m
          expr: sum by (job, status) (rate(faultexp_http_requests_total[5m]))
        - alert: FaultexpDown
          expr: up{job="faultexp"} == 0
          for: 1m
          labels: {severity: warning}
          annotations:
            summary: "faultexp 抓取失败({{ $labels.instance }})"
        - alert: FaultexpAbsent
          expr: absent(up{job="faultexp"})
          for: 2m
          labels: {severity: warning}
          annotations:
            summary: "Prometheus 中找不到 job=faultexp 的任何目标"
        - alert: FaultexpHighErrorRate
          expr: |
            sum(rate(faultexp_http_requests_total{status=~"5.."}[2m]))
              / sum(rate(faultexp_http_requests_total[2m])) > 0.1
          for: 2m
          labels: {severity: critical}
          annotations:
            summary: "faultexp 5xx 比例 {{ $value | humanizePercentage }}"
source ~/promlab/faultlab/env.sh
kubectl apply -f ~/promlab/faultlab/faultexp.yaml
kubectl -n faultlab rollout status deploy/faultexp --timeout=120s
kubectl -n faultlab run curl --rm -i --restart=Never --image=curlimages/curl:8.11.1 -- \
  -si http://faultexp.faultlab:8080/metrics | head -12
namespace/faultlab created
configmap/faultexp-code created
deployment.apps/faultexp created
service/faultexp created
servicemonitor.monitoring.coreos.com/faultexp created
prometheusrule.monitoring.coreos.com/faultexp-rules created
deployment "faultexp" successfully rolled out
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.13.x
Date: Mon, 16 Nov 2026 01:02:03 GMT
Content-Type: text/plain; version=0.0.4; charset=utf-8
Content-Length: 316

# HELP faultexp_up Always 1.
# TYPE faultexp_up gauge
faultexp_up 1
...

curl 镜像标签请换成你所在环境可拉取的版本;任何带 curl 的镜像都可以。Operator 通常在 30–60 秒内把新的 ServiceMonitor 写进配置,config-reloader 再触发 Prometheus 重新加载。

步骤 5:确认基线(约 1 分钟后)

pq 'up{job="faultexp"}'
pq 'scrape_samples_scraped{job="faultexp"}'
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[] | select(.name=="faultexp.rules") | .rules[] | "\(.name) \(.health) \(.state)"'
[{"__name__":"up","container":"faultexp","endpoint":"http","instance":"10.244.0.37:8080","job":"faultexp","namespace":"faultlab","pod":"faultexp-7c9d5b6f4-kq2mz","service":"faultexp"},"1"]
[{"__name__":"scrape_samples_scraped",...,"job":"faultexp",...},"3"]
FaultexpDown ok inactive
FaultexpAbsent ok inactive
FaultexpHighErrorRate ok inactive

热身:凭记忆回答(30 秒)

up == 0 与 up 序列不存在,有什么区别?

up == 0:Prometheus 知道这个目标并尝试抓取,但失败了(L4/L5)。序列不存在:Prometheus 根本没有这个目标(L2 服务发现或 L3 relabel 把它丢了,或者 ServiceMonitor 没被选中)。前者能触发 up == 0 告警,后者只能靠 absent()。这是本课最重要的一个区分。

Prometheus 的“一个样本”和“一条序列”是什么关系?

序列(series)由指标名 + 一组标签唯一确定;样本(sample)是某条序列在某个时间点的一个值。内存主要随活跃序列数增长,磁盘主要随样本数增长,查询成本随“选中的序列数 × 每条序列的样本数”增长。

环境自检清单

模块 1 · 排错方法论:从告警到根因

00:00 – 06:00 · 告警只是症状。先问“监控系统自己可信吗”,再把问题定位到信号链路的某一段,最后才动手修
6 分钟八段链路模型★★★★★
学习目标
  • 说出指标信号的八段链路:L1 暴露 → L2 发现 → L3 目标 relabel → L4 抓取 → L5 解析与限制 → L6 存储 → L7 查询与规则 → L8 通知与呈现。
  • 对每一段说出至少一个“观察窗口”:页面(/targets、/service-discovery、/tsdb-status、/rules、/alerts)、API、自监控指标或命令。
  • 按“可信度 → 定段 → 取证 → 止血 → 根因与预防”五步处理一条告警,区分业务故障、监控系统故障与观测误差。
前置知识:第 1 课抓取周期动画、第 2 课告警生命周期。重要程度:★★★★★

What:八段链路模型

段发生了什么(Prometheus 3.16 组件)典型现象 / 报错首选观察窗口
L1 暴露应用 / exporter 在 HTTP 端点上输出文本或 protobuf 格式的指标端点 404、500、响应极慢、Content-Type 不规范、指标名不合法curl -si http://目标/metrics | head
L2 发现服务发现(kubernetes_sd endpoints / endpointslice 角色)产生候选目标;在 kps 中先由 Operator 按 serviceMonitorSelector 选择 ServiceMonitor 再生成配置目标根本不出现;up 序列不存在/service-discovery、Operator 事件、配置 Secret prometheus-<CR 名>
L3 目标 relabelrelabel_configs(Operator 中的 relabelings)决定保留/丢弃目标、生成 job/instance 等标签目标在 “Dropped targets” 中;标签不符合预期/api/v1/targets?state=dropped、/api/v1/targets/relabel_steps
L4 抓取HTTP GET(带 Accept 协商)、超时 scrape_timeout、TLS / 认证、body 大小限制up == 0;lastError 为 connection refused、context deadline exceeded、server returned HTTP status 401 Unauthorized、body size limit exceeded/targets、scrape_duration_seconds
L5 解析与限制按 Content-Type 选择解析器;metric_relabel_configs;sample_limit、label_limit 等up == 0 且 lastError 为 sample limit exceeded、label_limit exceeded (…)、received unsupported Content-Type …scrape_samples_scraped vs scrape_samples_post_metric_relabeling、prometheus_target_scrapes_exceeded_sample_limit_total
L6 存储写入 head block 与 WAL;后台压缩成 2h 块;保留与删除内存飙升 / OOMKilled、启动时 WAL 回放很久、磁盘写满、乱序样本被丢弃/tsdb-status、prometheus_tsdb_head_series、prometheus_tsdb_compactions_failed_total
L7 查询与规则PromQL 引擎执行即时 / 范围查询;规则组按 evaluation_interval 评估查询超时、query processing would load too many samples into memory、规则 health = err、规则组评估超时(missed iterations)/rules、prometheus_rule_evaluation_failures_total、prometheus_rule_group_iterations_missed_total
L8 通知与呈现告警发给 Alertmanager(分组、抑制、静默、路由、接收器);Grafana 后端代理查询并渲染面板告警 firing 但没收到通知;通知风暴;面板 No data 但 Prometheus 有数据/alerts、amtool、prometheus_notifications_dropped_total、Grafana Query inspector

Why:为什么要先问“监控系统可信吗”

同一条 “FaultexpDown” 告警,可能是业务真的挂了(应用崩溃),也可能是监控系统自己出了问题(Prometheus 抓取超时、ServiceMonitor 被改)。如果直接按“业务故障”处理——重启应用、回滚版本——不但无效,还会制造新的变更。相反,如果监控系统坏掉,最危险的不是误报而是沉默:目标从发现中消失时 up == 0 永远不会成立,告警“全绿”。所以生产中必须有元监控(meta-monitoring):kps 默认的 Watchdog 告警永远处于 firing,用来做“死人开关”(dead man's switch)——外部系统收不到它就说明告警链路断了。

How:五步法

  1. 可信度:Prometheus 自己健康吗?up{job=~".*prometheus.*"}、/-/ready、Watchdog 是否还在发送、规则组是否按时评估(prometheus_rule_group_last_evaluation_timestamp_seconds)。
  2. 定段:现象落在 L1–L8 哪一段?关键问题:序列存在吗?值是 0 还是缺失?lastError 写的什么?
  3. 取证:只用只读手段——页面、API、自监控指标、日志——保存证据(截图 / JSON),再改任何东西。
  4. 止血:业务故障按业务流程处理;监控故障先恢复可见性(例如临时调高 scrapeTimeout、静默噪声告警并写明原因与到期时间)。
  5. 根因与预防:每次复盘至少落地一条护栏(limit、告警、CI 校验、文档)。

When:何时怀疑“观测误差”

数据存在但“看起来不对”时:rate() 的外推使结果带小数、范围窗口小于两个抓取间隔导致空结果、5 分钟 lookback(--query.lookback-delta 默认 5m)让已经消失的目标在图上“多活”几分钟、Grafana 的 step 太大把尖峰平均掉、counter 重置被误读。这些都不是故障,而是对查询语义的误解。

三类问题对比

业务故障监控系统故障观测误差
例子myapp 返回 500抓取超时、ServiceMonitor 未被选中、TSDB OOM窗口过小、step 太大、lookback 残影
up通常为 1(应用还能输出指标)0 或不存在1
谁处理应用团队平台 / 监控团队写查询的人
第一观察窗口业务指标与日志/targets、自监控指标Query inspector、PromQL 语义
常见误解① “up == 0 告警能覆盖目标消失”——不能,目标消失时序列不存在,需要 absent() 或按 job 统计目标数。② “Prometheus 页面能打开就说明监控正常”——规则组可能在漏评估、抓取可能在超时、通知队列可能在丢弃。③ “重启 Prometheus 能解决大部分问题”——重启会触发 WAL 回放(大实例可能十几分钟没有数据),而且会清掉现场证据。④ “告警没响就是 Alertmanager 的问题”——更常见的是规则根本没加载或表达式返回空。

八段链路与观察窗口

L1 暴露/metrics L2 发现SD · Operator L3 relabelkeep / drop L4 抓取HTTP · 超时 L5 解析限制limit · CT L6 存储head · WAL L7 查询规则PromQL L8 通知呈现AM · Grafana 失败表现:目标不存在 → up 序列缺失 失败表现:up == 0 + lastError 失败表现:数据有但慢 / 丢 / 不通知 / 不显示 观察窗口 curl -si/service-discoveryrelabel_steps/targetsscrape_samples_*/tsdb-status/rules · statsamtool · inspector Operator 事件scrape_duration_secondsexceeded_*_totalhead_seriesevaluation_failuresnotifications_dropped 元监控(meta-monitoring)贯穿全部八段:Watchdog 死人开关 + Prometheus 自身指标 + 第二个 Prometheus 互相监控“监控系统坏了”的最坏表现不是误报,而是沉默
图 1-1 八段链路:左三段失败让目标“消失”,中两段失败让 up 变 0,右三段失败让“数据有但用不上”

从告警到根因的决策流

告警 / 空面板症状 监控可信?Watchdog · 自监控 序列不存在 → L1–L3 up == 0 → L4–L5 up == 1 → L6–L8 或业务 取证 → 止血 根因 + 护栏
图 1-2 “up 存在吗?值是多少?”这一个问题就能把搜索空间缩小到两三段

交互:症状 → 链路段定位器

点击一个真实症状,看它落在八段中的哪一段、哪些段已经“确认正常”,以及下一步应执行的只读诊断命令。

选择上方的一个症状。
$ # 建议执行的诊断命令会显示在这里

五步法常用的只读命令

命令 / 查询段说明
count by (job) (up)、count by (job) (up == 0)L2–L5每个 job 的目标数与失败数;与“期望副本数”对比可发现目标消失
curl -s $P/api/v1/targets?state=active | jq …L4–L5每个目标的 health、lastError、lastScrapeDuration、scrapePool
curl -s "$P/api/v1/targets?state=dropped"L3被 relabel 丢弃的目标及其 discoveredLabels
ALERTS{alertstate="firing"}L7Prometheus 内部的告警状态序列(pending/firing)
time() - prometheus_rule_group_last_evaluation_timestamp_secondsL7规则组多久没评估了(正常应小于评估间隔)
rate(prometheus_notifications_dropped_total[5m])、prometheus_notifications_alertmanagers_discoveredL8发给 Alertmanager 的通知是否在丢、发现了几个 Alertmanager
kubectl -n monitoring logs $PROM_POD -c prometheus --since=15m | grep -E 'level=(WARN|ERROR)'全部Prometheus 3 使用 slog 格式日志:time=… level=WARN source=… msg="…"
source ~/promlab/faultlab/env.sh
# 1) 可信度:Prometheus 自己、规则组、通知链路
pq 'up{job=~".*prometheus.*|.*alertmanager.*"}'
pq 'max by (rule_group) (time() - prometheus_rule_group_last_evaluation_timestamp_seconds) > 60'
pq 'ALERTS{alertname="Watchdog"}'
# 2) 定段:目标数量与失败目标(含 lastError)
pq 'count by (job) (up == 0)'
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.health!="up") | [.scrapePool, .labels.instance, .lastError] | @tsv'
[{"__name__":"up","job":"kps-kube-prometheus-stack-prometheus",...},"1"]
[{"__name__":"up","job":"kps-kube-prometheus-stack-alertmanager",...},"1"]
[{"__name__":"ALERTS","alertname":"Watchdog","alertstate":"firing","severity":"none"},"1"]
(后三条查询在健康时没有输出)

如何验证:人为制造一个故障(实验分页)后,同样的命令应当准确地指向那一段。常见错误:在 kind 的 kps 中,kube-controller-manager、kube-scheduler、kube-etcd、kube-proxy 目标常常是 down(控制面组件只监听 127.0.0.1),这是已知环境噪声,不要被它们干扰——用 job 过滤你关心的目标。生产用途:把这几条查询做成值班手册的第一页,或做成一个 “Meta-monitoring” 仪表盘。

实验 1:同一个“空面板”,三种根因(约 6 分钟)

症状统一为:查询 job:faultexp_http_requests:rate5m 在 Grafana / Prometheus 中没有数据。每一轮都先用五步法判断,再看答案。

根因 A:目标消失(L2)——把 Deployment 缩容到 0。
kubectl -n faultlab scale deploy/faultexp --replicas=0
sleep 60
pq 'up{job="faultexp"}'                 # 没有输出:序列不存在
pq 'absent(up{job="faultexp"})'         # 返回 1
curl -s "$P/api/v1/targets?state=active" | jq '[.data.activeTargets[] | select(.labels.job=="faultexp")] | length'
[{"job":"faultexp"},"1"]
0

Endpoints 为空 → SD 不产生目标 → 没有 up。FaultexpDown 永远不会触发,只有 FaultexpAbsent 会在 2 分钟后 firing。复位:kubectl -n faultlab scale deploy/faultexp --replicas=1。

根因 B:抓取超时(L4)——响应延迟 12 秒,超过 scrapeTimeout: 10s。
kubectl -n faultlab set env deploy/faultexp DELAY=12 && kubectl -n faultlab rollout status deploy/faultexp
sleep 45
pq 'up{job="faultexp"}'
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.labels.job=="faultexp") | .lastError'
[{"__name__":"up",...,"job":"faultexp",...},"0"]
Get "http://10.244.0.41:8080/metrics": context deadline exceeded

序列存在、值为 0、lastError 明确。复位:kubectl -n faultlab set env deploy/faultexp DELAY-。

根因 C:观测误差(L7)——数据完好,是查询写错了。
pq 'job:faultexp_http_requests:rate5m{job="faultexp-svc"}'   # 空:标签值写错
pq 'count by (job) (job:faultexp_http_requests:rate5m)'       # 先看实际有哪些 job
pq 'rate(faultexp_http_requests_total[10s])'                   # 空:窗口小于两个抓取间隔(15s)
(第一条无输出)
[{"job":"faultexp"},"2"]
(第三条无输出)

rate() 至少需要窗口内有两个样本;抓取间隔 15s 时窗口应 ≥ 4 × 15s = 1m 才稳健(Grafana 中用 $__rate_interval,模块 7)。

复盘:填写三行记录(症状相同、段不同、观察窗口不同)。
根因 | 段 | up 状态   | 决定性证据                          | 护栏
A    | L2 | 不存在    | absent(up{job="faultexp"}) == 1     | 每个关键 job 都有 absent() 告警
B    | L4 | 0         | lastError: context deadline exceeded | scrape_duration_seconds 接近 timeout 时预警
C    | L7 | 1         | 标签值 / 窗口错误                   | 面板统一 $__rate_interval;查询先 count by

案例 1:凌晨“全绿”,其实监控早已失明

问题:一次 kps 升级后 ServiceMonitor 选择器从 release: kps 改成了另一个值,40 个业务 ServiceMonitor 全部未被选中,所有业务目标消失,up == 0 类告警自然不响;两天后用户投诉才发现。做法:增加 absent() 告警与“每个 job 的目标数低于期望”告警;Watchdog 接入外部死人开关服务。限制:absent() 需要为每个关键 job 单独写,适合少量核心服务;大规模时用 “目标数与上周同期比较”。

案例 2:告警风暴的根因是监控系统自身

问题:周一早上 300 个 TargetDown 同时 firing,值班人员开始逐个排查业务。做法:五步法第一步发现 Prometheus Pod 刚因 OOM 重启、WAL 回放用了 9 分钟——回放期间所有目标都被视为“新出现”,部分规则在数据不完整时被评估。结论:先看 Prometheus 自身指标(process_start_time_seconds、prometheus_tsdb_head_series)再看业务,节省了一小时。根因是基数爆炸(模块 3)。

案例 3:空面板其实是查询问题

问题:业务团队报告“Prometheus 丢数据”。做法:同一查询在 Prometheus UI 有数据,在 Grafana 没有 → L8;Query inspector 显示面板使用了 [1m] 窗口而 Grafana 自动 step 为 2m,部分时间段窗口内只有一个样本。修复:统一使用 $__rate_interval。

常见错误与解决

告警没有响,但目标明明已经挂了(up 查不到任何序列)

段:L2/L3。原因:目标消失时 up 序列在 5 分钟 lookback 后彻底消失,up == 0 表达式返回空集。诊断:pq 'absent(up{job="faultexp"})'、/service-discovery。修复:补 absent() 告警,或 count(up{job="x"}) < N。

Prometheus UI 能打开,但所有规则的 “Last evaluation” 都是几分钟前

段:L7。原因:规则组评估时间超过了评估间隔(被慢查询拖住),或 Prometheus 正在 WAL 回放。诊断:pq 'rate(prometheus_rule_group_iterations_missed_total[5m]) > 0'、pq 'prometheus_rule_group_last_duration_seconds > prometheus_rule_group_interval_seconds'。修复:拆分慢规则组、优化表达式(模块 4)。

kind 上 kube-controller-manager / kube-scheduler / kube-etcd 目标 down:connect: connection refused

段:L4。原因:kubeadm 默认让这些组件只监听 127.0.0.1,Prometheus 从 Pod 网络无法访问。处理:实验环境中可在 kps values 中关闭对应 ServiceMonitor(kubeControllerManager.enabled=false 等),或修改组件的 --bind-address。在排错时先过滤掉这些已知噪声。

Watchdog 告警不见了

段:L7/L8。含义:要么规则没加载(PrometheusRule 选择器变了)、要么 Prometheus 不在评估、要么 Alertmanager 收不到。诊断:/rules 搜索 Watchdog;pq 'prometheus_notifications_alertmanagers_discovered';kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool alert query --alertmanager.url=http://localhost:9093 alertname=Watchdog。这是“告警链路断了”的最强信号,优先级最高。

命令行操作题
1. 写一条查询,列出“每个 job 中失败目标的数量”,并只显示有失败的 job。
count by (job) (up == 0)

up == 0 只保留值为 0 的序列,count by (job) 后只有存在失败目标的 job 才会出现。

2. 用一条 curl + jq 命令打印所有不健康目标的 scrapePool、instance 和 lastError。
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.health!="up") | [.scrapePool, .labels.instance, .lastError] | @tsv'
场景分析题
值班时收到 50 条不同服务的 TargetDown,同一分钟内触发。你的前三个动作是什么?

① 判断可信度:大量目标同时 down 通常是共因——Prometheus 自身(重启 / OOM / 网络策略)、某个节点、DNS、Operator 配置变更。先看 process_start_time_seconds{job=~".*prometheus.*"}、Prometheus 日志、最近的变更(Helm history、GitOps 提交)。② 看 lastError 是否一致:全是 context deadline exceeded 指向 Prometheus 侧资源 / 网络;全是 connection refused 指向目标侧或 NetworkPolicy。③ 止血:在确认共因后用一条宽匹配的静默压住风暴(写明原因与到期时间),集中处理共因,不要逐个服务排查。

经核实的教学视频

▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
英文 · Prometheus 创始成员讲常见错误,包括缺少 absent 告警、基数等,适合作为本课导读
▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
英文 · 架构回顾:抓取、存储、告警各组件的位置(对应八段链路)

官方文档

视频分镜脚本(约 90 秒)

镜头 1 · 0–20s
画面:手机弹出告警 “FaultexpDown”,镜头拉远露出八个方块组成的链路。
旁白:告警只是症状,它可能来自链路上的任何一段。
镜头 2 · 20–50s
画面:三个并排终端:up 不存在、up 等于 0、up 等于 1;各自对应的方块亮起。
旁白:先问一个问题——up 存在吗?值是多少?答案直接告诉你在哪一段。
镜头 3 · 50–75s
画面:Watchdog 心跳线持续跳动,然后突然变平,外部死人开关发出警报。
旁白:监控系统坏掉时最危险的是沉默,所以要监控监控本身。
镜头 4 · 75–90s
画面:五步法清单逐项打勾:可信度、定段、取证、止血、根因与护栏。
旁白:每次排错都至少留下一条护栏。
或在“测验”中取得 ≥ 70% 的分数

模块 2 · 抓取失败:目标 down、超时与服务发现

06:00 – 13:00 · lastError 是 Prometheus 写给你的诊断报告;先区分“目标不存在”和“目标存在但抓取失败”,再逐段排查
7 分钟Prometheus 3.16 · Operator 0.95★★★★★
学习目标
  • 描述一次抓取的内部步骤与它产生的合成序列:up、scrape_duration_seconds、scrape_samples_scraped、scrape_samples_post_metric_relabeling、scrape_series_added。
  • 把常见 lastError 映射到根因:connection refused、no such host、context deadline exceeded、server returned HTTP status 401/403/404、body size limit exceeded、received unsupported Content-Type …、non-compliant scrape target sending blank Content-Type …。
  • 在 kps 中逐级检查 ServiceMonitor 选择链:Prometheus CR 选择器 → ServiceMonitor → Service 标签 → Service 端口名 → Endpoints(就绪 Pod)。
  • 用 /api/v1/targets?state=dropped 与 /api/v1/targets/relabel_steps 调试 relabel。
前置知识:第 1 课抓取配置、第 5 课 ServiceMonitor。重要程度:★★★★★

What:一次抓取内部发生了什么(v3.16.0 scrape/scrape.go)

  1. 调度:每个目标一个 scrape loop,按 scrape_interval 周期运行,起始偏移由目标标签哈希决定(避免所有目标同时抓取)。
  2. 请求:HTTP GET,Accept 头按 scrape_protocols 协商(默认 OpenMetrics 1.0.0 → OpenMetrics 0.0.1 → Prometheus text 1.0.0 → text 0.0.4);整个请求受 scrape_timeout 约束(默认 10s,且不得大于 scrape_interval,否则配置加载报 scrape timeout greater than scrape interval for scrape config with job name "…")。
  3. 响应检查:状态码非 200 → server returned HTTP status 404 Not Found;body 超过 body_size_limit → body size limit exceeded。
  4. 选择解析器:Prometheus 3 严格按 Content-Type 选择解析器;空或不认识且没有配置 fallback_scrape_protocol 时整次抓取失败。
  5. 解析 + metric relabel + 限制:逐个样本执行 metric_relabel_configs,检查 label_limit、label_name_length_limit、label_value_length_limit;累计样本数超过 sample_limit 时整次抓取回滚。
  6. 写入:提交到 TSDB;抓取失败时以空 body 再追加一次,给上次存在的序列写入陈旧标记(stale marker),所以失败目标的指标在图上立刻断开而不是“延续 5 分钟”。
  7. 报告:写入合成序列 up(成功 1 / 失败 0)、scrape_duration_seconds、scrape_samples_scraped、scrape_samples_post_metric_relabeling、scrape_series_added;开启 extra_scrape_metrics(3.x 中为配置项,旧的 --enable-feature=extra-scrape-metrics 正在淘汰)后还有 scrape_timeout_seconds、scrape_sample_limit、scrape_body_size_bytes。

lastError 速查(报错原文来自 v3.16.0 源码或 Go 标准库)

lastError(原文)段根因修复方向
Get "http://10.244.0.37:8081/metrics": dial tcp 10.244.0.37:8081: connect: connection refusedL4端口没有进程监听:targetPort 错、容器未监听、只监听 127.0.0.1核对 Service targetPort 与容器端口;ss -lntp
… dial tcp: lookup x on 10.96.0.10:53: no such hostL4静态目标 / DNS SD 写错主机名修正地址或改用 Kubernetes SD
… context deadline exceededL4响应时间 > scrape_timeout:exporter 慢(每次抓取都实时查询后端)、指标太多、网络丢包、NetworkPolicy 静默丢包看 scrape_duration_seconds 趋势;优化 exporter(缓存);必要时调高 timeout(≤ interval)
server returned HTTP status 401 Unauthorized / 403 ForbiddenL4需要认证(kubelet、受保护端点)或 RBAC 不足ServiceMonitor 中配置 authorization/bearerTokenSecret/TLS;检查 RBAC
server returned HTTP status 404 Not FoundL1/L4path 错(/metrics vs /actuator/prometheus)修正 path
body size limit exceededL4响应超过 body_size_limit(Operator:bodySizeLimit / enforcedBodySizeLimit)减少指标;确认 limit 合理
received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for targetL5exporter 返回了非标准 Content-Type(Prometheus 2.x 会默默按文本解析,3.x 拒绝)修 exporter;或设置 fallback_scrape_protocol: PrometheusText0.0.4(Operator:fallbackScrapeProtocol)
non-compliant scrape target sending blank Content-Type and no fallback_scrape_protocol specified for targetL5响应没有 Content-Type 头同上
sample limit exceededL5单次抓取样本数 > sample_limit模块 3
label_limit exceeded (metric: …, number of labels: 23, limit: 20)L5某条序列标签数超限模块 3

Why:kps 中目标“不出现”的选择链

在 Operator 体系中,“目标为什么没有出现”比“目标为什么 down”更常见。链路上每一级都是静默失败——没有报错,只是没有目标:

  1. Prometheus CR 的 serviceMonitorSelector(kps 默认 serviceMonitorSelectorNilUsesHelmValues: true → 只选 release: kps)与 serviceMonitorNamespaceSelector(kps 默认 {} = 所有命名空间)。
  2. ServiceMonitor spec.selector 必须匹配 Service 的标签(不是 Pod 的标签),namespaceSelector 默认只看 ServiceMonitor 自己的命名空间。
  3. endpoints 的 port 是 Service 端口的名字(Operator 官方排错文档特别强调:端口名在 Kubernetes 中可选,但 ServiceMonitor 需要它);也可用 targetPort(官方不推荐)。
  4. Service 必须有就绪的 Endpoints(Pod 就绪探针失败 → 不在 Endpoints 中 → 不是目标)。
  5. Prometheus 的 ServiceAccount 需要对目标命名空间的 services/endpoints(或 endpointslices)/pods 有 get/list/watch 权限——kps 默认给的是 ClusterRole。

How:两步分流

目标在 /targets 中且 down → 读 lastError(L4/L5)。目标不在 → 依次查:生成的配置里有没有这个 ServiceMonitor(L2-Operator)→ /service-discovery 中有没有被发现(L2-SD)→ 是否在 dropped 列表(L3)。Operator 会把非法的 ServiceMonitor 拒绝并发出 Kubernetes Event,kps 还有 PrometheusOperatorRejectedResources 告警。

When:调高 scrape_timeout 什么时候是对的?

只有当 exporter 天生慢(例如每次抓取都要查询一个数据库、或 blackbox 探测远端)且数据价值值得等待时;并且 timeout 必须 ≤ interval。更好的办法是让 exporter 缓存结果、拆分 job 或降低频率。不要把所有 job 的 timeout 都调大——它会掩盖网络与 NetworkPolicy 问题。

对比:目标 down vs 目标不存在

目标 down目标不存在
up0无序列
/targets红色,有 lastError不出现(可能在 dropped)
可用告警up == 0、kps 的 TargetDownabsent(up{job="x"})、目标数下降
常见段L4、L5L2、L3
常见误解① “ServiceMonitor 的 port: 8080 写数字也行”——port 字段是端口名字符串。② “selector 匹配 Pod 标签”——匹配的是 Service 的标签。③ “升级到 Prometheus 3 后 exporter 突然 down 是网络问题”——很可能是 Content-Type 严格校验。④ “抓取失败后旧数据会延续 5 分钟”——失败时会写入陈旧标记,曲线立即断开;只有目标消失时才会出现 lookback 残影(目标消失的那一刻同样会写陈旧标记,但若 Prometheus 重启等情况错过了这一刻,就会靠 lookback 过期)。

抓取流水线与失败点

SDendpoints relabelkeep/drop GETtimeout 状态/大小200 · body Content-Type选解析器 解析+限制metric_relabel 追加head/WAL 报告up · scrape_* 无目标droppedrefuseddeadlineHTTP 4xx/5xxbody sizeunsupportedblank CTsample limitlabel_limitout of orderduplicate up 序列不存在 整次抓取失败:up = 0 + lastError已有序列写入陈旧标记,曲线立即断开 部分样本丢弃,up 仍为 1只记日志 + 计数器 注意:乱序 / 重复时间戳只丢弃单个样本并计入 prometheus_target_scrapes_sample_*_total,不会让 up 变 0
图 2-1 每个失败点对应的 up 状态:左 = 不存在,中 = 0,右 = 1 但有丢弃

kps 的 ServiceMonitor 选择链

Prometheus CRserviceMonitorSelectorrelease: kps ServiceMonitorselector: app=faultexpport: http Servicelabels: app=faultexpports[].name: http Endpoints仅就绪 PodtargetPort 目标serviceMonitor/faultlab/faultexp/0 ✗ 标签不符 → 配置中没有✗ 端口名不符 → SD 无目标✗ Service 标签不符✗ 就绪失败 / targetPort 错✗ 网络 / 认证 → down 前四级全部是“静默失败”:没有报错,只有目标消失 —— 用 absent() 告警兜底,用配置 Secret 与 /service-discovery 逐级确认
图 2-2 只有最后一级失败才会产生 lastError

交互:抓取流水线故障模拟器

选择一种注入的故障,逐步执行一次抓取:每一步显示 Prometheus 实际做的事情,失败处显示 v3.16.0 源码中的报错原文以及最终的 up 与合成指标。

选择故障后点击“播放”或“下一步”。
$ # Prometheus 的行为与日志会显示在这里

核心命令

命令段说明
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0"L4–L5按 scrape pool 过滤;kps 的 pool 名为 serviceMonitor/<ns>/<name>/<endpoint 序号>
curl -s "$P/api/v1/targets?state=dropped"L3被丢弃的目标;默认只保留部分(keep_dropped_targets / Operator keepDroppedTargets 控制数量)
curl -s -G "$P/api/v1/targets/relabel_steps" --data-urlencode scrapePool=… --data-urlencode labels='{…}'L3对给定的发现标签逐条执行 relabel 规则,返回每一步的 rule、output、keep
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzipL2Operator 生成的完整配置(官方排错文档的方法)
kubectl get events -A --field-selector involvedObject.kind=ServiceMonitorL2Operator 拒绝非法资源时发出的事件
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator | tailL2Operator 调和日志
kubectl -n faultlab get endpointslices -l kubernetes.io/service-name=faultexpL2Service 后面是否有就绪的端点
source ~/promlab/faultlab/env.sh
# 1) 目标状态(含抓取耗时与 lastError)
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" \
  | jq '.data.activeTargets[] | {instance: .labels.instance, health, lastError, lastScrapeDuration, scrapeInterval, scrapeTimeout}'
# 2) 生成的配置里有没有这个 ServiceMonitor
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' \
  | base64 -d | gunzip | grep -n 'job_name: serviceMonitor/faultlab/'
{
  "instance": "10.244.0.37:8080",
  "health": "up",
  "lastError": "",
  "lastScrapeDuration": 0.003121,
  "scrapeInterval": "15s",
  "scrapeTimeout": "10s"
}
412:- job_name: serviceMonitor/faultlab/faultexp/0

relabel 逐步调试(L3)

POOL=serviceMonitor/faultlab/faultexp/0
LBL=$(curl -s "$P/api/v1/targets?state=any&scrapePool=$POOL" | jq -c '(.data.activeTargets + .data.droppedTargets)[0].discoveredLabels')
curl -s -G "$P/api/v1/targets/relabel_steps" --data-urlencode "scrapePool=$POOL" --data-urlencode "labels=$LBL" \
  | jq -r '.data.steps[] | "\(.rule.action)\t\(.rule.source_labels // [] | join(","))\tkeep=\(.keep)"' | head -12
keep	__meta_kubernetes_service_label_app	keep=true
keep	__meta_kubernetes_endpoint_port_name	keep=true
replace	__meta_kubernetes_namespace	keep=true
...

如何验证:出问题的那条规则之后 keep=false。常见错误:labels 参数必须是 JSON 对象(发现标签,包含 __meta_*)。生产用途:修改 relabel 规则前,先用 relabel_steps 对真实标签预演。另外 Prometheus 3 支持 scrape_failure_log_file(kps:prometheus.prometheusSpec.scrapeFailureLogFile)把每次抓取失败写入文件,适合偶发失败的取证。

从集群内直接验证 L1(绕过 Prometheus)

kubectl -n faultlab run curl --rm -i --restart=Never --image=curlimages/curl:8.11.1 -- \
  -s -o /dev/null -w 'code=%{http_code} ct=%{content_type} time=%{time_total}s size=%{size_download}\n' \
  http://faultexp.faultlab:8080/metrics
code=200 ct=text/plain; version=0.0.4; charset=utf-8 time=0.004s size=316

实验 2:四种抓取故障(约 8 分钟)

connection refused(L4):把 Service 的 targetPort 改成 8081。
kubectl -n faultlab patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8081}]'
sleep 40
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastError)"'
down Get "http://10.244.0.37:8081/metrics": dial tcp 10.244.0.37:8081: connect: connection refused

复位:kubectl -n faultlab patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":"http"}]'。注意 instance 标签也变成了 :8081——目标地址来自 Endpoints 的端口。

Content-Type(L5,Prometheus 3 特有):
kubectl -n faultlab set env deploy/faultexp CT=application/octet-stream && kubectl -n faultlab rollout status deploy/faultexp
sleep 40
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastError)"'
down received unsupported Content-Type "application/octet-stream" and no fallback_scrape_protocol specified for target

两种修复:首选修 exporter(kubectl -n faultlab set env deploy/faultexp CT-);无法修改第三方 exporter 时,在 ServiceMonitor 上设置回退协议:

kubectl -n faultlab patch servicemonitor faultexp --type=merge -p '{"spec":{"fallbackScrapeProtocol":"PrometheusText0.0.4"}}'
sleep 60; pq 'up{job="faultexp"}'
kubectl -n monitoring logs $PROM_POD -c prometheus --since=2m | grep -i 'content type' | tail -1
[{"__name__":"up",...,"job":"faultexp",...},"1"]
(DEBUG 级别时才会出现 "Invalid content type on scrape, using fallback setting." 日志;默认 INFO 级别不显示)

复位:kubectl -n faultlab set env deploy/faultexp CT-,并 kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"remove","path":"/spec/fallbackScrapeProtocol"}]'。

ServiceMonitor 未被选中(L2):删除 release 标签。
kubectl -n faultlab label servicemonitor faultexp release-
sleep 60
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -c 'serviceMonitor/faultlab/faultexp' || true
pq 'absent(up{job="faultexp"})'
kubectl -n monitoring get prometheus $PROM_CR -o jsonpath='{.spec.serviceMonitorSelector}{"\n"}'
0
[{"job":"faultexp"},"1"]
{"matchLabels":{"release":"kps"}}

没有任何报错——只有目标消失。复位:kubectl -n faultlab label servicemonitor faultexp release=kps。

relabel 把目标丢了(L3):加一条正则写错的 keep。
kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"add","path":"/spec/endpoints/0/relabelings","value":[{"sourceLabels":["__meta_kubernetes_pod_label_app"],"regex":"fault-exp","action":"keep"}]}]'
sleep 60
curl -s "$P/api/v1/targets?state=dropped" | jq -r '.data.droppedTargets[] | select(.discoveredLabels.__meta_kubernetes_service_name=="faultexp") | .discoveredLabels.__meta_kubernetes_pod_label_app' | head -3
faultexp

发现标签值是 faultexp,正则 fault-exp 不匹配(relabel 正则是完全锚定的)。用上面的 relabel_steps 命令能看到这条 keep 之后 keep=false。复位:kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"remove","path":"/spec/endpoints/0/relabelings"}]'。如果 dropped 列表为空,可能是被丢弃目标的保留数量限制,换用 relabel_steps 验证。

案例 1:升级到 Prometheus 3 后三个老 exporter 全部 down

问题:从 2.x 升级到 3.x 当天,一个自研 exporter(手写 HTTP,未设 Content-Type)和两个第三方 exporter(返回 text/html)全部 down。做法:lastError 直接给出原因;自研 exporter 修复为 text/plain; version=0.0.4;第三方的在 ServiceMonitor 上加 fallbackScrapeProtocol: PrometheusText0.0.4 并提交上游 issue。教训:升级前在预发环境用 3.x 抓取一遍所有目标,比对 up。

案例 2:间歇性 context deadline exceeded

问题:一个数据库 exporter 每小时有几次超时。做法:画出 max_over_time(scrape_duration_seconds{job="db"}[1h]),发现在整点备份时抓取耗时升到 12 秒——exporter 每次抓取都执行慢查询。修复:exporter 启用结果缓存、把慢查询指标拆到单独的 job(interval 2m、timeout 60s)。限制:拆分后两个 job 的标签要一致,否则面板查询要改。

案例 3:NetworkPolicy 导致“只有部分节点”的目标超时

问题:新命名空间启用默认拒绝的 NetworkPolicy 后,目标全部 context deadline exceeded(数据包被静默丢弃,所以不是 connection refused)。修复:允许来自 monitoring 命名空间、Prometheus Pod 标签的入站流量到指标端口。经验:refused = 有人明确拒绝;deadline = 没人回应(丢包、过载、卡住)。

常见错误与解决

scrape timeout greater than scrape interval for scrape config with job name "…"

段:配置加载。原因:scrape_timeout > scrape_interval(v3.16.0 config/config.go 校验)。在 Operator 中这样的配置会被拒绝或导致重新加载失败。诊断:kubectl -n monitoring logs $PROM_POD -c config-reloader、pq 'prometheus_config_last_reload_successful'。修复:timeout ≤ interval。

ServiceMonitor 存在,但 /targets 中完全看不到

诊断顺序:① 配置 Secret 中 grep serviceMonitor/<ns>/<name>:没有 → 选择器标签 / 命名空间选择器 / Operator 拒绝(kubectl get events -n <ns> --field-selector involvedObject.name=<sm>)。② 有 → kubectl get svc -l <selector> 是否匹配到 Service、端口名是否一致。③ kubectl get endpointslices -l kubernetes.io/service-name=<svc> 是否有就绪端点。④ dropped targets / relabel_steps。

Get "http://…/metrics": context deadline exceeded

诊断:pq 'max_over_time(scrape_duration_seconds{job="X"}[30m])' 看是否逼近 timeout;集群内 curl 计时(命令分页);看 NetworkPolicy。修复:优化 exporter、拆 job、修网络;最后才是调大 timeout。

server returned HTTP status 403 Forbidden(kubelet / cAdvisor 目标)

原因:Prometheus ServiceAccount 缺少 nodes/metrics 等权限,或 kubelet 未开启 webhook 认证(Operator 排错文档列出了 kubelet 403 的处理)。诊断:kubectl auth can-i get nodes/metrics --as=system:serviceaccount:monitoring:kps-kube-prometheus-stack-prometheus。

received unsupported Content-Type "text/html; charset=utf-8" and no fallback_scrape_protocol specified for target

原因:多半是 path 指向了一个 HTML 页面(登录页、默认首页)而不是指标端点,或者是 exporter 不规范。诊断:集群内 curl 看 body 前几行。修复:修正 path;确认是规范问题后再用 fallbackScrapeProtocol。

目标 up = 1,但某些指标“偶尔丢失”,日志有 Error on ingesting out-of-order samples

原因:两个目标暴露了完全相同的序列(例如 honor_labels: true 且两个副本输出相同标签),或 exporter 自带时间戳且时间倒退。诊断:pq 'rate(prometheus_target_scrapes_sample_out_of_order_total[5m]) > 0'、prometheus_target_scrapes_sample_duplicate_timestamp_total。修复:确保每个目标的标签集唯一(不要随意 honor_labels),去掉 exporter 输出的时间戳。

命令行操作题
1. 找出过去 30 分钟抓取耗时超过超时时间 80% 的目标(假设 timeout 统一为 10s)。
max_over_time(scrape_duration_seconds[30m]) > 8

开启 extra_scrape_metrics 后可写成通用形式:max_over_time(scrape_duration_seconds[30m]) / scrape_timeout_seconds > 0.8。

2. 不依赖 Prometheus UI,确认 ServiceMonitor faultlab/faultexp 是否被写进了生成的配置。
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -n 'serviceMonitor/faultlab/faultexp'
场景分析题
新上线的服务 ServiceMonitor 已创建,Pod 运行正常,/targets 中没有它,Operator 日志没有报错。请给出排查顺序和每一步的命令。

① 选择器:kubectl get prometheus -n monitoring -o jsonpath='{..serviceMonitorSelector}' 与 ServiceMonitor 的标签比对(最常见:缺 release: kps)。② 配置:解码 prometheus-<CR> Secret grep job 名。③ Service:kubectl get svc -n app -l <sm 的 selector>;端口名是否等于 endpoints[].port。④ 端点:kubectl get endpointslices -l kubernetes.io/service-name=…,Pod 是否 Ready(就绪探针失败的 Pod 不在端点中)。⑤ relabel:dropped targets 或 relabel_steps。⑥ RBAC:如果 Prometheus 只被授予特定命名空间权限,SD 会在日志中报 forbidden。每一级都没有报错,这正是要用 absent() 兜底的原因。

经核实的教学视频

▶
Relabeling in Prometheus | Relabeling Architecture and Flow, Configuration, Examples, Debugging — Prometheus Monitoring with Julius | PromLabs
英文 · relabel 的流程、配置与调试,对应 L3
▶
Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor - Step-by-Step — Anton Putra
英文 · ServiceMonitor / PodMonitor 选择机制,对应 kps 选择链
▶
Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1 — TechWorld with Nana
英文 · kube-prometheus-stack 组件回顾(录制时间较早,版本细节以本课为准)

官方文档

视频分镜脚本(约 100 秒)

镜头 1 · 0–20s
画面:一条传送带上的“抓取包裹”经过 SD、relabel、GET、Content-Type、限制、写入六个关卡。
旁白:每一次抓取都要过这些关,任何一关失败,up 就会变成零,或者目标干脆消失。
镜头 2 · 20–55s
画面:四个故障依次出现:connection refused、deadline exceeded、unsupported Content-Type、sample limit exceeded,每个在对应关卡亮红灯。
旁白:lastError 就是 Prometheus 写给你的诊断报告。
镜头 3 · 55–85s
画面:ServiceMonitor 选择链五级方块,第一级标签不匹配,后面全部变灰,没有任何报错。
旁白:目标消失是静默失败,只能逐级确认,或者用 absent 告警兜底。
镜头 4 · 85–100s
画面:relabel_steps 输出逐行展开,某一行 keep 变成 false。
旁白:relabel 不要猜,让 Prometheus 一步一步演给你看。
或在“测验”中取得 ≥ 70% 的分数

模块 3 · 基数爆炸:标签设计与限制

13:00 – 21:00 · 一个 user_id 标签就能让 Prometheus 的内存翻十倍。学会找到“谁在制造序列”,并在它压垮系统之前用限制把它挡在门外
8 分钟TSDB Status · sample_limit核心动画★★★★★
学习目标
  • 解释基数(cardinality):一个指标的序列数 = 实际出现过的标签值组合数,上限是各标签取值数的乘积;理解 churn(序列不断新建又过期)为什么比“稳定的高基数”更伤内存。
  • 用三种方法找到元凶:TSDB Status 页面 / /api/v1/status/tsdb、PromQL(topk(10, count by (__name__)({__name__=~".+"}))、scrape_series_added)、promtool tsdb analyze。
  • 配置护栏:sample_limit(超出则整次抓取失败)、label_limit / label_name_length_limit / label_value_length_limit、target_limit,以及 Operator 的 enforcedSampleLimit 等全局上限。
  • 止血与根治:metric_relabel_configs 丢弃指标或标签(以及“丢弃区分标签”的陷阱),修正埋点。
前置知识:第 1 课数据模型。重要程度:★★★★★

What:序列、基数与 churn

Prometheus 中一条序列由指标名 + 全部标签唯一确定。myapp_http_requests_total{method,route,status} 若有 4 种 method、30 个 route、6 种 status,再乘以 10 个 Pod(target 标签 pod、instance),上限是 4 × 30 × 6 × 10 = 7 200 条。如果有人加上 user_id(10 万个用户),上限变成 7.2 亿——这就是基数爆炸。

概念含义主要影响
活跃序列(head series)当前 head block 中的序列数 prometheus_tsdb_head_series内存(每条序列在 head 中有 memSeries 结构、标签字符串、倒排索引项、当前 chunk)
每次抓取样本数scrape_samples_scraped(每条序列每次抓取一个样本)CPU、WAL 写入、sample_limit
churn(序列流失)序列被创建后很快不再出现(标签值含时间、会话、Pod 名、请求 ID)head 中残留大量“已不活跃但未被回收”的序列,直到 head 压缩后的 GC;WAL 变大、回放变慢
查询基数一次查询选中的序列数查询延迟与内存(模块 4)

Why:为什么基数会“压垮”Prometheus

  • 内存:head 中的每条序列都常驻内存。经验值是每条活跃序列数 KiB(含标签、索引、chunk 缓冲);具体以你的实例 process_resident_memory_bytes / prometheus_tsdb_head_series 实测为准。50 万 → 500 万序列,内存可能从 3 GiB 涨到 30 GiB 并被 OOMKilled。
  • churn 放大:head 默认覆盖约 2–3 小时(模块 5)。每 30 秒换一批的标签值,即使“当前”只有 1 000 条,3 小时内 head 会累积 1 000 × 360 = 36 万条。
  • 重启变慢:WAL 记录了所有序列的创建,回放时间与序列数、样本数成正比;OOM → 重启 → 回放中又 OOM 是典型的死循环。
  • 查询变慢:sum(rate(x[5m])) 要读取所有匹配序列;倒排索引的 postings 列表也随之变长。
  • 下游成本:remote_write 到 Mimir / AMP / Azure Monitor 时,费用通常按样本数或活跃序列计费(第 3、4、6 课)。

How:找到元凶的三种方法

方法看什么优点注意
TSDB Status 页面(/tsdb-status)或 /api/v1/status/tsdb?limit=NheadStats(numSeries、chunkCount、minTime/maxTime)、seriesCountByMetricName、labelValueCountByLabelName、memoryInBytesByLabelName、seriesCountByLabelValuePair直接读 head 的倒排索引统计,很便宜只反映 head(最近约 2–3 小时);limit 默认 10、最大 10000
PromQLtopk(10, count by (__name__)({__name__=~".+"}))、topk(10, sum by (job) (scrape_series_added))、count(count by (user_id) (x))能按 job、namespace 切分;能画趋势第一条会选中全部序列,本身就是重查询,大实例上要谨慎(可能触发 max-samples)
promtool tsdb analyze已持久化块中的 churn 标签、最常见标签对、最高基数标签与指标能看“churn 最严重的标签”分析的是磁盘块(默认最后一个),新实例还没有块时会报错

How:护栏(v3.16.0 报错原文)

配置(scrape_config / ServiceMonitor 字段)超出时lastError
sample_limit / sampleLimit整次抓取回滚,up = 0,已有序列写入陈旧标记sample limit exceeded
label_limit / labelLimit整次抓取失败label_limit exceeded (metric: …, number of labels: N, limit: M)
label_name_length_limit整次抓取失败label_name_length_limit exceeded (metric: …, label name: …, length: N, limit: M)
label_value_length_limit整次抓取失败label_value_length_limit exceeded (metric: …, label name: …, value: "…", length: N, limit: M)
target_limit / targetLimit该 scrape pool 的所有目标都不抓取target_limit exceeded (number of targets: N, limit: M)
Operator:enforcedSampleLimit、enforcedLabelLimit、enforcedTargetLimit、enforcedBodySizeLimit(Prometheus CR)对所有 ServiceMonitor/PodMonitor 强制一个上限(取更小值),防止某个团队绕过 limit。kps:prometheus.prometheusSpec.enforcedSampleLimit

sample_limit 采用“失败即全丢”的设计是故意的:宁可让一个目标暂时 up = 0 并触发告警,也不让它悄悄吃掉整个 Prometheus。对应计数器 prometheus_target_scrapes_exceeded_sample_limit_total。

When:标签设计规则

  • 标签值必须是有界的小集合:method、route 模板(/orders/{id} 而不是 /orders/123)、status 类(或精确码)、region。
  • 永远不要用作标签:user_id、email、request_id / trace_id、完整 URL、SQL 文本、时间戳、错误消息全文。这些属于日志、trace 或 exemplar。
  • histogram 的 bucket 也是序列:le 有 12 个值就是 12 倍。第 1 课的 myapp 统一 buckets(0.005…5)是有意控制的;Native Histograms 能大幅减少这部分序列。
常见误解① “调大 sample_limit 就解决了”——只是把炸弹放进了屋里。② “用 labeldrop 去掉 user_id 就好”——如果 user_id 是唯一区分序列的标签,去掉后多条序列变成同一个标签集:值相同会被静默合并,值不同会触发 duplicate sample 丢弃,数据都不再正确;正确做法是在源头聚合或丢弃整个指标。③ “Prometheus 内存只和当前目标数有关”——churn 留下的序列在 head 压缩前一直占内存。④ “TSDB Status 显示的是全部历史”——只是 head。

标签值相乘:一个标签如何让序列数爆炸

method × 4GET POST PUT DELETE route × 30路由模板 status × 6200 201 400 404 500 503 pod × 10target 标签 = 7 200 条健康 + user_id × 100 000一次“方便排查”的代码改动 = 上限 7.2 亿条实际 = 出现过的组合数(仍可能数百万) 实际序列数 = 真实出现过的组合(不是全部乘积),但只要有一个无界标签,增长就没有上限
图 3-1 基数是乘法:控制住每个标签的取值数

head 中一条序列占用什么

倒排索引(postings) __name__="faultexp_user_requests_total"→ [ref 1, 2, 3, … 8000] user_id="u0" → [1]user_id="u1" → [2]…(每个值一个 postings 列表) session="s0" → [1] … memoryInBytesByLabelName 统计的就是这些标签值字符串占用的内存 memSeries(每条序列一个) ref、完整标签集head chunk(正在写入,内存中)已满 chunk → m-map 到 chunks_head/最后样本时间、陈旧状态一个 chunk 目标 120 个样本(--storage.tsdb.samples-per-chunk)序列不再出现后仍保留,直到head 截断后的 GC WAL(磁盘) Series 记录:首次出现时写入完整标签集Samples 记录:每次抓取churn → 大量 Series 记录→ WAL 变大、回放变慢重启时全部回放进内存
图 3-2 每条新序列同时消耗索引内存、memSeries 内存与 WAL 空间

核心动画:基数爆炸对内存与查询的影响

调整标签取值数与 churn,看三件事如何变化:① 每次抓取的样本数与 sampleLimit;② head 中累积的序列数与内存估算;③ 一个面板查询需要加载的样本数与 --query.max-samples(默认 50 000 000)。“时间线”按钮会逐步播放一次真实事故:发布 → 序列飙升 → 内存上涨 → sample limit 生效或 OOM → 修复。


每目标每次抓取样本
head 序列(约 3 小时累积)
head 内存估算(按 4 KiB/序列)
面板查询 sum(rate(x[5m])),6h 范围,step 30s 加载样本
目标状态
内存条:以 8 GiB 的 Prometheus Pod limit 为满格
拖动滑块,或播放事故时间线。
$ # 对应的真实指标、报错与命令

核心命令与查询

命令 / 查询作用
curl -s "$P/api/v1/status/tsdb?limit=5" | jq .datahead 统计 + 四个 Top 列表(limit 默认 10,最大 10000)
prometheus_tsdb_head_series、rate(prometheus_tsdb_head_series_created_total[5m])活跃序列与创建速率(churn 的直接信号)
topk(10, sum by (job) (scrape_series_added))哪个 job 每次抓取都在新建序列(churn 来源)
topk(10, max by (job) (scrape_samples_scraped))哪个 job 单次抓取样本最多
topk(10, count by (__name__)({__name__=~".+"}))序列最多的指标名(重查询,慎用)
count(count by (user_id) (faultexp_user_requests_total))某个标签的取值数
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb analyze /prometheus --limit=10分析最后一个持久化块的 churn 与基数
sum(increase(prometheus_target_scrapes_exceeded_sample_limit_total[1h]))sample_limit 生效次数
source ~/promlab/faultlab/env.sh
curl -s "$P/api/v1/status/tsdb?limit=5" | jq '{head: .data.headStats,
  topMetrics: .data.seriesCountByMetricName,
  topLabelValues: .data.labelValueCountByLabelName,
  topLabelMemory: .data.memoryInBytesByLabelName}'
{
  "head": {"numSeries": 61234, "numLabelPairs": 9812, "chunkCount": 132011, "minTime": 1763251200000, "maxTime": 1763258405123},
  "topMetrics": [
    {"name": "apiserver_request_duration_seconds_bucket", "value": 7920},
    {"name": "etcd_request_duration_seconds_bucket", "value": 5544}, ...],
  "topLabelValues": [{"name": "__name__", "value": 1820}, {"name": "id", "value": 410}, ...],
  "topLabelMemory": [{"name": "__name__", "value": 72310}, ...]
}

如何读:kps 默认采集的 apiserver / etcd histogram 往往就是基线中最大的指标——这也是很多团队在 kps values 中丢弃部分 bucket 的原因。常见错误:在大实例上频繁执行 count by (__name__) 全量查询;用 TSDB Status 替代。

止血:在 ServiceMonitor 上丢弃整个指标

spec:
  endpoints:
    - port: http
      metricRelabelings:
        - sourceLabels: [__name__]
          regex: faultexp_user_requests_total
          action: drop

全局护栏:kps values

prometheus:
  prometheusSpec:
    enforcedSampleLimit: 50000          # 任何 ServiceMonitor 的 sampleLimit 都不能超过它
    enforcedLabelLimit: 30
    enforcedLabelValueLengthLimit: 512
    enforcedTargetLimit: 500

kps 93.3.0 values 中 enforcedSampleLimit 默认是 false(不启用)。设置后 Operator 对所有 ServiceMonitor 取 min(自身 sampleLimit, enforced),未设置 sampleLimit 的也会被限制。

promtool:分析磁盘块(Compose 环境同样可用)

kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheus
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb analyze /prometheus --limit=5
# Compose(第 1 课 ~/promlab,镜像数据目录同为 /prometheus):
# cd ~/promlab && docker compose exec prometheus promtool tsdb analyze /prometheus --limit=5
BLOCK ULID                  MIN TIME       MAX TIME       DURATION  NUM SAMPLES  NUM CHUNKS  NUM SERIES  SIZE
01JD…                       1763229600000  1763236800000  2h0m0s    9102330      140211      60120       12MiB
Block ID: 01JD…
Duration: 2h0m0s
Total Series: 60120
Label names: 212
Postings (unique label pairs): 9750
Postings entries (total label pairs): 512330

Label pairs most involved in churning:
1830 session=1763235570-17
...
Highest cardinality labels:
8000 user_id
...
Highest cardinality metric names:
8000 faultexp_user_requests_total

kps 使用 prometheus:v3.16.0-distroless 镜像:有 promtool,没有 shell(kubectl exec … -- sh 会失败)。需要 du、ls 时用 kubectl debug 临时容器,或改用 /api/v1/status/tsdb/blocks 与 prometheus_tsdb_* 指标。刚安装不到约 3 小时的实例还没有持久化块,analyze 会因为找不到块而报错。

实验 3:user_id 标签爆炸 → sample limit → 修复(约 8 分钟)

记录基线:
pq 'prometheus_tsdb_head_series'
pq 'process_resident_memory_bytes{job=~".*prometheus"} / 2^20'
[{"__name__":"prometheus_tsdb_head_series",...},"61234"]
[{...,"job":"kps-kube-prometheus-stack-prometheus",...},"412.6"]
注入:一次“方便排查”的发布让每个用户都有一条序列(8 000 个用户 > sampleLimit 5000)。
kubectl -n faultlab set env deploy/faultexp SERIES=8000 && kubectl -n faultlab rollout status deploy/faultexp
sleep 45
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastError)"'
pq 'scrape_samples_scraped{job="faultexp"}'
pq 'increase(prometheus_target_scrapes_exceeded_sample_limit_total[2m])'
down sample limit exceeded
[{...,"job":"faultexp",...},"8003"]
[{...},"8"]

scrape_samples_scraped 仍然报告了真实样本数(源码注释:超过限制后继续解析,以便报告正确的总数),但一个样本都没有写入。FaultexpDown 将在 1 分钟后 pending → firing。护栏起作用了:Prometheus 的 head 没有增长。

观察“如果没有护栏”:临时把 sampleLimit 调到 20000(仅限实验)。
kubectl -n faultlab patch servicemonitor faultexp --type=merge -p '{"spec":{"sampleLimit":20000}}'
sleep 75
pq 'up{job="faultexp"}'
pq 'prometheus_tsdb_head_series'
curl -s "$P/api/v1/status/tsdb?limit=3" | jq -c '.data.seriesCountByMetricName, .data.labelValueCountByLabelName'
pq 'count(count by (user_id) (faultexp_user_requests_total))'
[{...},"1"]
[{"__name__":"prometheus_tsdb_head_series",...},"69241"]
[{"name":"faultexp_user_requests_total","value":8000},{"name":"apiserver_request_duration_seconds_bucket","value":7920},...]
[{"name":"user_id","value":8000},{"name":"session","value":8000},{"name":"__name__","value":1821}]
[{},"8000"]
再加上 churn:会话 ID 每 30 秒换一批(每分钟新增约 2 000 条序列,做 3 分钟即可)。
kubectl -n faultlab set env deploy/faultexp SERIES=1000 CHURN=1 && kubectl -n faultlab rollout status deploy/faultexp
sleep 180
pq 'rate(prometheus_tsdb_head_series_created_total[2m])'
pq 'topk(3, sum by (job) (scrape_series_added))'
pq 'prometheus_tsdb_head_series'
[{...},"33.6"]
[{"job":"faultexp"},"1000"]
[{...},"75890"]

当前每次抓取只有 1000 条,但每次都是新序列:head 序列数持续上涨,直到下一次 head 压缩 + GC 才回落。抓取间隔 15s、会话窗口 30s,所以每两次抓取中有一次 scrape_series_added 等于 1000(另一次为 0)——持续不为零的 series_added 就是 churn 的指纹;用 sum_over_time(scrape_series_added[5m]) 看更平滑。

止血与根治:先在 ServiceMonitor 上丢弃该指标,再“修复代码”(关闭 SERIES/CHURN),最后恢复 sampleLimit。
kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"add","path":"/spec/endpoints/0/metricRelabelings","value":[{"sourceLabels":["__name__"],"regex":"faultexp_user_requests_total","action":"drop"}]}]'
sleep 60
pq 'scrape_samples_scraped{job="faultexp"}'
pq 'scrape_samples_post_metric_relabeling{job="faultexp"}'
# 根治 + 复位
kubectl -n faultlab set env deploy/faultexp SERIES- CHURN-
kubectl -n faultlab patch servicemonitor faultexp --type=json -p '[{"op":"remove","path":"/spec/endpoints/0/metricRelabelings"}]'
kubectl -n faultlab patch servicemonitor faultexp --type=merge -p '{"spec":{"sampleLimit":5000}}'
[{...},"1003"]
[{...},"3"]

scrape_samples_scraped 与 scrape_samples_post_metric_relabeling 的差值就是 metric relabel 丢弃的样本数。注意:metric relabel 发生在抓取之后,exporter 仍然生成、网络仍然传输这些数据——它是止血,不是根治。head 中已经存在的序列要等 head 压缩后才释放内存。

案例 1:一个 path 标签让 Prometheus 每天 OOM

问题:某服务把原始 URL(含订单号)作为 path 标签,head 序列从 80 万涨到 900 万,Prometheus 反复 OOMKilled,每次重启 WAL 回放 20 分钟后又 OOM。做法:① 临时:ServiceMonitor 加 metricRelabelings 丢弃该指标,并把 Prometheus 内存 limit 临时调大以完成回放;② 根治:埋点改为路由模板;③ 护栏:kps 设置 enforcedSampleLimit,每个 ServiceMonitor 设 sampleLimit;新增告警 rate(prometheus_tsdb_head_series_created_total[10m]) 超过基线 3 倍。

案例 2:Kubernetes 自身指标的基数

问题:kps 默认采集的 apiserver_request_duration_seconds_bucket、etcd_request_duration_seconds_bucket 在大集群中占了 30% 的序列。做法:在 kps values 中给 kubeApiServer / kubeEtcd ServiceMonitor 加 metricRelabelings 丢弃不用的 bucket 或整个指标(先确认没有仪表盘/规则依赖);用 promtool tsdb analyze 每周复查。限制:kps 自带的某些规则和仪表盘依赖这些指标,丢弃前用 Grafana “Explore → Metrics” 或规则文件 grep 确认。

案例 3:remote_write 账单翻倍

问题:托管 Prometheus(按样本计费)月度账单翻倍。做法:本地 TSDB Status 的 seriesCountByMetricName 与托管侧的 usage 对比,定位到一个新 exporter 的 histogram(每个 Pod 60 个 bucket × 200 个 route)。在 write_relabel_configs 中只发送需要的指标,本地保留原始数据 2 天用于排错。

常见错误与解决

sample limit exceeded

段:L5。诊断:pq 'scrape_samples_scraped{job="X"}' 看真实样本数;集群内 curl 统计 grep -vc '^#';找出新增的指标与标签。修复:修埋点或用 metricRelabelings 丢弃;确有需要时才调高 limit,并评估内存。预防:每个 ServiceMonitor 设 sampleLimit,全局 enforcedSampleLimit。

label_limit exceeded (metric: http_requests_total{…}, number of labels: 23, limit: 20)

原因:exporter 把大量元数据作为标签(或 relabel 时 labelmap 把所有 Pod 标签都映射了进来)。修复:收窄 labelmap 正则;labeldrop 不需要的标签(确保剩余标签仍能唯一区分序列)。

Prometheus Pod 反复 OOMKilled,日志停在 "Replaying WAL, this may take a while"

原因:基数 / churn 让 head 超过内存 limit;回放 WAL 时需要重建全部序列,同样超限。处理:① 临时调大内存 limit 让回放完成;② 立即用 metricRelabelings / 下线目标阻止新序列;③ 等待 head 压缩释放。极端情况下备份后删除 WAL(丢失 head 中尚未压缩的约 2–3 小时数据),只在业务方接受时执行。详见模块 5。

TSDB Status 页面很慢或查询 count by (__name__) 报 query processing would load too many samples into memory

原因:全量选择所有序列本身就是重查询。修复:使用 /api/v1/status/tsdb?limit=…;按 job 缩小范围 count by (__name__) ({job="X"})。

labeldrop 后数据“少了”或出现 Error on ingesting samples with different value but same timestamp

原因:去掉了唯一区分序列的标签,多条序列合并为一条。诊断:pq 'rate(prometheus_target_scrapes_sample_duplicate_timestamp_total[5m])'。修复:撤销 labeldrop,改为在源头聚合或丢弃整个指标。

命令行操作题
1. 不用全量查询,找出 head 中序列最多的 5 个指标与取值最多的 5 个标签。
curl -s "$P/api/v1/status/tsdb?limit=5" | jq '.data.seriesCountByMetricName, .data.labelValueCountByLabelName'
2. 写一条告警表达式:过去 10 分钟序列创建速率是 1 天前同一时刻的 3 倍以上。
rate(prometheus_tsdb_head_series_created_total[10m])
  > 3 * rate(prometheus_tsdb_head_series_created_total[10m] offset 1d)
场景分析题
开发团队要求“把 customer_id 加到请求指标上,方便按大客户查看延迟”,客户有 5 万个,其中 50 个是重点客户。你怎么回应?

不能直接把 5 万个取值的标签加到高频指标上:乘以 route、status、Pod 与 histogram bucket 后会达到千万级序列。可选方案:① 只对 50 个重点客户输出 customer_tier 或 key_account 标签(其余归为 other),取值有界;② 单个客户的排查用日志 / trace(带 customer_id),指标上用 exemplar 关联 trace;③ 如果必须按客户统计,用单独的低频、无 histogram 的指标,并设置 sampleLimit;④ 在 CI 中用 promtool check metrics 检查埋点(它会提示一些命名问题,基数仍需人工评审)。

经核实的教学视频

▶
PromCon 2018: Bomb Squad: Containing the Cardinality Explosion — Prometheus Monitoring
英文 · 大规模环境中检测与限制基数的实践
▶
Tracking Cardinality Explosions In Flight - Roman Khavronenko & Langson Zhang — CNCF [Cloud Native Computing Foundation]
英文 · 在运行中追踪基数爆炸
▶
Prometheus TSDB Churn: Diagnosing High Cardinality Metrics — Cloud Explainers
英文 · churn 与高基数诊断

官方文档

视频分镜脚本(约 100 秒)

镜头 1 · 0–20s
画面:四个标签方块相乘得到 7200,第五个方块“user_id × 100000”掉下来,数字滚动到数亿。
旁白:基数是乘法,一个无界标签就能让序列数失控。
镜头 2 · 20–50s
画面:head 内存条从绿色涨到红色,Pod 被 OOMKilled,重启后 WAL 回放进度条走到一半再次崩溃。
旁白:内存跟着活跃序列走,churn 会让旧序列在 head 中堆积。
镜头 3 · 50–80s
画面:TSDB Status 页面四个 Top 列表依次高亮,最上面一行是 faultexp_user_requests_total。
旁白:先用 TSDB Status 找到元凶,而不是在大实例上跑全量查询。
镜头 4 · 80–100s
画面:sampleLimit 像闸门一样关上,目标变红但 head 曲线保持平稳。
旁白:sample limit 选择牺牲一个目标,保护整个 Prometheus。
或在“测验”中取得 ≥ 70% 的分数

模块 4 · 查询性能:慢 PromQL 与仪表盘优化

21:00 – 28:00 · 查询的成本可以算出来:选中多少序列 × 每条序列读多少样本 × 多少个步长。把这个乘法变小,查询就快
7 分钟stats=all · recording rules★★★★☆
学习目标
  • 用成本模型估算查询:选中序列数、每步读取样本数、步数(range / step),并读懂 stats=all 返回的 seriesTouched、totalQueryableSamples、peakSamples、各阶段耗时。
  • 认识三道硬限制及其报错:--query.max-samples(默认 50000000)→ query processing would load too many samples into memory in …;--query.timeout(默认 2m)→ query timed out in …;单条序列最多 11 000 个点 → exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)。
  • 用 recording rule、先聚合再计算、收窄选择器、合理的 step 与刷新间隔优化仪表盘;用 query log 与 prometheus_engine_* 指标找出慢查询来源。
前置知识:第 1 课 PromQL、第 2 课 recording rules。重要程度:★★★★☆

What:一次查询的成本模型

PromQL 引擎处理一个范围查询 sum by (job) (rate(x[5m]))(时间范围 6h、step 30s)时:

  1. 选择序列:在倒排索引中求 __name__="x" 等匹配器的 postings 交集 → 得到 N 条序列(seriesTouched)。正则匹配器(尤其 =~".*foo.*")需要遍历该标签的全部取值。
  2. 逐步计算:步数 = 6h / 30s + 1 = 721。每一步对每条序列读取窗口内样本:5m / 15s ≈ 20 个。总共读取约 N × 721 × 20 个样本(totalQueryableSamples 的量级)。
  3. 内存峰值:引擎在同一时刻持有的样本数(peakSamples)受 --query.max-samples 限制;超过即报错,而不是变慢。
  4. 聚合与返回:sum by (job) 把 N 条变成几条,返回 721 个点。返回点数 = range / step + 1,超过 11 000 被 API 直接拒绝。
参数(v3.16.0 默认)含义超出时kps 设置位置
--query.max-samples=50000000单个查询同时载入内存的样本上限query processing would load too many samples into memory in query executionprometheusSpec.query.maxSamples
--query.timeout=2m单个查询最长执行时间query timed out in expression evaluation(in 之后为出错阶段)prometheusSpec.query.timeout
--query.max-concurrency=20同时执行的查询数,超出的排队(prometheus_engine_queries 中的排队时间计入 queue_time)变慢,可能因排队超时prometheusSpec.query.maxConcurrency
--query.lookback-delta=5m即时向量向前查找最近样本的最大距离—(影响“残影”与稀疏序列)prometheusSpec.query.lookbackDelta
11 000 点(API 硬编码)range / step 的上限exceeded maximum resolution of 11,000 points per timeseries…不可配置;增大 step

Why:哪些写法会慢

反模式为什么慢改写
{__name__=~".+"}、没有指标名的选择器选中全部序列总是带指标名;元数据用 /api/v1/status/tsdb
http_requests_total{path=~".*order.*"}非锚定正则遍历高基数标签的全部值用等值或前缀正则;修正标签设计
histogram_quantile(0.99, rate(x_bucket[5m]))对每个 Pod × route × bucket 分别计算histogram_quantile(0.99, sum by (le) (rate(x_bucket[5m]))),或 recording rule
max_over_time(rate(x[5m])[30d:1m])子查询在大范围内逐步计算内层recording rule 预计算内层
仪表盘 30 个面板 × 自动刷新 5s × 10 个人每分钟 3 600 个查询刷新 ≥ 30s–1m、折叠行(未展开不查询)、共享查询(Dashboard 数据源)
面板范围 30d、Max data points 很大步数多、点数多让 Grafana 自动计算 step($__interval),长范围看 recording rule 或下采样(第 6 课)

How:recording rule 是最有效的优化

recording rule 把 sum by (job, status) (rate(faultexp_http_requests_total[5m])) 这样的表达式每个评估间隔算一次并写成新序列 job:faultexp_http_requests:rate5m(命名约定 level:metric:operations,第 2 课)。仪表盘查询从“N 条原始序列 × 每步 20 个样本”变成“几条预计算序列 × 每步 1 个样本”。代价:规则组自身的评估成本、只能看到规则创建之后的数据(历史可用 promtool tsdb create-blocks-from rules 回填)。

When:先查 Prometheus 还是先查 Grafana

同一查询在 Prometheus UI 也慢 → 查询本身(本模块);Prometheus 快、Grafana 慢 → 面板太多、step 太小、数据源代理、浏览器渲染(模块 7);只有高峰期慢 → 并发与排队(prometheus_engine_query_duration_seconds{slice="queue_time"})、规则组与仪表盘抢资源。

常见误解① “调大 max-samples / timeout 就好”——它们是保护 Prometheus 不被单个查询拖垮的保险丝。② “step 越小越精确”——超过抓取间隔的精度没有意义,而成本线性上升。③ “recording rule 会让数据延迟”——延迟最多一个评估间隔,换来的是稳定的面板。④ “topk 能减少计算量”——topk 仍然要先计算全部序列。

查询成本 = 序列 × 每步样本 × 步数

① 选择序列postings 交集seriesTouched = N ② 每步读窗口[5m] / 15s ≈ 20 样本× 721 步 ③ 峰值内存peakSamples≤ query.max-samples ④ 聚合返回点数 = 721≤ 11 000 优化抓手① 收窄选择器 / 修基数 ② recording rule 把 N 变成几条、把 20 个样本变成 1 个 ③ 降低范围 / 增大 step④ 先 sum by (le) 再 histogram_quantile ⑤ 仪表盘刷新间隔与面板数量
图 4-1 每个阶段对应一个可调的旋钮

一个仪表盘如何放大查询压力

10 个浏览器刷新 5s 30 个面板 × 2 查询+ 变量 All 展开 Grafana 后端数据源代理 Prometheus7 200 查询/分钟max-concurrency 20 → 排队与规则评估抢 CPU 10 × (60s / 5s) × 60 = 7 200 次/分钟;把刷新改成 1m 并折叠不常用的行 → 约 300 次/分钟
图 4-2 慢的往往不是单个查询,而是查询的数量

交互:查询成本计算器

输入序列数、时间范围、step、rate 窗口与抓取间隔,计算步数、读取样本、峰值样本估算与是否触发限制;切换“使用 recording rule”看差异。估算模型为简化版(峰值按“每步每序列窗口样本数 × 序列数”估算),实际值以 stats=all 为准。

$ # 对应的 API 调用与可能的报错

核心命令

命令 / 查询作用
curl -s "$P/api/v1/query_range" --data-urlencode query=… -d start=… -d end=… -d step=30 -d stats=all返回 stats.timings 与 stats.samples(stats 只接受 true/all,其他值在 3.16 中会得到弃用警告)
prometheus_engine_query_duration_seconds{quantile="0.9"}按 slice(inner_eval、prepare_time、queue_time、result_sort)拆分的查询耗时
prometheus_engine_queries、prometheus_engine_queries_concurrent_max正在执行 / 排队的查询数与并发上限
prometheus_rule_group_last_duration_seconds规则组本身是否过慢
kps:prometheus.prometheusSpec.queryLogFile: /dev/stdout开启 query log(JSON,含查询文本、来源与统计),用 kubectl logs 读取;distroless 镜像中无法 cat 文件,写 stdout 最方便
promtool query instant $P 'expr'命令行即时查询(本机安装 promtool 时)
source ~/promlab/faultlab/env.sh
END=$(date +%s); START=$((END-6*3600))
q() { curl -s "$P/api/v1/query_range" --data-urlencode "query=$1" -d start=$START -d end=$END -d step=${2:-30} -d stats=all \
      | jq -c '{status, error, series: (.data.result|length), touched: .data.stats.samples.seriesTouched,
                samples: .data.stats.samples.totalQueryableSamples, peak: .data.stats.samples.peakSamples,
                evalSec: .data.stats.timings.evalTotalTime}'; }
q 'sum by (status) (rate(faultexp_http_requests_total[5m]))'
q 'sum by (status) (job:faultexp_http_requests:rate5m)'
q 'up' 1     # 6h / 1s = 21601 点
{"status":"success","error":null,"series":2,"touched":2,"samples":28840,"peak":...,"evalSec":0.0041}
{"status":"success","error":null,"series":2,"touched":2,"samples":1442,"peak":...,"evalSec":0.0012}
{"status":"error","error":"exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)","series":0,...}

faultexp 基线只有 2 条序列,差异还不明显;实验中会先制造 8 000 条序列再对比。常见错误:忘记 --data-urlencode,+、{ 等字符被错误编码,得到 bad_data: invalid parameter "query": …(API 错误格式:invalid parameter %q: …)。

开启 query log(kps values)

prometheus:
  prometheusSpec:
    queryLogFile: /dev/stdout
    query:
      maxSamples: 50000000      # 默认值,显式写出便于审计
      timeout: 2m
      maxConcurrency: 20
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --reuse-values -f querylog.yaml
kubectl -n monitoring logs $PROM_POD -c prometheus --since=5m | grep '"params"' | jq -c '{q: .params.query, step: .params.step, eval: .stats.timings.evalTotalTime}' | sort -t: -k4 -rn | head

query log 会记录每个查询(含规则评估之外的 API 查询),量大时只在排查期间开启。--reuse-values 会复用上次的 values 并叠加新的文件——注意它也会使用旧 chart 版本的默认值(Helm 课第 7 课),生产中建议用完整 values 文件。

实验 4:同一面板,优化前后(约 7 分钟)

制造一个“重”指标:让 faultexp 输出 4 000 条稳定的 user_id 序列(低于 sampleLimit),等待 5 分钟积累数据。
kubectl -n faultlab set env deploy/faultexp SERIES=4000 && kubectl -n faultlab rollout status deploy/faultexp
sleep 300
测量“面板原始查询”(先在同一终端执行“命令”分页中定义 q() 函数的那段代码):
END=$(date +%s); START=$((END-3600))
q 'sum(rate(faultexp_user_requests_total[5m]))' 15
q 'count by (session) (faultexp_user_requests_total{session=~".*99.*"})' 15
{"status":"success","series":1,"touched":4000,"samples":...,"evalSec":0.21}
{"status":"success","series":40,"touched":40,"samples":...,"evalSec":0.09}

第二条是非锚定正则:需要遍历 session 标签的 4 000 个值。

加 recording rule 并对比:
kubectl -n faultlab patch prometheusrule faultexp-rules --type=json -p '[{"op":"add","path":"/spec/groups/0/rules/-","value":{"record":"job:faultexp_user_requests:rate5m","expr":"sum by (job) (rate(faultexp_user_requests_total[5m]))"}}]'
sleep 120
q 'job:faultexp_user_requests:rate5m' 15
pq 'prometheus_rule_group_last_duration_seconds{rule_group=~".*faultexp.*"}'
{"status":"success","series":1,"touched":1,"samples":...,"evalSec":0.002}
[{...,"rule_group":"/etc/prometheus/rules/prometheus-kps-kube-prometheus-stack-prometheus-rulefiles-0/faultlab-faultexp-rules-....yaml;faultexp.rules"},"0.035"]

recording rule 只有规则创建之后的数据;面板切换到规则后,早于规则的时间段为空。

触发 max-samples(可选,仅实验环境):临时把 maxSamples 调到 10 万,体验报错。
kubectl -n monitoring patch prometheus $PROM_CR --type=merge -p '{"spec":{"query":{"maxSamples":100000}}}'
sleep 90
q 'sum(rate(faultexp_user_requests_total[5m]))' 15
kubectl -n monitoring patch prometheus $PROM_CR --type=json -p '[{"op":"remove","path":"/spec/query/maxSamples"}]'
{"status":"error","error":"query processing would load too many samples into memory in query execution",...}

Operator 修改 Prometheus 启动参数会滚动重启 Prometheus(触发 WAL 回放);直接 patch CR 的改动会在下一次 helm upgrade 时被覆盖——生产中通过 values 修改。

复位:
kubectl -n faultlab set env deploy/faultexp SERIES-
kubectl apply -f ~/promlab/faultlab/faultexp.yaml     # 恢复 PrometheusRule 原样

案例 1:周一早会仪表盘拖垮 Prometheus

问题:每周一 9 点 40 人同时打开“全局概览”(48 个面板、刷新 10s、默认范围 7d),Prometheus CPU 打满,规则组 missed iterations 导致告警延迟。做法:query log 按来源统计发现 70% 查询来自该仪表盘;核心面板改用 recording rule,默认范围改为 6h、刷新 1m,不常用的面板放进折叠行。结果:查询量下降约 90%(团队测量)。

案例 2:SLO 仪表盘的 30 天子查询

问题:avg_over_time((sum(rate(errors[5m])) / sum(rate(requests[5m])))[30d:5m]) 每次打开都超时。做法:把内层比值做成 recording rule job:slo_errors_per_request:ratio_rate5m,30 天窗口直接对规则序列 avg_over_time;更长期的数据交给第 6 课的 Thanos/Mimir 下采样。

案例 3:变量查询比面板还慢

问题:仪表盘变量 label_values(pod)(没有指标名)每次刷新都扫描全部序列。做法:改为 label_values(kube_pod_info{namespace="$namespace"}, pod),并设置变量刷新为 “On dashboard load”。

常见错误与解决

query processing would load too many samples into memory in query execution

段:L7。原因:峰值样本数超过 --query.max-samples(默认 5000 万)。诊断:同一查询缩小范围加 stats=all 观察 peakSamples 随范围的增长;看选中序列数。修复:recording rule、收窄选择器、增大 step、缩短范围。调大上限前先评估 Prometheus 内存余量。

query timed out in expression evaluation

原因:超过 --query.timeout(默认 2m),或在高峰期排队(queue_time 计入总时间)。诊断:pq 'prometheus_engine_query_duration_seconds{quantile="0.99"}'、pq 'prometheus_engine_queries'。修复:同上;并减少仪表盘并发。

exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)

原因:range / step > 11 000(例如 7 天、step 30s = 20 161 点)。修复:增大 step;Grafana 中检查面板的 Min interval 与 Max data points,不要写死很小的 step。

bad_data: invalid parameter "query": 1:12: parse error: unexpected …

原因:语法错误或 URL 编码错误(+ 被当作空格)。修复:curl 使用 --data-urlencode;Prometheus UI 的编辑器会给出语法提示;/api/v1/parse_query 与 /api/v1/format_query 可做格式检查。

found duplicate series for the match group {…} on the right hand-side of the operation / multiple matches for labels: many-to-one matching must be explicit (group_left/group_right)

原因:二元运算两侧的匹配标签不唯一(常见于 kube-state-metrics 的 info 指标 join,或 Pod 重建时新旧两条序列短暂并存)。修复:用 on(...) 限定匹配标签、group_left 指定多对一,并对 info 指标先 max by (…) 去重。这类错误常在“有时报错有时正常”的面板中出现。

命令行操作题
1. 把下面的 P99 查询改写为更便宜的形式:histogram_quantile(0.99, rate(myapp_http_request_duration_seconds_bucket[5m]))(只需要整体 P99)。
histogram_quantile(0.99, sum by (le) (rate(myapp_http_request_duration_seconds_bucket[5m])))

先按 le 聚合再计算分位数;进一步可做成 recording rule job:myapp_http_request_duration_seconds_bucket:rate5m(保留 le)。

2. 用 API 获取一次范围查询的 seriesTouched 与 peakSamples。
curl -s "$P/api/v1/query_range" --data-urlencode 'query=sum(rate(faultexp_http_requests_total[5m]))' \
  -d start=$(( $(date +%s)-3600 )) -d end=$(date +%s) -d step=30 -d stats=all | jq '.data.stats.samples | {seriesTouched, peakSamples, totalQueryableSamples}'
场景分析题
平台团队提议把 --query.max-samples 从 5000 万调到 5 亿,“因为业务方的大屏总报错”。你怎么评估?

max-samples 是防止单个查询吃光内存的保险丝:每个样本在内存中约十几字节以上,5 亿样本意味着单个查询可能占用数 GiB,并发几个就能让 Prometheus OOM——影响的是所有告警。应先用 query log 找出是哪个面板、哪条查询;用 recording rule 或缩小范围解决;长范围分析交给 Thanos/Mimir(带下采样与查询切分)。如果确需调大,结合 Prometheus 内存余量、maxConcurrency 一起评估,并为大屏使用独立的只读副本或查询前端。

经核实的教学视频

▶
PromCon 2024 - Inside a PromQL Query: Understanding the Mechanics — Prometheus Monitoring
英文 · PromQL 查询的内部执行过程
▶
PromCon EU 2022: Anatomy of a Slow Query, and Lessons Learned Building Query Acceleration Techniques — Prometheus Monitoring
英文 · 慢查询剖析与加速技巧
▶
Optimizing PromQL Queries - Aliaksandr Valialkin - PromCon 2024 Lightning Talk — Prometheus Monitoring
英文 · 闪电演讲,PromQL 优化要点

官方文档

视频分镜脚本(约 90 秒)

镜头 1 · 0–25s
画面:一个查询被拆成三个乘数:序列 8000 × 每步 20 样本 × 721 步,结果数字飞速增长并撞上 “max-samples” 红线。
旁白:查询成本是一个乘法,任何一个乘数变小,查询就变快。
镜头 2 · 25–60s
画面:recording rule 像预制菜一样每 30 秒做好一份,面板直接取用;stats 对比 4000 条变 1 条。
旁白:最有效的优化是 recording rule。
镜头 3 · 60–90s
画面:40 个浏览器同时刷新,查询队列排满;刷新间隔改为一分钟后队列清空。
旁白:慢的往往不是单个查询,而是查询的数量。
或在“测验”中取得 ≥ 70% 的分数

模块 5 · TSDB 内部:head block、WAL、压缩与磁盘

28:00 – 35:00 · 理解样本从内存到磁盘的旅程,就能解释“为什么重启要等十分钟”“为什么内存三小时后才降”“为什么磁盘超过了保留期”
7 分钟v3.16.0 tsdb/核心动画★★★★☆
学习目标
  • 画出数据目录:持久化块(meta.json、index、chunks/、tombstones)、chunks_head/(m-map 的 head chunks)、wal/(128 MiB 段 + checkpoint.N)。
  • 解释 head 的生命周期:样本写入 head chunk(目标 120 个样本)与 WAL → 满的 chunk m-map 到磁盘 → head 跨度超过 1.5 × 2h 时把最老的 2h 持久化成块 → head 截断 + GC → WAL 前 2/3 段做 checkpoint。
  • 解释压缩层级(2h → 6h → 18h → 54h…,最大块 = min(保留期 × 10%, 31d))、时间 / 大小 / 百分比保留的语义(整块删除;大小保留包含 WAL 与 head chunks)。
  • 根据日志与指标诊断:WAL 回放慢、压缩失败、磁盘写满、乱序样本被丢弃。
前置知识:模块 3。重要程度:★★★★☆

What:数据目录(kps 中为 /prometheus)

/prometheus
├── 01JD6Z…/                 # 持久化块(ULID 命名,按时间排序)
│   ├── meta.json           # minTime/maxTime、stats、compaction.level、sources
│   ├── index               # 序列标签 + 倒排索引(postings)
│   ├── chunks/000001       # 压缩后的样本(XOR 编码)
│   └── tombstones          # 删除标记(admin API 删除序列时)
├── chunks_head/            # head 中“已写满”的 chunk,m-map 到内存
│   ├── 000001
│   └── 000002
├── wal/
│   ├── 00000021            # WAL 段,默认 128 MiB(tsdb/wlog DefaultSegmentSize)
│   ├── 00000022
│   └── checkpoint.00000020 # 截断时把仍存活的序列与样本压缩成的检查点
├── lock
└── queries.active          # 正在执行的查询(崩溃后启动时会打印出来,帮助定位“致命查询”)

How:样本的旅程(v3.16.0 tsdb/head.go、tsdb/db.go)

  1. 追加:抓取的一批样本先写入 WAL(Series 记录:首次出现的序列;Samples 记录:样本),再写入每条序列的 head chunk。WAL 默认压缩(--storage.tsdb.wal-compression 默认 true,算法 snappy,可选 zstd)。
  2. m-map:一个 head chunk 写满(目标 --storage.tsdb.samples-per-chunk=120 个样本,15s 间隔约 30 分钟)后被写到 chunks_head/ 并 m-map,内存中只保留“正在写的”chunk。
  3. 压缩(compaction):head 的块范围是 2h(--storage.tsdb.min-block-duration,隐藏参数,仅测试用)。当 head 跨度 > 2h × 1.5 = 3h(compactable()),把最老的完整 2h 范围写成一个持久化块(日志 write block started、Head portion block created)。
  4. 截断与 GC:块写好后,head 截断到新的最小时间,GC 删除已不活跃的序列(日志 Head GC completed)——churn 产生的序列在这一刻才释放内存。
  5. WAL checkpoint:把 WAL 前 2/3 的段(last = first + (last-first)*2/3)中仍需要的数据写入 checkpoint.N,删除旧段(日志 WAL checkpoint complete)。
  6. 块合并:后台把相邻的小块合并成大块:范围按 ×3 增长(2h、6h、18h、54h…),上限 = min(保留期的 10%, 31d)(kps 默认保留 10d → 最大块 1d,所以实际最大是 18h 块)。合并减少索引重复与文件数。
  7. 保留:按时间(kps 默认 retention: 10d;Prometheus 自身默认 15d)、大小(retentionSize)或磁盘百分比(3.x 新增 retention.percentage)删除整个最老的块。大小保留统计“WAL + head chunks + 所有块”。
  8. 启动回放:重启时依次加载 m-map chunks(Replaying on-disk memory mappable chunks if any)→ checkpoint(WAL checkpoint loaded)→ 剩余 WAL 段(Replaying WAL, this may take a while / WAL segment loaded)→ WAL replay completed。回放期间 /-/ready 返回未就绪,/api/v1/status/walreplay 显示进度。

Why:这些机制解释了哪些现象

现象机制解释
停止 churn 后内存不降,约 1–3 小时后突然下降不活跃序列要等下一次 head 压缩后的 GC 才释放
重启后 10 分钟没有数据WAL 回放:时长与 WAL 中的序列数、样本数成正比(基数越高越慢)
保留期 10d,却能查到 11 天前的数据按块删除:块的 maxTime 早于保留边界时才删除整个块
磁盘占用 = 块 + 约 3 小时的 WALWAL 覆盖 head 尚未持久化的部分,并有 checkpoint
“out of bounds” 样本被丢弃未开启乱序写入时,早于 head 最小有效时间的样本会被拒绝(prometheus_target_scrapes_sample_out_of_bounds_total)

When:需要调整什么

  • 保留:kps 中用 prometheus.prometheusSpec.retention / retentionSize / retentionPercentage。注意:3.16 中 --storage.tsdb.retention.time/size 命令行参数已标记 DEPRECATED,推荐写进配置文件 storage.tsdb.retention;Operator 生成的方式以 Operator 版本为准,作为用户只改 CR 字段即可。
  • 乱序写入:remote write 接收端、回填或多源推送时才需要 storage.tsdb.out_of_order_time_window(配置文件;Operator:tsdb.outOfOrderTimeWindow);普通抓取不需要。
  • 磁盘:retentionSize 设为 PV 容量的 80% 左右作为“保险丝”;告警 predict_linear(kubelet_volume_stats_available_bytes[6h], 24*3600) < 0(kps 自带类似的 KubePersistentVolumeFillingUp)。
  • 内存快照:--enable-feature=memory-snapshot-on-shutdown 让正常关闭时写快照,下次启动跳过大部分 WAL 回放(对 OOM 这种非正常退出无效)。
常见误解① “WAL 越大越安全,可以调大保留”——WAL 只覆盖 head,不影响保留。② “删除 WAL 只会丢最近几分钟”——会丢 head 中所有尚未持久化的数据(最多约 3 小时)。③ “保留期是精确的”——按块删除,存在最多一个块范围的偏差。④ “Prometheus 支持多个实例共享一个数据目录”——不支持,lock 文件就是为了防止这种情况;NFS 等非 POSIX 文件系统也不受支持。⑤ “compaction 失败只是警告”——持续失败会让 head 不断增长直到 OOM,必须告警 prometheus_tsdb_compactions_failed_total。

head、WAL 与块的关系

抓取 / 规则Appender.Commit WAL(磁盘,顺序写)Series / Samples 记录128 MiB 段 + checkpoint Head(内存)memSeries + 倒排索引每序列 1 个活动 chunk跨度 ≤ ~3h chunks_head/写满的 chunkm-map(120 样本) 持久化块 2hindex + chunks + meta.json不可变 合并块 6h / 18h …≤ min(保留×10%, 31d) head 跨度 > 3h → 最老 2h 写成块 重启回放:chunks_head(m-map)→ WAL checkpoint → 剩余 WAL 段 → ready回放耗时 ∝ WAL 中的序列与样本数 —— 基数爆炸让重启变慢
图 5-1 WAL 保证崩溃不丢数据,head 提供写入与最近数据的查询,块提供长期存储

时间轴:一次 head 压缩

00:0002:0004:0006:0008:00 块 00–02 块 02–04 head 04:00–07:05(跨度 3h05m > 3h) 新块 04–06 head 06–07:05 之后:head 截断 → GC 释放不活跃序列 → WAL checkpoint;三个相邻 2h 块稍后合并为 6h 块
图 5-2 head 总是保留最近 1–3 小时;压缩每 2 小时左右发生一次

核心动画:TSDB head / WAL / compaction

模拟一个每 15 秒抓取一次的 Prometheus。每点一次“下一步”时间前进一段,观察 head chunk 写满并 m-map、WAL 段增长、head 跨度超过 3h 时压缩、截断、GC 与 checkpoint;也可以点击“OOM 崩溃并重启”观察 WAL 回放顺序。勾选 churn 看 GC 前后的序列数差异。日志行均取自 v3.16.0 源码中的真实日志消息。

Head(内存)
head 序列数
当前 head chunk 样本(目标 120)
chunks_head/(m-map)
wal/
持久化块
点击“下一步”开始。
$ # Prometheus 日志(slog 格式,节选)

核心命令与指标

命令 / 指标说明
curl -s $P/api/v1/status/tsdb/blocks | jq所有块的 ulid、minTime、maxTime、stats、compaction.level
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheus块列表(人类可读大小);distroless 镜像中可用
curl -s $P/api/v1/status/walreplay回放进度 {min, max, current}(段号)
prometheus_tsdb_head_series、prometheus_tsdb_head_chunks、prometheus_tsdb_head_chunks_storage_size_byteshead 规模与 chunks_head 磁盘占用
prometheus_tsdb_wal_storage_size_bytes、prometheus_tsdb_wal_segment_current、prometheus_tsdb_wal_fsync_duration_secondsWAL 大小、当前段号、fsync 延迟(磁盘慢的信号)
prometheus_tsdb_storage_blocks_bytes、prometheus_tsdb_retention_limit_bytes、prometheus_tsdb_lowest_timestamp块占用、大小保留上限、最早数据时间
prometheus_tsdb_compactions_total、prometheus_tsdb_compactions_failed_total、prometheus_tsdb_compaction_duration_seconds压缩次数、失败、耗时
prometheus_tsdb_head_truncations_failed_total、prometheus_tsdb_checkpoint_creations_failed_total、prometheus_tsdb_wal_corruptions_total截断、checkpoint 失败与 WAL 损坏
prometheus_tsdb_time_retentions_total、prometheus_tsdb_size_retentions_total按时间 / 大小删除块的次数
source ~/promlab/faultlab/env.sh
curl -s $P/api/v1/status/tsdb/blocks | jq -r '.data.blocks[] | [.ulid, (.minTime/1000|todate), (.maxTime/1000|todate), .stats.numSeries, .compaction.level] | @tsv'
curl -s "$P/api/v1/status/tsdb" | jq '.data.headStats | {numSeries, chunkCount, min: (.minTime/1000|todate), max: (.maxTime/1000|todate)}'
pq 'prometheus_tsdb_wal_storage_size_bytes / 2^20'
pq 'prometheus_tsdb_storage_blocks_bytes / 2^20'
01JD2…	2026-11-14T00:00:00Z	2026-11-14T18:00:00Z	61002	3
01JD5…	2026-11-14T18:00:00Z	2026-11-15T12:00:00Z	60488	3
01JD8…	2026-11-15T12:00:00Z	2026-11-15T18:00:00Z	60112	2
01JD9…	2026-11-15T18:00:00Z	2026-11-15T20:00:00Z	60030	1
{"numSeries":61234,"chunkCount":132011,"min":"2026-11-15T20:00:00Z","max":"2026-11-15T22:41:05Z"}
[{...},"58.3"]
[{...},"412.9"]

如何读:level 1 = 由 head 直接写出的 2h 块,level 2 = 6h,level 3 = 18h;head 的 min 正好是最后一个块的 max。

压缩与回放相关日志

kubectl -n monitoring logs $PROM_POD -c prometheus --since=6h \
  | grep -E 'write block|Head portion block created|compact blocks|Head GC completed|WAL checkpoint complete|Deleting obsolete block' | tail -8
time=2026-11-15T22:00:03Z level=INFO source=compact.go:689 msg="write block started" component=tsdb mint=1763236800000 maxt=1763244000000 ulid=01JD9…
time=2026-11-15T22:00:04Z level=INFO source=db.go:1856 msg="Head portion block created" component=tsdb ulids=[01JD9…] ...
time=2026-11-15T22:00:04Z level=INFO source=head.go:1806 msg="Head GC completed" component=tsdb caller=truncateMemory duration=21.4ms
time=2026-11-15T22:00:05Z level=INFO source=head.go:1760 msg="WAL checkpoint complete" component=tsdb first=18 last=20 duration=402ms
time=2026-11-15T22:00:09Z level=INFO source=compact.go:… msg="compact blocks" component=tsdb count=3 mint=… maxt=… ulid=01JD8… sources=[…] duration=1.1s

实验 5:读懂 TSDB,并观察一次 WAL 回放(约 7 分钟)

块与 head:执行“命令”分页的块列表与 headStats 命令,回答:最后一个块的 maxTime 与 head 的 minTime 是否相等?最大的 compaction level 是多少?(kps 默认保留 10d → 最大块 1 天 → 最高能到 18h 块,即 level 3)。
制造一些 churn 让回放更明显(可选):
kubectl -n faultlab set env deploy/faultexp SERIES=1000 CHURN=1
sleep 240
pq 'prometheus_tsdb_head_series'
强制杀死 Prometheus(模拟 OOM),观察回放:
kubectl -n monitoring delete pod $PROM_POD --grace-period=0 --force
sleep 5
kubectl -n monitoring logs -f $PROM_POD -c prometheus | grep -E 'Replaying|replay|WAL segment loaded|checkpoint loaded|Server is ready|unclean' &
LOGPID=$!
until curl -s $P/-/ready | grep -q Ready; do curl -s $P/api/v1/status/walreplay; echo; sleep 2; done
kill $LOGPID
time=… level=INFO source=head.go:762 msg="Replaying on-disk memory mappable chunks if any" component=tsdb
time=… level=INFO source=head.go:847 msg="On-disk memory mappable chunks replay completed" component=tsdb duration=…
time=… level=INFO source=head.go:855 msg="Replaying WAL, this may take a while" component=tsdb
time=… level=INFO source=head.go:914 msg="WAL checkpoint loaded" component=tsdb
time=… level=INFO source=head.go:950 msg="WAL segment loaded" component=tsdb segment=21 maxSegment=23 …
time=… level=INFO source=head.go:950 msg="WAL segment loaded" component=tsdb segment=23 maxSegment=23 …
time=… level=INFO source=head.go:988 msg="WAL replay completed" component=tsdb checkpoint_replay_duration=… wal_replay_duration=… total_replay_duration=4.2s
time=… level=INFO … msg="Server is ready to receive web requests."
{"status":"success","data":{"min":20,"max":23,"current":22}}

强制删除后 port-forward 会断开,需要重新执行 ~/promlab/faultlab/pf.sh(Pod 名不变,StatefulSet 会以相同名字重建)。回放期间端口转发可能连接失败,循环会继续重试。kind 上通常几秒;生产中几百万序列可能需要十几分钟。

数一数空窗:在 Prometheus UI 中画 up{job="faultexp"},能看到 Pod 重启期间的空洞。kps 默认单副本 Prometheus;生产中用 2 个副本 + Thanos/Mimir 去重(第 6 课)消除空窗。
复位:kubectl -n faultlab set env deploy/faultexp SERIES- CHURN-。

案例 1:OOM → 回放 → 再 OOM 的死循环

问题:基数事故后 Prometheus 每次启动回放到 70% 就被 OOMKilled。做法:① 临时把内存 limit 提高 50% 让回放完成;② 回放完成后立即丢弃元凶指标;③ 等下一次 head 压缩后恢复 limit。如果无法提高内存:先备份 wal/ 再移走它启动(接受丢失 head 中约 2–3 小时数据),这需要业务方签字确认。预防:enforcedSampleLimit + head 序列告警 + memory-snapshot-on-shutdown(对正常重启有效)。

案例 2:磁盘写满后不再接收数据

问题:PV 50 GiB,保留 30d,业务增长后磁盘写满,日志出现 no space left on device,WAL 无法写入,抓取全部失败。做法:扩容 PV(StorageClass 支持 allowVolumeExpansion 时修改 Prometheus CR 的 storage 请求或按 Operator 文档处理 StatefulSet 卷扩容),并设置 retentionSize: 40GiB 作为保险丝。教训:只用时间保留就没有“磁盘上限”,必须两者都设。

案例 3:压缩持续失败,head 一直增长

问题:prometheus_tsdb_compactions_failed_total 每 2 小时 +1,head 跨度越来越长,内存持续上涨。日志显示块目录中有一个残缺块(之前磁盘满时写了一半)。做法:把残缺块移出数据目录后重启,压缩恢复。预防:kps 自带 PrometheusTSDBCompactionsFailing 告警,确保它路由到值班人员。

常见错误与解决

Prometheus 启动后长时间不 Ready,日志停在 "Replaying WAL, this may take a while"

原因:WAL 很大(高基数 / churn / 长时间没有压缩)。诊断:curl -s $P/api/v1/status/walreplay 看段号进度;kubectl top pod 看内存是否逼近 limit。处理:耐心等待并确保内存足够;startupProbe / readinessProbe 不要太激进(Operator 默认的 startupProbe 已为回放预留较长时间)。

Encountered WAL read error, attempting repair

原因:上次非正常退出导致 WAL 末尾损坏。Prometheus 会截断到损坏处并继续(日志 Successfully repaired WAL),损坏点之后的数据丢失。诊断:prometheus_tsdb_wal_corruptions_total。预防:避免 SIGKILL(给足 terminationGracePeriodSeconds),使用可靠的块存储。

… write /prometheus/wal/00000123: no space left on device

处理:扩容卷;临时可删除最老的块目录(整块删除,数据永久丢失,先备份或确认已上传到长期存储);不要先删 WAL。预防:同时设置 retention 与 retentionSize;磁盘预测告警。

日志 Error on ingesting samples that are too old or are too far into the future / out of bounds 计数增长

原因:目标自带时间戳且时间落后(或节点时钟漂移),样本早于 head 的最小有效时间。诊断:pq 'rate(prometheus_target_scrapes_sample_out_of_bounds_total[5m])'、比较目标所在节点与 Prometheus 所在节点的时钟。修复:修 NTP;去掉 exporter 的时间戳;确有需要的场景(回填、remote write 接收)才开启 out_of_order_time_window。

保留期已过但磁盘没有下降

原因:按块删除:大块(例如 18h 块)要等其 maxTime 也超出保留期才删除;或 head/WAL 本身很大。诊断:块列表的 maxTime 与 prometheus_tsdb_lowest_timestamp。

命令行操作题
1. 列出每个块的时间范围、序列数与 compaction level。
curl -s $P/api/v1/status/tsdb/blocks | jq -r '.data.blocks[] | [(.minTime/1000|todate), (.maxTime/1000|todate), .stats.numSeries, .compaction.level] | @tsv'
2. 写一条告警:TSDB 压缩在过去 3 小时内失败过。
increase(prometheus_tsdb_compactions_failed_total[3h]) > 0
场景分析题
你停止了一个 churn 严重的 exporter,但 Prometheus 内存 2 小时后才下降。业务方认为“Prometheus 内存泄漏”。请解释并给出验证方法。

不是泄漏:不活跃序列仍留在 head 中,直到 head 跨度超过 3h 触发压缩,最老的 2h 被持久化,随后 head 截断与 GC 才删除这些序列并释放内存。验证:对比 prometheus_tsdb_head_series 的下降时刻与日志中的 Head GC completed、write block started 时刻,以及 prometheus_tsdb_head_series_removed_total 的增长。Go 运行时把内存还给操作系统还有额外延迟,所以 RSS 可能比 head 序列数下降得更晚。

经核实的教学视频

▶
SREcon22 Asia/Pacific - Lifecycle of a Sample in the Prometheus TSDB — USENIX
英文 · TSDB 维护者讲解样本从 head、WAL 到块的完整生命周期,与本模块动画对应
▶
Lifecycle of a Sample in the Prometheus TSDB - Ganesh Vernekar — FOSSASIA
英文 · 同一主题的另一场演讲
▶
PromCon Online 2020 - TSDB WTF, Ian Billett, Improbable — Prometheus Monitoring
英文 · 生产中遇到的 TSDB 怪现象与解释
▶
PromCon 2016: The Prometheus Time Series Database - Björn Rabenstein — Prometheus Monitoring
英文 · 历史背景(Prometheus 1.x 存储,现已被 2.x/3.x TSDB 取代,仅作对比)

官方文档

视频分镜脚本(约 100 秒)

镜头 1 · 0–25s
画面:一个样本同时落入两个地方:磁盘上的 WAL 日志条和内存中的 head chunk。
旁白:每个样本先写 WAL 保证不丢,再写进内存中的 head。
镜头 2 · 25–55s
画面:head chunk 装满 120 个样本后“啪”地贴到 chunks_head 目录;head 时间条拉长到三小时,最老两小时被切下来压成一个块。
旁白:head 超过三小时,最老的两小时就被写成不可变的块。
镜头 3 · 55–80s
画面:GC 扫帚扫走灰色的不活跃序列,内存条下降;WAL 前三分之二段被折叠成 checkpoint。
旁白:直到这一刻,churn 留下的序列才真正释放。
镜头 4 · 80–100s
画面:进程崩溃,重启后进度条依次走过 m-map chunks、checkpoint、WAL 段。
旁白:重启要回放 WAL,基数越高回放越慢。
或在“测验”中取得 ≥ 70% 的分数

模块 6 · 告警不触发或告警风暴

35:00 – 42:00 · 告警链路有七道关:规则加载、评估、表达式结果、for、发送、Alertmanager 处理、接收器。不响时逐关检查;响太多时从分组、抑制与阈值三处治理
7 分钟Alertmanager v0.35.0 · amtool★★★★★
学习目标
  • 沿七道关诊断“告警没有通知”:规则是否加载(/rules)→ health 与 lastError → 表达式是否返回序列 → for 是否满足(pending)→ Prometheus 是否发到 Alertmanager → Alertmanager 中是否被静默 / 抑制 / 路由到 null → 接收器是否发送成功。
  • 认识 kps 默认 Alertmanager 配置:group_by: ['namespace']、group_wait 30s、group_interval 5m、repeat_interval 12h,默认接收器 null(不发送任何通知),Watchdog 路由到 null,以及基于 severity 的抑制规则。
  • 治理告警风暴:合理的 group_by、抑制规则(共因抑制症状)、for 与 keep_firing_for 防抖、症状告警优先于原因告警。
前置知识:第 2 课告警生命周期与 Alertmanager 路由。重要程度:★★★★★

What:告警链路的七道关

#关卡失败表现观察窗口
1规则加载(kps:PrometheusRule 被 ruleSelector 选中 → Operator 校验 → 写入规则 ConfigMap → reloader 重载)/rules 中没有这条规则/api/v1/rules、Operator 事件、PrometheusOperatorRejectedResources、prometheus_config_last_reload_successful
2评估(每 evaluation_interval,kps 默认 30s)health = err,lastError 有内容prometheus_rule_evaluation_failures_total
3表达式结果health = ok,但永远 inactive:表达式返回空把 expr 粘到 UI 执行
4for 持续时间反复 pending → inactive(flapping),从不 firingALERTS{alertstate="pending"} 的历史
5发送到 Alertmanager(每 --rules.alert.resend-delay=1m 重发,队列 --alertmanager.notification-queue-capacity=10000)Prometheus 中 firing,Alertmanager 中没有prometheus_notifications_alertmanagers_discovered、_errors_total、_dropped_total、_queue_length
6Alertmanager:去重 → 静默 → 抑制 → 路由 → 分组等待Alertmanager 中可见但 suppressed,或路由到 nullamtool alert query -s -i、amtool config routes test、AM UI
7接收器(webhook、邮件、Teams、PagerDuty…)AM 认为已发送,接收方没收到alertmanager_notifications_failed_total{integration}、AM 日志

Why:最常见的四个“不响”原因

  1. 表达式在故障时返回空:up == 0 在目标消失时为空(模块 1);rate(x[1m]) 在抓取间隔 30s 时只有两个样本、抖动时为空;标签匹配写错;指标在故障时根本不输出(应用挂了就不会输出 errors_total)。
  2. 规则没有加载:kps 默认 ruleSelectorNilUsesHelmValues: true → 只加载带 release: kps 的 PrometheusRule;PromQL 语法错误时 Operator 拒绝整个资源。
  3. for 太长或数据抖动:pending 期间只要有一次评估返回空,状态回到 inactive,计时重来。
  4. Alertmanager 吞掉了:kps 默认路由的接收器就是 null;过宽的静默(namespace=~".+");抑制规则 equal 标签不完整导致误抑制。

How:告警风暴的三种治理

手段作用示例
分组 group_by同组告警合并为一条通知;组内新增告警等 group_interval 再发按 ['namespace','alertname'] 而不是 ['...'](每条告警单独成组)或 instance
抑制 inhibit_rules“原因”告警存在时压制“症状”告警NodeDown 抑制同节点上所有 Pod 告警(equal: [node]);kps 默认 critical 抑制同 namespace + alertname 的 warning/info
防抖避免阈值附近反复触发与恢复for: 5m;Prometheus 2.42+ 的 keep_firing_for: 10m(条件消失后继续 firing 一段时间);使用更长的 rate 窗口

When:值班手册中的“告警不响”检查顺序

从 Prometheus 往外查:/rules 有没有 → health → UI 执行 expr → ALERTS → Alertmanager UI/amtool → 接收器日志。每一步都能用只读方式完成,前 4 步不涉及 Alertmanager。

对比:Prometheus 告警状态与 Alertmanager 状态

Prometheus(规则)Alertmanager(告警实例)
inactive / pending / firingactive / suppressed(silenced 或 inhibited)/ unprocessed
firing 告警每 resend-delay 重发一次,带 endsAt未在 endsAt 前续期 → 视为 resolved(resolve_timeout 用于没有 endsAt 的告警)
重启后通过 ALERTS_FOR_STATE 恢复 for 进度(--rules.alert.for-outage-tolerance 默认 1h)静默与通知日志保存在本地数据卷,集群间 gossip 同步
常见误解① “kps 装好就会发通知”——默认接收器是 null,必须配置自己的接收器。② “规则 health = ok 就说明会响”——ok 只表示评估没有出错,表达式可能一直为空。③ “告警恢复了 Alertmanager 立刻发 resolved”——取决于 send_resolved 与 group_interval。④ “静默可以无限期”——静默必须有到期时间,并写清创建人与原因;过期静默是事故复盘中最常见的发现之一。⑤ “抑制规则的 equal 留空更省事”——留空意味着任意一个 source 告警会抑制所有匹配 target 的告警。

七道关

① 加载ruleSelector ② 评估health ③ 结果非空? ④ forpending ⑤ 发送notifier ⑥ AM 处理静默·抑制·路由 ⑦ 接收器webhook… /rules 无lastErrorUI 执行为空抖动重置dropped/errorssuppressed / nullfailed_total Prometheus 内部(/rules、ALERTS)前四关不涉及 Alertmanager Alertmanager(amtool、AM UI)kps 默认接收器 = null
图 6-1 从左往右逐关检查,第一处异常就是答案

风暴治理:分组与抑制

NodeNotReady node=w1 PodNotReady × 25(w1 上) TargetDown × 18(w1 上) HighLatency × 6(症状) inhibit_rulessource: alertname=NodeNotReadytarget: severity=~warning|infoequal: [node] 通知 1:NodeNotReady w1(critical) 通知 2:HighLatency(按 namespace 分组) 50 条告警 → 2 条通知;被抑制的 43 条在 AM 中仍可见(state=suppressed),恢复后自动解除
图 6-2 抑制规则需要原因告警与症状告警共享 equal 中的标签(例如 node)

交互:告警链路逐关检查器 + 分组计算器

上半部分:选择一种“告警不响”的故障,逐步模拟 Prometheus 规则评估与 Alertmanager 处理,看在哪一关停下。下半部分:输入告警数量与 group_by,估算会产生多少条通知。

选择故障后点击“逐关检查”。
$ # 诊断命令与输出

$ # 通知数估算

核心命令

命令关说明
curl -s "$P/api/v1/rules?type=alert" | jq …①②规则是否存在、health、lastError、state、evaluationTime
pq 'ALERTS{alertname="X"}'③④pending/firing 的实例(带全部标签)
curl -s $P/api/v1/alertmanagers | jq⑤Prometheus 发现的 Alertmanager(activeAlertmanagers)
kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093 alert query -s -i⑥列出告警,包括被静默(-s)与被抑制(-i)的
… amtool --alertmanager.url=http://localhost:9093 silence query⑥当前静默;silence expire <ID> 解除
… amtool --alertmanager.url=http://localhost:9093 config routes test namespace=faultlab severity=critical⑥给定标签会匹配哪个接收器
… amtool --alertmanager.url=http://localhost:9093 config routes show⑥打印路由树
pq 'rate(alertmanager_notifications_failed_total[5m])'⑦按 integration 统计发送失败
source ~/promlab/faultlab/env.sh
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[] | select(.name=="faultexp.rules") | .rules[] | [.name, .health, .state, (.lastError // "")] | @tsv'
curl -s $P/api/v1/alertmanagers | jq -r '.data.activeAlertmanagers[].url'
AMT="kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093"
$AMT config routes show
$AMT config routes test namespace=faultlab alertname=FaultexpHighErrorRate severity=critical
FaultexpDown	ok	inactive
FaultexpAbsent	ok	inactive
FaultexpHighErrorRate	ok	inactive
http://10.244.0.21:9093/api/v2/alerts
Routing tree:
└── default-route  receiver: null
    └── {alertname="Watchdog"}  receiver: null
null

最后一行 null 说明:即使告警 firing,kps 默认配置也不会通知任何人。常见错误:在 Prometheus 侧排查半天,其实是路由问题。生产用途:把 amtool config routes test 放进 Alertmanager 配置变更的 CI。

实验 6:一条“永远不响”的告警,以及路由与静默(约 10 分钟)

部署一个 webhook 接收器并路由 faultlab 的告警:
apiVersion: v1
kind: ConfigMap
metadata: {name: amsink-code, namespace: faultlab}
data:
  sink.py: |
    import json
    from http.server import BaseHTTPRequestHandler, HTTPServer
    class H(BaseHTTPRequestHandler):
        def do_POST(self):
            d = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
            print(d.get("status"), json.dumps(d.get("groupLabels")),
                  [a["labels"].get("alertname") for a in d.get("alerts", [])], flush=True)
            self.send_response(200); self.end_headers()
        def log_message(self, *a): pass
    HTTPServer(("", 8080), H).serve_forever()
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: amsink, namespace: faultlab}
spec:
  selector: {matchLabels: {app: amsink}}
  template:
    metadata: {labels: {app: amsink}}
    spec:
      containers:
        - name: sink
          image: python:3.13-alpine
          command: ["python", "-u", "/app/sink.py"]
          ports: [{containerPort: 8080}]
          volumeMounts: [{name: code, mountPath: /app}]
      volumes: [{name: code, configMap: {name: amsink-code}}]
---
apiVersion: v1
kind: Service
metadata: {name: amsink, namespace: faultlab}
spec:
  selector: {app: amsink}
  ports: [{port: 8080}]
# 完整替换 kps 的 alertmanager.config(Helm 对列表是整体替换,不是合并)
alertmanager:
  config:
    global: {resolve_timeout: 5m}
    inhibit_rules:
      - source_matchers: ['severity = critical']
        target_matchers: ['severity =~ warning|info']
        equal: ['namespace', 'alertname']
      - source_matchers: ['severity = warning']
        target_matchers: ['severity = info']
        equal: ['namespace', 'alertname']
      - source_matchers: ['alertname = InfoInhibitor']
        target_matchers: ['severity = info']
        equal: ['namespace']
      - target_matchers: ['alertname = InfoInhibitor']
    route:
      group_by: ['namespace', 'alertname']
      group_wait: 30s
      group_interval: 5m
      repeat_interval: 12h
      receiver: 'null'
      routes:
        - receiver: 'null'
          matchers: ['alertname = "Watchdog"']
        - receiver: faultlab-sink
          matchers: ['namespace = "faultlab"']
          group_wait: 10s
          group_interval: 1m
    receivers:
      - name: 'null'
      - name: faultlab-sink
        webhook_configs:
          - url: http://amsink.faultlab:8080/
            send_resolved: true
    templates: ['/etc/alertmanager/config/*.tmpl']
kubectl apply -f ~/promlab/faultlab/amsink.yaml
helm upgrade kps prometheus-community/kube-prometheus-stack -n monitoring --version 93.3.0 --reuse-values -f ~/promlab/faultlab/am-values.yaml
sleep 60
$AMT config routes test namespace=faultlab alertname=FaultexpHighErrorRate severity=critical
faultlab-sink

PrometheusRule 中的告警没有 namespace 标签时,告警会继承表达式结果中的 namespace(来自目标标签);sum(…) 聚合掉所有标签后 namespace 会消失——这正是下一步要遇到的坑。

注入:开启错误流量,等待告警:
kubectl -n faultlab set env deploy/faultexp ERRORS=1
sleep 240
pq 'ALERTS{alertname="FaultexpHighErrorRate"}'
kubectl -n faultlab logs deploy/amsink --tail=5
[{"__name__":"ALERTS","alertname":"FaultexpHighErrorRate","alertstate":"firing","severity":"critical"},"1"]
(amsink 没有任何输出)

告警在 Prometheus 中已经 firing,但 webhook 没收到。用 amtool 查路由:

$AMT alert query alertname=FaultexpHighErrorRate
$AMT config routes test alertname=FaultexpHighErrorRate severity=critical
Alertname              Starts At                Summary                         State
FaultexpHighErrorRate  2026-11-16 02:31:10 UTC  faultexp 5xx 比例 28.57%        active
null

根因:表达式用 sum(…) 聚合掉了 namespace,告警没有 namespace 标签 → 不匹配 faultlab 路由 → 落入默认 null。修复:sum by (namespace, job) (…) 保留路由所需的标签,或在规则 labels 中显式加 namespace: faultlab(kps 自带规则都保留了 namespace,因为默认 group_by 和抑制都依赖它)。

kubectl -n faultlab patch prometheusrule faultexp-rules --type=json -p '[{"op":"add","path":"/spec/groups/0/rules/3/labels/namespace","value":"faultlab"}]'
sleep 120; kubectl -n faultlab logs deploy/amsink --tail=3
firing {"alertname": "FaultexpHighErrorRate", "namespace": "faultlab"} ['FaultexpHighErrorRate']
“永远不响”:窗口过小——把表达式窗口改成 [10s](抓取间隔 15s)。
kubectl -n faultlab patch prometheusrule faultexp-rules --type=json -p '[{"op":"replace","path":"/spec/groups/0/rules/3/expr","value":"sum(rate(faultexp_http_requests_total{status=~\"5..\"}[10s])) / sum(rate(faultexp_http_requests_total[10s])) > 0.1"}]'
sleep 90
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[].rules[] | select(.name=="FaultexpHighErrorRate") | "\(.health) \(.state)"'
pq 'rate(faultexp_http_requests_total[10s])'
ok inactive
(无输出:10s 窗口内最多只有一个样本,rate 返回空)

health 是 ok——没有任何报错,告警就是不会响。护栏:在 CI 中对规则做 promtool test rules 单元测试(第 2 课),并约定 rate 窗口 ≥ 4 × 抓取间隔。复位:kubectl apply -f ~/promlab/faultlab/faultexp.yaml(恢复规则原样,同时会移除上一步添加的 namespace 标签——如需保留请修改文件)。

过宽的静默:
$AMT silence add 'namespace=~".+"' --comment="维护窗口" --duration=30m --author=oncall
$AMT alert query -s
$AMT silence query
$AMT silence expire $($AMT silence query -q)
3f1c2a9e-…
Alertname              Starts At                Summary   State
FaultexpHighErrorRate  …                        …         suppressed
ID                                    Matchers              Ends At                  Created By  Comment
3f1c2a9e-…                            namespace=~".+"       2026-11-16 03:10:00 UTC  oncall      维护窗口

一条 namespace=~".+" 的静默会压住整个集群的告警(Watchdog 也会被静默,外部死人开关会报警——这正是 Watchdog 的价值)。

复位:
kubectl -n faultlab set env deploy/faultexp ERRORS-
kubectl apply -f ~/promlab/faultlab/faultexp.yaml
# 保留 amsink 与路由供模块 8 使用;如需恢复 kps 默认 Alertmanager 配置,执行不带 -f am-values.yaml 的 helm upgrade 并显式提供原 values

案例 1:数据库挂了,告警却没响

问题:告警 rate(db_errors_total[5m]) > 10。数据库进程崩溃后 exporter 也随之停止输出 db_errors_total,表达式返回空。修复:增加 up{job="db"} == 0 与 absent(up{job="db"});业务侧用黑盒探测(blackbox_exporter)从用户视角检测。原则:“错误计数类”告警必须搭配“数据缺失类”告警。

案例 2:一次节点故障带来 400 条通知

问题:group_by 包含 pod,节点 NotReady 导致 120 个 Pod 告警各自成组,每组一条 Teams 消息。做法:group_by 改为 ['namespace','alertname'];新增抑制规则:KubeNodeNotReady 抑制同 node 的 warning/info 告警(需要 Pod 类告警带 node 标签,kps 规则中部分有、部分需要 join kube_pod_info)。结果:同类事件通知降到个位数。

案例 3:flapping 的磁盘告警

问题:磁盘使用率在 89%–91% 之间波动,阈值 90%、for: 0m,一天发 200 次 firing/resolved。做法:for: 15m + keep_firing_for: 30m;同时改用 predict_linear 预测“几小时内写满”,比静态阈值更有意义。

常见错误与解决

/rules 页面中找不到我的 PrometheusRule

诊断:kubectl get prometheus -n monitoring -o jsonpath='{..ruleSelector}' 与规则标签比对;kubectl get events -n <ns> --field-selector involvedObject.name=<rule> 看 Operator 是否因 PromQL 语法拒绝;pq 'prometheus_config_last_reload_successful'。修复:补 release: kps;本地用 promtool check rules 检查(PrometheusRule 需要先取出 spec 部分)。

vector contains metrics with the same labelset after applying alert labels

段:评估(health = err)。原因:规则的 labels 覆盖了表达式结果中用来区分序列的标签(例如两条结果只差 instance,规则又设置了 instance: x),产生重复标签集(v3.16.0 rules/alerting.go 的 ErrDuplicateAlertLabelSet)。recording rule 对应的报错是 … after applying rule labels。修复:不要在 labels 中覆盖维度标签,或先聚合。

告警一直 pending,从不 firing

原因:数据抖动导致某次评估返回空,pending 计时重置;或 for 长于故障持续时间。诊断:在 UI 中画 ALERTS{alertname="X"} 与表达式本身。修复:更长的 rate 窗口、max_over_time 平滑、合理的 for。

Prometheus 中 firing,Alertmanager UI 中看不到

诊断:curl -s $P/api/v1/alertmanagers 是否为空(kps 中由 alerting.alertmanagers 指向 alertmanager-operated);pq 'rate(prometheus_notifications_errors_total[5m])'、prometheus_notifications_dropped_total;Prometheus 日志中的 Error sending alerts 类消息;NetworkPolicy。

Alertmanager 显示已发送,Teams / Slack 没收到

诊断:pq 'increase(alertmanager_notifications_failed_total[1h])' 按 integration 看;AM 日志 kubectl -n monitoring logs $AM_POD -c alertmanager | grep -i notify;webhook URL 过期、代理、TLS。预防:对 alertmanager_notifications_failed_total 本身告警,并通过另一条通道发送。

同一条告警收到两次通知(Alertmanager HA)

原因:多个 Alertmanager 副本之间 gossip 集群没有组成(端口 9094 不通、peer 地址错误),各自独立发送。诊断:pq 'alertmanager_cluster_members' 应等于副本数;AM UI 的 Status 页面显示 cluster 状态。

命令行操作题
1. 用 amtool 检查 labels namespace=payments severity=warning alertname=HighLatency 会被路由到哪个接收器。
kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093 \
  config routes test namespace=payments severity=warning alertname=HighLatency
2. 列出所有 health 不是 ok 的规则及其 lastError。
curl -s "$P/api/v1/rules" | jq -r '.data.groups[].rules[] | select(.health!="ok") | [.name, .health, .lastError] | @tsv'
场景分析题
团队抱怨“告警太多没人看”,每天 300 条通知。你会如何系统地治理?

① 数据:从 Alertmanager 通知日志或 ALERTS 统计每个 alertname 的通知次数与平均持续时间,找出 Top 10。② 分类:持续时间短、自动恢复的是 flapping → 调 for / keep_firing_for / 窗口;同一事件触发多条的是缺分组或抑制 → 调 group_by、加共因抑制;无人处理的 → 降级为工单或仪表盘,或删除。③ 原则:告警基于症状(用户可感知的错误率、延迟、SLO burn rate,第 6 课)而不是原因;每条告警都要有 runbook 和明确的处理人。④ 度量:每周复盘通知数量与“需要人工处理的比例”。

经核实的教学视频

▶
PromCon EU 2019: Improved Alerting with Prometheus and Alertmanager — Prometheus Monitoring
英文 · 告警设计与 Alertmanager 用法的改进实践
▶
Prometheus Alertmanager | Hands on Demo Grouping, Inhibition, and Silences on Alertmanager — Tech with Lian
英文 · 分组、抑制、静默的动手演示
▶
Prometheus Alerting Rules for Beginners: Pending, Firing and promtool Tests (Real Output) — DevOps Simplified
英文 · pending/firing 与 promtool 规则测试

官方文档

视频分镜脚本(约 90 秒)

镜头 1 · 0–25s
画面:告警像一封信穿过七道门:加载、评估、结果、for、发送、Alertmanager、接收器;在第三道门前信消失了。
旁白:health 等于 ok 不代表会响,表达式可能一直为空。
镜头 2 · 25–55s
画面:amtool config routes test 输出 null,镜头放大 kps 默认配置中的 receiver null。
旁白:kps 默认不发送任何通知,先确认路由。
镜头 3 · 55–90s
画面:50 条告警被抑制规则和分组折叠成 2 条通知。
旁白:告警风暴用分组、抑制和防抖治理,原因告警压制症状告警。
或在“测验”中取得 ≥ 70% 的分数

模块 7 · Grafana 排错:数据源、面板与权限

42:00 – 50:00 · Prometheus 有数据、面板却显示 No data:问题一定在“浏览器 → Grafana 后端 → 数据源 → Prometheus → 返回 → 转换 → 渲染”这条路径上的某一跳
8 分钟Grafana 13.3.1(kps 子 chart 14.4.1)★★★★☆
学习目标
  • 画出面板查询的请求路径:浏览器 → POST /api/ds/query(Grafana 后端)→ Prometheus 数据源插件 → 从 Grafana Pod 的网络访问 Prometheus → 结果帧 → 转换(transformations)→ 渲染。
  • 用 Query inspector(Query / Data / Stats / JSON)区分“查询没返回”“返回了但被转换丢掉”“渲染设置隐藏了”。
  • 理解 $__interval、$__rate_interval、Min interval、Max data points 与数据源 Scrape interval(jsonData.timeInterval)如何决定 step 与 rate 窗口。
  • 排查 kps 的 sidecar 预配(标签 grafana_dashboard: "1"、grafana_datasource: "1")、变量、Datasource … was not found 与权限问题。
前置知识:第 1 课 Grafana 架构、第 5 课 kps 中的 Grafana。重要程度:★★★★☆

What:一次面板查询的路径

  1. 前端:面板根据时间范围、Max data points、Min interval 计算 $__interval(并据此决定 step),替换模板变量。
  2. Grafana 后端:浏览器调用 POST /api/ds/query,后端校验用户对仪表盘 / 数据源的权限。
  3. 数据源插件:Prometheus 数据源(后端插件)把查询转换成 /api/v1/query_range(或 instant)请求,从 Grafana Pod 发出——所以 URL 必须是 Grafana 能解析的地址(kps 默认 http://kps-kube-prometheus-stack-prometheus.monitoring:9090/,uid prometheus),与你的浏览器能否访问无关。
  4. 返回与转换:结果转成 data frame,经过 transformations(过滤、合并、重命名)。
  5. 渲染:可视化选项(单位、阈值、Overrides、隐藏序列、Y 轴范围)。

step 与 rate 窗口

变量 / 设置含义排错要点
$__interval≈ 时间范围 / Max data points,不小于 Min interval 与数据源 Scrape intervalstep 太小 → 点数多(11 000 限制);太大 → 尖峰被抹平
$__rate_intervalmax($__interval + Scrape interval, 4 × Scrape interval)rate 窗口始终至少包含 4 个抓取间隔,避免“缩放时间范围后变 No data”
数据源 Scrape interval(jsonData.timeInterval)Grafana 假设的抓取间隔kps 自动设为 Prometheus 的 scrapeInterval;手工建数据源时常被遗漏(默认 15s)
Max data points / Min interval(面板 Query options)限制点数与最小 step“写死”很小的 Min interval 会让长范围查询超限

Why:Grafana 常见故障的分类

类别典型现象第一观察窗口
连通性面板红色三角:Post "http://…:9090/api/v1/query_range": dial tcp: lookup … no such host / connect: connection refused数据源 “Save & test”、/api/datasources/uid/<uid>/health
数据源引用Datasource ${DS_PROMETHEUS} was not found、Datasource xyz was not found面板 JSON 中的 datasource.uid
查询语义No data,Prometheus UI 同样为空Query inspector → Query 标签页里的实际 expr 与 step
变量选 All 后 No data;变量下拉为空Inspector 中替换后的 expr(= vs =~、All 值)
转换 / 渲染Inspector Data 标签有数据,图上没有Transformations、Overrides、单位与阈值
预配ConfigMap 里的仪表盘 / 数据源没出现sidecar 容器日志(grafana-sc-dashboard、grafana-sc-datasources)、标签
权限看不到仪表盘、Explore 不可用、“Access denied”组织角色(Viewer/Editor/Admin)、文件夹权限、团队

How:二分法

把 Inspector 中的 expr 原样复制到 Prometheus UI(同一时间范围与 step)执行:Prometheus 也没有 → 查询或 L1–L7 的问题;Prometheus 有、Grafana 没有 → 看 Inspector 的 Data 标签:没有帧 → 数据源 / 连通 / 权限;有帧 → 转换与渲染。

When:何时怀疑 Grafana 自身

只有某些用户看不到(权限)、只有某个仪表盘慢(面板数量与刷新,模块 4)、升级后部分面板报 “Panel plugin not found”(插件未安装或不兼容)、预配的修改在 UI 中被保存后与 ConfigMap 不一致(预配的仪表盘在 UI 中修改无法持久保存,应改源文件)。

常见误解① “浏览器能打开 Prometheus,Grafana 就能连上”——Grafana 后端从 Pod 网络访问,用的是集群内 DNS。② “rate 窗口写死 [1m] 最简单”——缩放时间范围或抓取间隔变化时会时有时无,用 $__rate_interval。③ “No data 就是没数据”——可能是转换、Overrides 隐藏、单位或时间范围(时区、未来时间)造成的。④ “导入社区仪表盘一定能用”——${DS_PROMETHEUS} 输入占位符必须在导入时映射到实际数据源;指标名可能与你的 exporter 版本不同。

面板请求路径与每一跳的失败

浏览器变量 · $__interval Grafana 后端/api/ds/query · 权限 数据源插件uid=prometheus Prometheusquery_range 转换frames 渲染overrides 变量为空 / All403 · 无权限was not foundno such hostbad_data · 超时过滤掉隐藏/单位 Query inspector:Query 标签 = 实际发出的请求(expr、step);Data 标签 = 返回的帧;Stats = 耗时与点数二分法:把 expr 拿到 Prometheus UI 执行,判断问题在 Prometheus 前还是后
图 7-1 Grafana 到 Prometheus 的请求从 Grafana Pod 发出

kps 中的 sidecar 预配

ConfigMap(任意命名空间)label grafana_dashboard: "1" ConfigMap / Secretlabel grafana_datasource: "1" grafana-sc-dashboardwatch → 写文件 → 调 reload API grafana-sc-datasources写 provisioning/datasources grafana 容器provisioning 加载日志:provisioning 错误 kps 93.3.0:dashboards sidecar searchNamespace = ALL;datasources sidecar 默认只看 Grafana 所在命名空间(以 values 为准)
图 7-2 预配的仪表盘不出现:标签 → sidecar 日志 → grafana 日志

交互:面板请求路径追踪器

选择一个“面板异常”,逐跳追踪请求:每一跳显示 Grafana / Prometheus 实际做的事情,失败的一跳显示报错和修复方法。

选择一个异常后点击“追踪”。
$ # 每一跳的请求与响应

核心命令(Grafana HTTP API,用 admin 账号)

命令作用
curl -s -u admin:$GPW $G/api/healthGrafana 版本与数据库状态
curl -s -u admin:$GPW $G/api/datasources | jq '.[] | {uid,name,type,url}'所有数据源及 URL
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health后端健康检查(等同 UI 的 Save & test)
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query -d '{…}'以 Grafana 后端身份执行查询,绕过浏览器
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20仪表盘 sidecar 是否发现 / 写入
kubectl -n monitoring logs deploy/kps-grafana -c grafana | grep -iE 'level=(error|warn)'Grafana 服务端错误(预配、插件、数据源代理)
source ~/promlab/faultlab/env.sh
export GPW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
curl -s -u admin:$GPW $G/api/datasources | jq -c '.[] | {uid, name, type, url, timeInterval: .jsonData.timeInterval}'
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health | jq
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query -d '{
  "from": "now-15m", "to": "now",
  "queries": [{"refId": "A", "datasource": {"uid": "prometheus"}, "expr": "up{job=\"faultexp\"}", "instant": true}]
}' | jq '.results.A | {status, error, frames: (.frames | length)}'
{"uid":"prometheus","name":"Prometheus","type":"prometheus","url":"http://kps-kube-prometheus-stack-prometheus.monitoring:9090/","timeInterval":"30s"}
{"uid":"alertmanager","name":"Alertmanager","type":"alertmanager",...}
{
  "message": "Successfully queried the Prometheus API.",
  "status": "OK"
}
{"status": 200, "error": null, "frames": 1}

如何验证:/api/ds/query 返回帧而面板没有 → 问题在前端(变量、转换、渲染)。常见错误:API token / 密码写进脚本历史;实验后 unset GPW。生产用途:合成监控定期调用 /api/ds/query 与数据源 health,作为 Grafana 自身的可用性检查。

实验 7:坏数据源、坏引用、坏变量(约 8 分钟)

预配一个仪表盘(faultlab 命名空间,sidecar searchNamespace = ALL):
apiVersion: v1
kind: ConfigMap
metadata:
  name: faultlab-dashboard
  namespace: faultlab
  labels: {grafana_dashboard: "1"}
data:
  faultlab.json: |
    {
      "uid": "faultlab", "title": "Faultlab", "schemaVersion": 39, "refresh": "1m",
      "time": {"from": "now-1h", "to": "now"},
      "templating": {"list": [{
        "name": "status", "type": "query", "multi": true, "includeAll": true,
        "datasource": {"type": "prometheus", "uid": "prometheus"},
        "query": {"query": "label_values(faultexp_http_requests_total, status)", "refId": "V"}
      }]},
      "panels": [{
        "id": 1, "type": "timeseries", "title": "faultexp 请求速率",
        "gridPos": {"h": 9, "w": 24, "x": 0, "y": 0},
        "datasource": {"uid": "prometheus", "type": "prometheus"},
        "targets": [{"refId": "A",
          "expr": "sum by (status) (rate(faultexp_http_requests_total{status=~\"$status\"}[$__rate_interval]))"}]
      }]
    }
kubectl apply -f ~/promlab/faultlab/dash.yaml
sleep 20
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=5 | grep -i faultlab
curl -s -u admin:$GPW "$G/api/search?query=Faultlab" | jq -c '.[] | {uid,title,folderTitle}'
... Writing /tmp/dashboards/faultlab.json ...
{"uid":"faultlab","title":"Faultlab","folderTitle":null}

浏览器打开 http://localhost:3000/d/faultlab,应看到 status=200 一条线(ERRORS 关闭时 500 为 0)。

坏引用:把面板数据源 uid 改成不存在的 prom-old。
kubectl -n faultlab get cm faultlab-dashboard -o yaml | sed 's/{"uid": "prometheus", "type"/{"uid": "prom-old", "type"/' | kubectl apply -f -
sleep 30   # 刷新浏览器
面板左上角红色三角:Datasource prom-old was not found

导入社区仪表盘时最常见的同类错误是 Datasource ${DS_PROMETHEUS} was not found(导入时没有映射输入)。修复:改回 prometheus 或使用数据源变量 ${datasource}。复位:kubectl apply -f ~/promlab/faultlab/dash.yaml。

坏变量:在 UI 中编辑面板,把 status=~"$status" 改成 status="$status",变量选 All。打开 Inspector → Query:
sum by (status) (rate(faultexp_http_requests_total{status="(200|500)"}[2m0s]))

多值 / All 变量被格式化为正则 (200|500),必须配 =~。同时注意 $__rate_interval 被替换成了 2m0s(kps 数据源 timeInterval = 30s,下限为 4 × 30s;如果显示 1m,说明数据源的 Scrape interval 被设成了 15s,与实际抓取间隔不符)。放弃修改(不要保存——预配的仪表盘保存会失败或被覆盖)。

坏数据源(连通性):添加一个指向错误主机的预配数据源(datasource sidecar 默认只看 Grafana 所在命名空间,所以放在 monitoring,实验后删除)。
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
  name: faultlab-bad-ds
  namespace: monitoring
  labels: {grafana_datasource: "1"}
data:
  bad.yaml: |
    apiVersion: 1
    datasources:
      - name: Prometheus-typo
        uid: prom-typo
        type: prometheus
        access: proxy
        url: http://kps-kube-prometheus-stak-prometheus.monitoring:9090
EOF
sleep 40
curl -s -u admin:$GPW $G/api/datasources/uid/prom-typo/health | jq
{
  "message": "… dial tcp: lookup kps-kube-prometheus-stak-prometheus.monitoring on 10.96.0.10:53: no such host …",
  "status": "ERROR"
}

从 Grafana Pod 内验证 DNS:kubectl -n monitoring exec deploy/kps-grafana -c grafana -- wget -qO- http://kps-kube-prometheus-stack-prometheus.monitoring:9090/-/ready(Grafana 镜像通常带 busybox wget,以实际镜像为准)。清理:kubectl -n monitoring delete cm faultlab-bad-ds(sidecar 删除文件后,已加载的数据源是否同时删除取决于 sidecar 与预配设置,必要时在 UI 中删除)。

案例 1:升级 Prometheus 抓取间隔后面板“断断续续”

问题:为节省成本把 scrapeInterval 从 15s 改为 60s,大量面板变成虚线和空洞。原因:面板写死 rate(x[1m]),窗口内只有一个样本。修复:全量替换为 $__rate_interval,并确认数据源 timeInterval 同步改为 60s(kps 自动同步)。

案例 2:新同事看不到任何仪表盘

问题:SSO 登录后是 Viewer,但仪表盘都放在只授权给 “SRE” 团队的文件夹。做法:按团队设置文件夹权限,公共仪表盘放在 Viewer 可见的文件夹;用 SSO 组映射到 Grafana 团队,避免手工维护。

案例 3:GitOps 预配的仪表盘被 UI 修改“覆盖”

问题:有人在 UI 中修改了 sidecar 预配的仪表盘并以新名字另存,几周后两个版本内容分叉。做法:预配仪表盘设为不可编辑,修改走 Git(JSON 或 Grafonnet / Terraform,第 6 课与 Terraform 课);UI 中的实验只在个人文件夹。

常见错误与解决

Datasource ${DS_PROMETHEUS} was not found

原因:导入的仪表盘带有 __inputs 占位符,未在导入时映射;或通过 ConfigMap 预配时原样写入。修复:把 JSON 中的 ${DS_PROMETHEUS} 替换为实际 uid,或增加数据源类型变量 datasource 并引用 ${datasource}。

Post "http://…:9090/api/v1/query_range": dial tcp: lookup … no such host / connection refused

原因:数据源 URL 错(Service 名、命名空间、端口、routePrefix),或 NetworkPolicy 阻止 Grafana → Prometheus。诊断:数据源 health API;从 Grafana Pod 内请求 /-/ready。

面板 No data,Inspector Data 标签显示有数据

原因:转换(Filter by name / Organize fields)去掉了字段、Overrides 隐藏了序列、Y 轴 min/max 把值挤出、单位换算。修复:逐个禁用 transformations;Inspector → Panel JSON 查看 overrides。

变量下拉为空或 “Templating … Error updating options”

原因:label_values(metric, label) 中指标在当前时间范围无数据;变量依赖链中上游变量为空;正则过滤掉了所有值。诊断:在 Explore 中执行 count by (label) (metric);检查变量刷新设置(On dashboard load / On time range change)。

sidecar 预配的仪表盘没有出现

诊断:ConfigMap 标签必须是 grafana_dashboard: "1"(kps 默认 label / labelValue);kubectl logs deploy/kps-grafana -c grafana-sc-dashboard;JSON 是否合法(jq . file.json);uid 冲突时后加载的会覆盖或报错(看 grafana 容器日志)。

命令行操作题
1. 不打开浏览器,检查 Grafana 的 Prometheus 数据源是否能连通 Prometheus。
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health | jq
2. 以 Grafana 后端身份执行 sum(up) 即时查询,确认返回的帧数量。
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query \
  -d '{"from":"now-5m","to":"now","queries":[{"refId":"A","datasource":{"uid":"prometheus"},"expr":"sum(up)","instant":true}]}' | jq '.results.A.frames | length'
场景分析题
业务团队说“Grafana 上的错误率面板和 Prometheus 告警对不上:面板显示 2%,告警说 12%”。你如何排查?

① Inspector 取出面板实际 expr 与 step,和告警规则 expr 对比:窗口($__rate_interval vs [2m])、标签过滤(变量是否只选了部分 status 或 Pod)、聚合方式(avg of ratios vs ratio of sums)。② step 较大时面板点是该 step 处的瞬时计算结果,短时尖峰不一定落在点上;告警每 30s 评估一次,更“敏感”。③ 用同一时间点在 Prometheus UI 执行两条表达式对比。通常结论是查询语义不同,修正为统一的 recording rule 让面板和告警引用同一条序列。

经核实的教学视频

▶
GrafanaCONline: Prometheus rate queries in Grafana — Grafana
英文 · rate 查询、$__interval 与 $__rate_interval 的来龙去脉
▶
How to build a Prometheus query in Grafana — Grafana
英文 · Grafana 中构建 Prometheus 查询(Query builder 与 Code 模式)
▶
Understanding Dashboards in Grafana | Panels, Visualizations, Queries, and Transformations — Grafana
英文 · 面板、查询与转换的关系(排查“有数据却不显示”)

官方文档

视频分镜脚本(约 90 秒)

镜头 1 · 0–25s
画面:一条查询从浏览器出发,经过 Grafana 后端、数据源插件,抵达 Prometheus 再返回;途中六个检查站。
旁白:面板的请求是从 Grafana 服务器发出的,不是从你的浏览器。
镜头 2 · 25–60s
画面:Query inspector 三个标签页依次展开:Query 中的 expr、Data 中的帧、Stats 中的耗时。
旁白:把 expr 拿到 Prometheus 执行,就能判断问题在前还是在后。
镜头 3 · 60–90s
画面:rate 窗口从固定的一分钟变为 $__rate_interval,断续的线变得连贯。
旁白:rate 窗口用 rate interval,至少包含四个抓取间隔。
或在“测验”中取得 ≥ 70% 的分数

模块 8 · 综合故障盲盒

50:00 – 60:00 · 8 种真实故障随机注入:只给你值班时会看到的现象,用八段链路与本课工具定位、修复、写下护栏
10 分钟fault-box.sh交互排障树★★★★★
学习目标
  • 在不知道故障类型的前提下,按“可信度 → 定段 → 取证 → 止血 → 根因与护栏”完成诊断。
  • 覆盖 8 种故障:connection refused、ServiceMonitor 未被选中、抓取超时、Content-Type、sample limit、churn、告警窗口过小、Grafana 数据源引用错误。
  • 每次修复后写出一条护栏(limit、告警、CI 检查、约定)。
前置知识:模块 1–7。重要程度:★★★★★

What:8 种故障一览(答案表,演练前不要看)

#注入方式值班时看到的现象段决定性证据修复护栏
1Service targetPort → 8081FaultexpDown firingL4lastError connect: connection refusedtargetPort 改回 http使用命名端口;部署后检查 up
2ServiceMonitor 去掉 release: kpsfaultexp 面板全空,FaultexpDown 不响L2absent(up{job="faultexp"}) = 1;配置 Secret 中无该 job补标签absent 告警;CI 校验 SM 标签
3DELAY=12FaultexpDown firing,偶发恢复不了L4lastError context deadline exceeded;scrape_duration ≈ 10s修 exporter(去掉延迟)抓取耗时 / timeout 比例告警
4CT=application/octet-streamexporter“升级”后 downL5received unsupported Content-Type …修 exporter 或 fallbackScrapeProtocol升级前在预发用 3.x 抓取
5SERIES=8000FaultexpDown firing,exporter 本身正常L5sample limit exceeded;scrape_samples_scraped ≈ 8003修埋点 / metricRelabelings dropsampleLimit + enforcedSampleLimit
6SERIES=1000 + CHURN=1Prometheus 内存持续上涨,所有目标 upL6rate(prometheus_tsdb_head_series_created_total[5m]) 高;scrape_series_added 持续非零去掉会话标签序列创建速率告警
7规则窗口 [10s] + ERRORS=15xx 明显增加,FaultexpHighErrorRate 不响L7规则 health ok、state inactive;UI 执行表达式为空窗口改为 [2m]promtool test rules;窗口 ≥ 4 × 抓取间隔
8仪表盘数据源 uid → prom-oldFaultlab 仪表盘红色三角L8Datasource prom-old was not found改回 uid prometheus仪表盘使用数据源变量;CI 校验 uid

How:每轮诊断节奏(≤ 3 分钟)

  1. 读现象,问:up 存在吗?值是多少?(定段的一半工作)
  2. 跑“标准诊断包”(实验分页第 2 步)。
  3. 按段深入:lastError / 配置 Secret / TSDB Status / 规则与 ALERTS / Grafana API。
  4. 修复并验证:up = 1、告警恢复、面板有数据。
  5. 写一句护栏。
常见误解① “故障 2 和故障 1 一样是目标挂了”——一个是 up 不存在,一个是 up = 0,告警行为完全不同。② “故障 5 调大 sampleLimit 就好”——那就进入故障 6 的内存问题。③ “故障 7 是 Alertmanager 的问题”——Prometheus 中根本没有 pending。

8 种故障在八段链路中的位置

L1 暴露 L2 发现 L3 relabel L4 抓取 L5 限制 L6 存储 L7 规则 L8 呈现 (#3 #4 #5 #6 的源头)#2 未选中#1 refused#3 timeout#4 Content-Type#5 sample limit#6 churn#7 窗口过小#8 uid 不存在 up 不存在:#2 | up = 0:#1 #3 #4 #5 | up = 1:#6 #7 #8先回答“up 存在吗、值是多少”,8 选 1 变成 3 选 1
图 8-1 故障分布与 up 状态

交互:浏览器内故障盲盒

点击“抽一个故障”,你只会看到值班现象。选择诊断命令查看(示例)输出,然后判断根因;答对后显示修复与护栏。成绩保存在本浏览器。

$ # 点击上方按钮开始

fault-box.sh:在 kind + kps 上随机注入故障

保存为 ~/promlab/faultlab/fault-box.sh 并 chmod +x。前提:模块 0 的 faultexp.yaml、模块 7 的 dash.yaml 已存在。脚本只修改命名空间 faultlab 中的对象。

#!/usr/bin/env bash
# 第 7 课综合故障盲盒:./fault-box.sh random | 1..8 | reveal | reset
set -uo pipefail
D=~/promlab/faultlab; NS=faultlab; ANS=$D/.answer
k() { kubectl -n $NS "$@" >/dev/null; }

base() {
  k set env deploy/faultexp DELAY- CT- SERIES- CHURN- ERRORS-
  # 删除后重建,确保 patch 加入的字段(fallbackScrapeProtocol、relabelings…)全部清除
  k delete servicemonitor faultexp --ignore-not-found
  k delete prometheusrule faultexp-rules --ignore-not-found
  kubectl apply -f $D/faultexp.yaml >/dev/null
  k patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":"http"}]'
  [ -f $D/dash.yaml ] && kubectl apply -f $D/dash.yaml >/dev/null
  k rollout status deploy/faultexp --timeout=120s
}

f1() { k patch svc faultexp --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8081}]'
       echo "告警:FaultexpDown 已 firing。"; }
f2() { k label servicemonitor faultexp release-
       echo "用户反馈:Faultlab 仪表盘所有面板都是 No data,但没有任何告警。"; }
f3() { k set env deploy/faultexp DELAY=12
       echo "告警:FaultexpDown 已 firing。exporter 团队说服务“很健康”。"; }
f4() { k set env deploy/faultexp CT=application/octet-stream
       echo "exporter 刚“升级”了一个版本,随后 FaultexpDown firing。"; }
f5() { k set env deploy/faultexp SERIES=8000
       echo "开发团队刚发布了“按用户统计请求”的新功能,随后 FaultexpDown firing,但 Pod 运行正常。"; }
f6() { k set env deploy/faultexp SERIES=1000 CHURN=1
       echo "平台告警:Prometheus 内存持续上涨。所有目标都是 up。"; }
f7() { k set env deploy/faultexp ERRORS=1
       k patch prometheusrule faultexp-rules --type=json -p '[{"op":"replace","path":"/spec/groups/0/rules/3/expr","value":"sum(rate(faultexp_http_requests_total{status=~\"5..\"}[10s])) / sum(rate(faultexp_http_requests_total[10s])) > 0.1"}]'
       echo "用户投诉大量 500 错误,但 FaultexpHighErrorRate 一直没有响。"; }
f8() { kubectl -n $NS get cm faultlab-dashboard -o yaml \
         | sed 's/{"uid": "prometheus", "type"/{"uid": "prom-old", "type"/' | kubectl apply -f - >/dev/null
       echo "用户截图:Faultlab 仪表盘面板左上角出现红色三角。"; }

case "${1:-random}" in
  reset)  base; rm -f $ANS; echo "已复位到干净基线(等待约 1 分钟让 Prometheus 重新加载)";;
  reveal) echo "本次注入的故障编号:$(cat $ANS 2>/dev/null || echo 无)";;
  random|[1-8])
    base
    n=${1:-random}; [ "$n" = random ] && n=$(( RANDOM % 8 + 1 ))
    echo $n > $ANS
    echo "故障已注入,2–4 分钟后现象完全出现。值班现象:"; f$n;;
  *) echo "用法:$0 random|1..8|reveal|reset"; exit 1;;
esac

注意:kubectl apply -f faultexp.yaml 中的 Deployment 不含 env,单独 apply 不会删除用 kubectl set env 加上的变量(它们不在 last-applied 中),所以脚本显式删除。故障 6 注入后,head 中的序列要等下一次 head 压缩才会释放(模块 5)。Compose 环境(~/promlab)可以手工复现其中的 #3 #4 #5 #7:在 compose 文件中对 myapp 以外的一个测试 exporter 设置同样的环境变量即可。

实验 8:盲盒演练(每轮约 3 分钟,至少 4 轮)

抽取:
cd ~/promlab/faultlab && chmod +x fault-box.sh && source env.sh
./fault-box.sh random
故障已注入,2–4 分钟后现象完全出现。值班现象:
告警:FaultexpDown 已 firing。exporter 团队说服务“很健康”。
标准诊断包(每轮都先跑这一组):
pq 'up{job="faultexp"}'; pq 'absent(up{job="faultexp"})'
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/faultlab/faultexp/0" | jq -r '.data.activeTargets[] | "\(.health) \(.lastScrapeDuration) \(.lastError)"'
pq 'scrape_samples_scraped{job="faultexp"}'
pq 'rate(prometheus_tsdb_head_series_created_total[5m])'
curl -s "$P/api/v1/rules?type=alert" | jq -r '.data.groups[] | select(.name=="faultexp.rules") | .rules[] | "\(.name) \(.health) \(.state)"'
pq 'ALERTS{namespace="faultlab"} or ALERTS{alertname=~"Faultexp.*"}'
按段深入:
# L2:配置里有没有
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -c 'serviceMonitor/faultlab/faultexp'
kubectl -n faultlab get servicemonitor faultexp --show-labels
# L1:绕过 Prometheus 直接看 exporter
kubectl -n faultlab run curl --rm -i --restart=Never --image=curlimages/curl:8.11.1 -- -s -o /dev/null \
  -w 'code=%{http_code} ct=%{content_type} time=%{time_total}s size=%{size_download}\n' http://faultexp.faultlab:8080/metrics
# L7:规则表达式
kubectl -n faultlab get prometheusrule faultexp-rules -o jsonpath='{.spec.groups[0].rules[3].expr}{"\n"}'
# L8:Grafana
curl -s -u admin:$GPW $G/api/dashboards/uid/faultlab | jq -c '[.dashboard.panels[].datasource]'
核对、修复、复位:写下判断后执行 ./fault-box.sh reveal,按“原理”分页的修复列操作并验证(up = 1、告警恢复或能正确触发、面板有数据),然后 ./fault-box.sh reset 进入下一轮。
记录表:
轮次 | 现象 | up 状态 | 段 | 决定性证据 | 根因 | 修复 | 护栏 | 用时
1    |      |         |    |            |      |      |      |
2    |      |         |    |            |      |      |      |

案例 1:叠加故障

问题:一次发布同时引入了高基数标签(#5)并把 exporter 换成了返回 text/html 的新框架(#4)。值班人员修好 Content-Type 后,目标立刻因 sample limit 再次 down。教训:L5 中多个检查按顺序执行(先选解析器、再计样本),修好一个才会暴露下一个;每次修复后都重新读 lastError。

案例 2:把盲盒做成团队演练

做法:平台团队在共享 kind 环境中每周注入一次故障,新成员限时诊断;复盘记录沉淀为第 9 课的问题库与值班手册。效果:真实事故中“定段”的时间明显缩短(团队自述,未量化验证)。

案例 3:护栏清单进入发布流程

做法:每个新服务上线检查:ServiceMonitor 标签与 sampleLimit、absent 告警、规则单元测试、仪表盘数据源变量、Content-Type 规范。由 CI 中的 promtool check rules、promtool test rules、kubeconform 与一段 jq 校验完成。

交互排障树:Prometheus & Grafana 深度故障

从你看到的现象开始逐步选择,叶子节点给出诊断命令与修复。

命令行操作题
1. 一条命令同时判断 faultexp 的 up 是“不存在”“0”还是“1”。
up{job="faultexp"} or on() vector(-1)

返回 -1 表示序列不存在(or on() vector(-1) 在左侧为空时补一个值)。

2. 找出所有 lastError 非空的目标,并按 lastError 分组计数。
curl -s "$P/api/v1/targets?state=active" | jq -r '.data.activeTargets[] | select(.lastError!="") | .lastError' \
  | sed -E 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(:[0-9]+)?/IP/g' | sort | uniq -c | sort -rn
场景分析题
你注入了一个故障,现象是“Prometheus 内存上涨,所有目标 up”。同事建议重启 Prometheus。请评估。

重启不能解决 churn:新序列仍在产生;而且会触发 WAL 回放(序列越多越慢),期间没有数据和告警评估,还可能因为回放内存不足而 OOM 循环。正确顺序:用 rate(prometheus_tsdb_head_series_created_total[5m]) 和 sum_over_time(scrape_series_added[5m]) 按 job 找到 churn 来源 → metricRelabelings 丢弃或修复埋点 → 等待下一次 head 压缩释放内存 → 加序列创建速率告警。只有在内存即将 OOM 时才考虑临时提高 limit。

经核实的教学视频

▶
Don't Make These 6 Prometheus Monitoring Mistakes | Prometheus Best Practices & Pitfalls — Prometheus Monitoring with Julius | PromLabs
英文 · 复习:常见错误清单
▶
PromCon Online 2020 - TSDB WTF, Ian Billett, Improbable — Prometheus Monitoring
英文 · 真实生产中的 TSDB 故障故事,适合盲盒后复盘

官方文档

视频分镜脚本(约 90 秒)

镜头 1 · 0–15s
画面:盲盒打开,8 张故障卡旋转,停在一张只写着“FaultexpDown firing”的卡上。
旁白:只看现象,不看答案。
镜头 2 · 15–60s
画面:终端依次运行 up、absent、targets、TSDB 指标、rules;八段链路中对应方块逐个变绿,最后一个变红。
旁白:先问 up 存在吗、值是多少,再按段取证。
镜头 3 · 60–90s
画面:修复后 up 变为 1,记录表写下一条护栏。
旁白:每次修复都留下一条护栏。
或在“测验”中取得 ≥ 70% 的分数

命令速查表

深度排错常用命令、查询与报错原文(Prometheus v3.16.0 · Alertmanager v0.35.0 · Grafana 13.3.1 · kps 93.3.0)
可信度与定段
ALERTS{alertname="Watchdog"}
count by (job) (up == 0)
absent(up{job="X"})
up{job="X"} or on() vector(-1)
time() - prometheus_rule_group_last_evaluation_timestamp_seconds
rate(prometheus_notifications_dropped_total[5m])
抓取与发现(L2–L5)
curl -s "$P/api/v1/targets?state=active&scrapePool=serviceMonitor/NS/NAME/0" | jq '.data.activeTargets[]|{health,lastError,lastScrapeDuration}'
curl -s "$P/api/v1/targets?state=dropped"
curl -s -G "$P/api/v1/targets/relabel_steps" --data-urlencode scrapePool=… --data-urlencode labels='{…}'
kubectl -n monitoring get secret prometheus-$PROM_CR -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep job_name
kubectl get events -n NS --field-selector involvedObject.kind=ServiceMonitor
基数(L5–L6)
curl -s "$P/api/v1/status/tsdb?limit=10" | jq .data
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb analyze /prometheus --limit=10
prometheus_tsdb_head_series
rate(prometheus_tsdb_head_series_created_total[5m])
topk(10, sum by (job) (sum_over_time(scrape_series_added[5m])))
topk(10, max by (job) (scrape_samples_scraped))
increase(prometheus_target_scrapes_exceeded_sample_limit_total[1h])
查询性能(L7)
curl -s "$P/api/v1/query_range" --data-urlencode query='…' -d start=… -d end=… -d step=30 -d stats=all \
  | jq '.data.stats.samples|{seriesTouched,peakSamples,totalQueryableSamples}'
prometheus:
  prometheusSpec:
    queryLogFile: /dev/stdout
    query: {maxSamples: 50000000, timeout: 2m, maxConcurrency: 20}
TSDB(L6)
curl -s $P/api/v1/status/tsdb/blocks | jq '.data.blocks[]|{ulid,minTime,maxTime,level:.compaction.level}'
curl -s $P/api/v1/status/walreplay
kubectl -n monitoring exec $PROM_POD -c prometheus -- promtool tsdb list -r /prometheus
increase(prometheus_tsdb_compactions_failed_total[3h]) > 0
prometheus_tsdb_wal_storage_size_bytes
prometheus_tsdb_storage_blocks_bytes
rate(prometheus_tsdb_wal_corruptions_total[1h])
告警(L7–L8)
curl -s "$P/api/v1/rules" | jq -r '.data.groups[].rules[]|select(.health!="ok")|[.name,.lastError]|@tsv'
AMT="kubectl -n monitoring exec $AM_POD -c alertmanager -- amtool --alertmanager.url=http://localhost:9093"
$AMT alert query -s -i
$AMT silence query
$AMT config routes show
$AMT config routes test namespace=X severity=critical alertname=Y
Grafana(L8)
curl -s -u admin:$GPW $G/api/health
curl -s -u admin:$GPW $G/api/datasources/uid/prometheus/health
curl -s -u admin:$GPW -H 'Content-Type: application/json' $G/api/ds/query \
  -d '{"from":"now-5m","to":"now","queries":[{"refId":"A","datasource":{"uid":"prometheus"},"expr":"up","instant":true}]}'
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20
护栏片段
# ServiceMonitor
spec:
  sampleLimit: 5000
  labelLimit: 30
  labelValueLengthLimit: 512
  endpoints:
    - port: http
      scrapeTimeout: 10s        # ≤ interval
      metricRelabelings:
        - {sourceLabels: [__name__], regex: 'debug_.*', action: drop}
# kps values
prometheus:
  prometheusSpec:
    enforcedSampleLimit: 50000
    retention: 10d
    retentionSize: 40GiB

报错原文速查

报错(原文)段见
… connect: connection refusedL4模块 2
… context deadline exceededL4模块 2
server returned HTTP status 403 ForbiddenL4模块 2
body size limit exceededL4模块 2
received unsupported Content-Type "…" and no fallback_scrape_protocol specified for targetL5模块 2
non-compliant scrape target sending blank Content-Type and no fallback_scrape_protocol specified for targetL5模块 2
sample limit exceededL5模块 3
label_limit exceeded (metric: …, number of labels: N, limit: M)L5模块 3
target_limit exceeded (number of targets: N, limit: M)L2模块 3
scrape timeout greater than scrape interval for scrape config with job name "…"配置模块 2
query processing would load too many samples into memory in query executionL7模块 4
query timed out in …L7模块 4
exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)L7模块 4
found duplicate series for the match group … on the right hand-side of the operation / multiple matches for labels: many-to-one matching must be explicit (group_left/group_right)L7模块 4
vector contains metrics with the same labelset after applying alert labelsL7模块 6
Replaying WAL, this may take a while(长时间停留)L6模块 5
Encountered WAL read error, attempting repairL6模块 5
Datasource … was not foundL8模块 7

综合实验 + 结业测验

在 kind + kps 上逐一注入 8 种故障,完成诊断记录,并为团队输出一份“自监控与护栏”清单
约 60–90 分钟本地 kind · 零费用
场景

你是平台团队的监控负责人。公司刚从 Prometheus 2.x 升级到 3.16,过去一个月出现了“告警沉默两天”“Prometheus 每天 OOM”“大屏拖垮 Prometheus”三起事故。请在 kind 集群 lab 的 faultlab 命名空间中用 fault-box.sh 依次注入故障 1–8,每个故障完成“定段 → 证据 → 修复 → 护栏”,最后提交诊断记录表与自监控与护栏清单。

准备:完成模块 0;保存模块 7 的 dash.yaml 与模块 8 的 fault-box.sh。
cd ~/promlab/faultlab && source env.sh && ./pf.sh
export GPW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
kubectl apply -f dash.yaml && ./fault-box.sh reset
故障 1–2(目标 down 与目标消失):
./fault-box.sh 1; sleep 90; pq 'up{job="faultexp"}'          # 0 → lastError: connection refused
./fault-box.sh 2; sleep 90; pq 'absent(up{job="faultexp"})'   # 1 → 配置 Secret 中无该 job
故障 3–5(L4/L5):
./fault-box.sh 3; sleep 90   # context deadline exceeded
./fault-box.sh 4; sleep 90   # received unsupported Content-Type …;分别用“修 exporter”和 fallbackScrapeProtocol 两种方法修复
./fault-box.sh 5; sleep 90   # sample limit exceeded;用 metricRelabelings drop 止血
故障 6(L6):
./fault-box.sh 6; sleep 240
pq 'rate(prometheus_tsdb_head_series_created_total[2m])'
pq 'topk(3, sum by (job) (sum_over_time(scrape_series_added[2m])))'
故障 7–8(L7/L8):
./fault-box.sh 7; sleep 240   # 规则 health ok、state inactive;在 UI 执行表达式为空
./fault-box.sh 8; sleep 40    # Faultlab 仪表盘:Datasource prom-old was not found
curl -s -u admin:$GPW $G/api/dashboards/uid/faultlab | jq -c '[.dashboard.panels[].datasource]'
输出:自监控与护栏清单(复制到团队文档,按实际情况填写负责人与日期):
# Prometheus 自监控与护栏清单
## A. 元监控
- [ ] Watchdog 接入外部死人开关(收不到即报警)
- [ ] 每个关键 job:absent(up{job=…}) 或目标数下降告警
- [ ] 规则组漏评估:rate(prometheus_rule_group_iterations_missed_total[5m]) > 0
- [ ] 通知链路:prometheus_notifications_dropped_total、alertmanager_notifications_failed_total
## B. 抓取
- [ ] 所有 ServiceMonitor 带 release 标签(CI 校验)、使用命名端口
- [ ] 抓取耗时 / timeout > 0.8 预警(extra_scrape_metrics)
- [ ] 升级 Prometheus 前在预发全量抓取一次(Content-Type)
## C. 基数
- [ ] 每个 ServiceMonitor 设置 sampleLimit / labelLimit;kps 设置 enforcedSampleLimit
- [ ] 序列创建速率告警(对比 1 天前)
- [ ] 每周 TSDB Status / promtool tsdb analyze 复查 Top 10
- [ ] 埋点评审:禁止 user_id、request_id、原始 URL 等无界标签
## D. 查询
- [ ] 高频面板与 SLO 使用 recording rule
- [ ] 仪表盘刷新 ≥ 1m、默认范围 ≤ 6h、rate 使用 $__rate_interval
- [ ] 排查期开启 queryLogFile
## E. 存储
- [ ] retention + retentionSize 同时设置;磁盘预测告警
- [ ] compactions_failed、wal_corruptions 告警
- [ ] 内存 limit 覆盖 WAL 回放峰值;评估 memory-snapshot-on-shutdown
## F. 告警
- [ ] 规则 promtool test rules 进 CI;rate 窗口 ≥ 4 × 抓取间隔
- [ ] Alertmanager 配置变更运行 amtool config routes test
- [ ] group_by、抑制规则、静默必须有到期时间与原因
## G. Grafana
- [ ] 仪表盘使用数据源变量;预配仪表盘走 Git
- [ ] 数据源 health 与 /api/ds/query 合成监控
清理:
./fault-box.sh reset
kubectl delete namespace faultlab
kubectl -n monitoring delete cm faultlab-bad-ds --ignore-not-found
./pf.sh stop; unset GPW
# 如修改过 kps 的 Alertmanager 配置(模块 6),用你的标准 values 文件重新 helm upgrade
验收清单

开放式自测

1. 为什么 sample_limit 选择“整次抓取失败”而不是“只保留前 N 个样本”?

只保留一部分样本会产生不完整、不可预测的数据(每次保留哪些取决于输出顺序),聚合结果会悄悄出错;整次失败让 up = 0,触发告警,问题立刻可见,同时保护了 Prometheus 的内存。

2. 如何设计一个能发现“监控系统沉默”的机制?

Watchdog 永远 firing → Alertmanager → 外部死人开关服务(收不到即报警);第二个 Prometheus(或托管服务)监控主 Prometheus 的 up 与规则评估;absent 告警覆盖关键 job。

3. head 序列数与 Prometheus 内存的关系为什么不是严格线性的?

内存还包括 chunk 缓冲、查询临时内存、WAL 写缓冲、Go GC 余量;标签字符串长度不同;m-map chunks 走页缓存。只能用实测比值做容量规划,并预留查询与回放的峰值。

4. 什么时候应该调大 query.max-samples?

确认查询本身合理(已使用 recording rule、范围与 step 合理)、业务确需、Prometheus 内存有余量、并发受控时。更好的选择通常是 Thanos/Mimir 的查询切分与下采样。

5. 为什么 Grafana 的 rate 窗口推荐 $__rate_interval?

它保证窗口至少覆盖 4 个抓取间隔且不小于 step + 一个抓取间隔:缩放时间范围或抓取间隔变化时都能有足够的样本,并且相邻点之间不会漏掉数据。

6. 本课哪些故障在托管 Prometheus(Azure Monitor / AMP)中会以不同形式出现?

基数直接体现为费用与配额(摄取限制、活跃序列限制);TSDB 内部(WAL、压缩、磁盘)由云厂商负责,不再是你的故障;抓取故障在托管采集器(ama-metrics、AMP scraper)中仍然存在,但观察窗口变为其自身的日志与指标;查询限制变为服务配额(第 3、4 课)。

来源与版本说明

本课技术事实的核实依据(核实日期:2026-11-15)
主题核实结论来源(核实日期)
版本Prometheus v3.16.0(2026-11-05);Alertmanager v0.35.0(2026-11-09);Grafana v13.3.1(2026-11-10,课程规范写的 12.x 已过时);kube-prometheus-stack 93.3.0(2026-11-13,Operator v0.95.2,Prometheus 镜像 v3.16.0-distroless,Grafana 子 chart 14.4.1 / appVersion 13.3.1)GitHub Releases API:prometheus、alertmanager、grafana、helm-charts(2026-11-15)
抓取报错sample limit exceeded、label_limit exceeded (…)、label_name_length_limit …、label_value_length_limit …、target_limit exceeded (…)、body size limit exceeded、server returned HTTP status %s;超限后继续解析以报告真实样本数;失败时追加空 body 写入陈旧标记v3.16.0 scrape/scrape.go、scrape/target.go
Content-Type四种 … no fallback_scrape_protocol specified for target 报错原文;识别的类型:application/openmetrics-text、application/vnd.google.protobuf、text/plainv3.16.0 model/textparse/interface.go
抓取配置默认 scrape_interval 1m、scrape_timeout 10s、evaluation_interval 1m;timeout > interval 报错原文;默认 scrape_protocols 顺序;extra_scrape_metrics 成为配置项,--enable-feature=extra-scrape-metrics 正在淘汰v3.16.0 config/config.go、cmd/prometheus/main.go
查询限制--query.max-samples=50000000、--query.timeout=2m、--query.max-concurrency=20、--query.lookback-delta=5m;报错原文;11 000 点限制;stats 参数仅 true/allv3.16.0 cmd/prometheus/main.go、promql/engine.go、web/api/v1/api.go、util/stats/query_stats.go
TSDB块 2h;compactable = 跨度 > 1.5 × 块范围;块范围 ×3 递增,最大 min(保留 10%, 31d);WAL 段 128 MiB,checkpoint 取前 2/3 段;samples-per-chunk 120;WAL 压缩默认 snappy;保留默认 15d,retention 命令行参数标记 DEPRECATED(改用配置文件),新增 retention.percentage;大小保留包含 WAL 与 head chunks;日志消息原文v3.16.0 tsdb/db.go、tsdb/head.go、tsdb/compact.go、tsdb/wlog/wlog.go、config/config.go
TSDB 状态 API/api/v1/status/tsdb 字段与 limit(默认 10、最大 10000);/status/tsdb/blocks、/status/walreplay、/targets/relabel_stepsv3.16.0 web/api/v1/api.go
promtooltsdb analyze(--limit 默认 20、--extended、--match;默认分析最后一个块)输出标题;tsdb list -r;check service-discoveryv3.16.0 cmd/promtool/main.go、tsdb.go
自监控指标prometheus_target_scrapes_exceeded_sample_limit_total 等抓取指标;prometheus_tsdb_*;prometheus_rule_*;prometheus_notifications_*;prometheus_engine_*v3.16.0 scrape/metrics.go、tsdb/*、rules/group.go、notifier/metric.go、promql/engine.go
规则vector contains metrics with the same labelset after applying alert labels;--rules.alert.resend-delay=1m;通知队列 10000v3.16.0 rules/alerting.go、rules/recording.go、cmd/prometheus/main.go
OperatorServiceMonitor 字段 sampleLimit、labelLimit、labelNameLengthLimit、labelValueLengthLimit、targetLimit、bodySizeLimit、fallbackScrapeProtocol(PrometheusText0.0.4 等);Prometheus CR enforced*、query、queryLogFile、scrapeFailureLogFile、tsdb.outOfOrderTimeWindow、retentionPercentage;默认 serviceDiscoveryRole = Endpoints;配置 Secret prometheus-<name> 的 prometheus.yaml.gz;拒绝资源时发出 EventOperator v0.95.2 pkg/apis/monitoring/v1/*.go;Troubleshooting
kps 默认值选择器 NilUsesHelmValues=true(release: kps)、命名空间选择器 {};retention 10d、walCompression true、enforcedSampleLimit false;Alertmanager 默认路由 group_by [namespace]、30s/5m/12h、接收器 null、Watchdog → null、三条 severity 抑制规则;Grafana sidecar 标签 grafana_dashboard/grafana_datasource = "1",数据源 uid prometheus,timeInterval 跟随 scrapeInterval,dashboards searchNamespace ALL;未设置 adminPasswordkube-prometheus-stack 93.3.0 values.yaml、templates/grafana/configmaps-datasources.yaml
镜像distroless 镜像包含 /bin/promtool,无 shell;Alertmanager 镜像基于 busybox,含 amtoolv3.16.0 Dockerfile.distroless;Alertmanager v0.35.0 Dockerfile

视频核实说明

以下视频均通过 YouTube oEmbed 接口(https://www.youtube.com/oembed?url=…&format=json,2026-11-15)核实了标题与频道:PromLabs《Don't Make These 6 Prometheus Monitoring Mistakes…》(NEMsO1qeI1s)、《Relabeling in Prometheus…》(mXvuKAb6ZwY);TechWorld with Nana《How Prometheus Monitoring works…》(h4Sl21AKiDg)、《Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1》(QoDqxm7ybLc);Anton Putra《Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor - Step-by-Step》(HOmdYtsB950);Prometheus Monitoring《PromCon 2018: Bomb Squad…》(MHiXP5QW4_U)、《PromCon 2024 - Inside a PromQL Query…》(t53-7vUhbqY)、《PromCon EU 2022: Anatomy of a Slow Query…》(t9dw698NMvs)、《Optimizing PromQL Queries - Aliaksandr Valialkin…》(w6hj0VSnw5U)、《PromCon Online 2020 - TSDB WTF…》(zTH7DKAWqHc)、《PromCon 2016: The Prometheus Time Series Database…》(HbnGSNEjhUc)、《PromCon EU 2019: Improved Alerting…》(RlOA5KgBkz8);CNCF《Tracking Cardinality Explosions In Flight…》(EdGNwAa-vGk);Cloud Explainers《Prometheus TSDB Churn…》(ilyNu6RmkU4);USENIX《SREcon22 Asia/Pacific - Lifecycle of a Sample in the Prometheus TSDB》(LOZQFT8Dcq0);FOSSASIA《Lifecycle of a Sample in the Prometheus TSDB - Ganesh Vernekar》(35TAaAESLcc);Tech with Lian《Prometheus Alertmanager | Hands on Demo Grouping, Inhibition, and Silences…》(IoCz7NJ-LT0);DevOps Simplified《Prometheus Alerting Rules for Beginners…》(Op0cUlooq4k);Grafana《GrafanaCONline: Prometheus rate queries in Grafana》(09bR9kJczKM)、《How to build a Prometheus query in Grafana》(5VrjOzIOJPw)、《Understanding Dashboards in Grafana…》(vTiIkdDwT-0)。时长、上传日期与内容细节未逐一核实;多数录制于 Prometheus 2.x / Grafana 9–11 时期,版本细节以本课为准。所有视频均为英文。

语音讲解说明

“语音”分页使用浏览器 Web Speech API(zh-CN)朗读讲解稿,英文术语用 en-US 发音;效果取决于操作系统语音包。本课件生成环境无法调用 TTS 服务,因此没有内嵌 MP3;讲解稿可直接交给 TTS 工具生成音频。本课件也无法直接生成视频,已为每个模块提供分镜脚本。

已知限制

  • 本课所有命令按 Prometheus v3.16.0 / Operator v0.95.2 源码、kps 93.3.0 values 与官方文档编写,未在本课件生成环境中对 kind 集群实际运行;“预期输出”中的 IP、Pod 名后缀、ULID、序列数、内存与耗时均为示例。
  • Grafana 13 的报错与健康检查文字(例如 “Successfully queried the Prometheus API.”、“Datasource … was not found”)未逐字对照 Grafana 13.3.1 源码(Prometheus 数据源代码已移出主仓库),以实际 UI 为准;Grafana 镜像是否带 wget 未核实。
  • Prometheus 日志的具体字段(source= 行号、附加键值)随版本变化;课件只保证消息文本(msg)来自 v3.16.0 源码。
  • 每条活跃序列的内存开销(动画中按 4 KiB 估算)是经验值,不是基准测试;查询成本计算器为简化模型。
  • kps 默认 scrapeInterval 为空(由 Operator 默认 30s 决定)、datasource sidecar 的 searchNamespace 默认值未逐行核实;relabel_steps 在 UI 中的展示位置以实际 UI 为准。
  • curlimages/curl:8.11.1、python:3.13-alpine 镜像标签按常见可用版本书写,未在本环境拉取验证。
  • 第 1–6 课与第 8 课与本课并行编写,跨课引用以课程统一约定(myapp、~/promlab、kind 集群 lab、命名空间 monitoring、release kps)为准,具体页面内容以各课最终版本为准。