使用 Prometheus snapshot 回填,步骤是什么?
解读
在国内 DevOps/可观测性面试中,**“Prometheus snapshot 回填”**常被用来考察候选人是否真正落地过“历史数据迁移+InfluxDB 冷启动”场景。
核心诉求是:利用 Prometheus 的本地快照,把旧指标无损地写入 InfluxDB,并保证时间戳、label、value 三要素不漂移,同时不触发 InfluxDB 的背压或 OOM。
面试官想听的是“可复制的 SOP”,而不是“大概知道 remote-write”。
知识点
- Prometheus 快照机制:通过
promtool tsdb dump或 API/api/v1/admin/tsdb/snapshot生成只读块,保留原始时间戳。 - InfluxDB 行协议:必须将 Prometheus exposition 格式转换为 measurement=指标名,tag=label,field=value timestamp(ns)。
- 写放大与乱序:InfluxDB 1.x 默认拒绝乱序写入,需开启
max-concurrent-write-limit=0与max-index-log-file-size=1MB临时调大容忍度;2.x 需设置influxd --storage-ingestion-rate-max=0。 - 批量 vs 限速:国内公有云小规格实例(4C8G)单次 batch 建议 5000~10000 行/200 ms,并发不超过 8,否则容易被云监控限流触发 “429 Too Many Requests”。
- 可观测性:每 10 s 打印
influx_write_latency_seconds与points_written_total,用于回滚点定位。
答案
步骤一:生成只读快照
在 Prometheus 节点执行
curl -XPOST http://localhost:9090/api/v1/admin/tsdb/snapshot
得到 /prometheus/snapshots/20240518T143000Z-1c8dbb9a9d860f8a 目录,确保文件属主与 InfluxDB 进程一致,避免后续 permission denied。
步骤二:格式转换(Prometheus → InfluxDB 行协议)
使用国内镜像源安装 prom2influx:
go install -ldflags "-s -w" github.com/influxdata/influxdb-observability/prometheus2influx@latest
执行
prom2influx dump --snapshot=/prometheus/snapshots/20240518T143000Z-1c8dbb9a9d860f8a \ --output=/data/snapshot.lp \ --timestamp-precision=ns \ --label-as-tags
关键参数:--label-as-tags 会把 Prometheus label 直接映射成 InfluxDB tag,避免后期 Flux 查询再 join。
步骤三:预检查 InfluxDB 写入策略
- 若目标 bucket 已有 7 天 TTL,需临时调高:
influx bucket update -n prometheus_backfill -r 30d - 关闭压缩与索引限流:
InfluxDB 1.x:在/etc/influxdb/influxdb.conf追加
[data] max-concurrent-compactions = 1 max-index-log-file-size = "1048576"
InfluxDB 2.x:环境变量INFLUXD_STORAGE_COMPACT_THROUGHPUT_BURST=48MB - 记录当前 series cardinality:
influx inspect report-disk --bucket-path ~/.influxdbv2/engine/data/xxx | grep "Total Series"
若 > 500 万,需提前扩容或拆 bucket。
步骤四:限速批量写入
influx write --bucket prometheus_backfill \ --file /data/snapshot.lp \ --rate-limit 100000/minute \ --max-line-length 65536 \ --retry-interval 5s \ --compression gzip
国内云厂商 VPC 内网可关闭 TLS 以节省 15% CPU;若跨地域,先传至对象存储再内网拉取,避免公网 3 分钱/GB 流量费。
步骤五:一致性校验
- 随机采样 1% 指标,用 Flux 对比 Prometheus 原始值:
from(bucket:"prometheus_backfill") |> range(start:2024-05-17T00:00:00Z, stop:2024-05-18T00:00:00Z) |> filter(fn: (r) => r._measurement == "node_cpu_seconds_total") |> sample(n:1000, pos:1)
与promtool query instant http://localhost:9090 'node_cpu_seconds_total'结果 diff 应 < 0.1%。 - 检查
influxdb_written_points_total与promtool tsdb list的样本数是否相等。
步骤六:收尾
- 恢复原始 TTL:
influx bucket update -n prometheus_backfill -r 7d - 触发一次全量压缩:
influxd compact --bucket-id 0x1234 - 删除快照目录,释放磁盘。
拓展思考
- 如果快照体积 > 2 TB,单台
influx write会成为瓶颈,可先用promtool tsdb dump按 2 h Block 拆片,再用 Kafka + Telegraf 多并发灌库,整体时间从 18 h 降到 3 h。 - 对于 InfluxDB Cluster (Enterprise),需提前创建 RP(Retention Policy)映射,并在写入时指定
db=_internal&rp=autogen避免跨节点路由失败。 - 若业务要求 零停机,可双写:旧 Prometheus 继续远程写 InfluxDB,回填快照时用 timestamp 去重(
influx write --skipRowOnConflict),实现“热补数据”。