如何将 OpenTelemetry 指标无缝写入 Prometheus?

解读

在国内金融、运营商、电商等生产级 K8s 集群中,Prometheus 仍是事实监控标准,而新业务普遍采用 OpenTelemetry 统一埋点。面试官关心的是:

  1. 你是否理解两套体系的数据模型差异(OTLP vs Prometheus exposition format);
  2. 能否在不改业务代码、不启新存储的前提下,让 Prometheus 像抓取原生目标一样拿到 OTel 指标;
  3. 方案必须具备高可用、可灰度、可版本回滚的落地细节,以匹配国内严苛的“变更评审”流程。

知识点

  • OpenTelemetry Collector:官方推荐的“代理+处理器+导出器”三件套,可部署为 K8s DaemonSet 或 Deployment。
  • Prometheus Receiver & Prometheus Exporter:Collector 内置组件,分别用于接收 OTLP 指标和暴露 /metrics 端点,实现协议转换。
  • target_allocator 模式:OTel Operator 提供的 CRD,自动把 Collector 实例与 Prometheus ServiceMonitor 关联,解决分片与一致性哈希。
  • 指标类型映射:OTel Sum→Prometheus Counter,Histogram 直方桶对齐,Summary 量化误差需丢弃 quantile 或转写。
  • 资源属性标签化:k8s.pod.name、k8s.node.name 等 resource attributes 必须扁平化为 Prometheus label,否则 Grafana 模板变量无法匹配。
  • 高可用策略:Collector 采用反亲和 + HPA + WAL 本地落盘,避免单点;同时 Prometheus 侧做**分片抓取(sharding)**降低单机压力。
  • 安全合规:通过ServiceAccount + RBAC + kube-rbac-proxy限制 /metrics 端口只读;敏感指标按国内等保要求脱敏或丢弃。

答案

  1. 在 K8s 集群内以 DaemonSet 方式部署 OpenTelemetry Collector,镜像使用国内镜像仓库(如 registry.cn-hangzhou.aliyuncs.com/otel/opentelemetry-collector-contrib:0.91.0),避免拉取外网失败。
  2. Collector 配置核心段落:
    receivers:
    otlp:
    protocols:
    grpc:
    endpoint: 0.0.0.0:4317
    processors:
    memory_limiter:
    limit_mib: 819
    batch:
    timeout: 5s
    resource:
    attributes:
    - key: k8s.cluster.id
    from_attribute: k8s.cluster.name
    action: upsert
    exporters:
    prometheus:
    endpoint: 0.0.0.0:8889
    namespace: otel
    send_timestamps: true
    metric_expiration: 5m
    resource_to_telemetry_conversion:
    enabled: true # 关键:把 resource attributes 转成 label
    service:
    pipelines:
    metrics:
    receivers: [otlp]
    processors: [memory_limiter, batch, resource]
    exporters: [prometheus]
  3. 为 Collector 创建无头 Service(ClusterIP=None),并在其上方定义PodMonitor(或 ServiceMonitor):
    • port: 8889
      path: /metrics
      interval: 30s
      honor_labels: true # 防止 Prometheus 自动加 exported_ 前缀*
  4. Prometheus Operator 检测到 PodMonitor 后,自动把各 Collector Pod 列入抓取目标;业务容器只需把 OTLP 指标打到 <Collector-Service>:4317,无需任何代码改造。
  5. 上线流程:
    a) 在测试 Namespace 灰度 10% Pod,观察 Prometheus TargetUp==1 且grafana 看板无断点;
    b) 通过 kubectl annotate 给 Collector DaemonSet 打上 version=vx.y.z,方便回滚;
    c) 发布单里明确**“双写期”**——老 Prometheus 路径仍保留,7 天后确认无数据缺失再下线。

拓展思考

  • 多集群联邦场景:若集团级 Prometheus 采用 Thanos Receive 模式,可直接让 Collector 使用 OTLP→Remote Write Exporter,跳过中转 /metrics,减少一次协议转换;但需评估 Thanos 端内存反压。
  • 指标量级治理:国内某头部券商实践表明,未做 drop 规则的 OTel Histogram 会使 Prometheus Series 暴涨 5 倍;建议在 processor 内按维度做 tail_sampling,或改用 ExponentialHistogram 并关闭不必要的 bucket。
  • 国产化替代:在信创环境(ARM+麒麟)下,官方镜像可能缺失,需要基于 Alibaba Cloud Linux 3 重编 Collector,并开启 CGO_ENABLED=0 静态链接,避免 glibc 版本冲突。
  • 合规审计:金融客户要求指标链路可追踪,可在 Collector 内加 attributes/insert 处理器,注入 trace_id 与 span_id,实现监控-链路一体化,方便后续定位慢 SQL 或异常吞吐。