链路追踪 · 第 6 / 13 章
6OTel Collector:receiver / processor / exporter 管道
Collector 是一个「遥测数据网关」:应用只负责用 OTLP 把数据发出去,采样、脱敏、改名、扇出、重试、批处理全部在 Collector 侧完成。它带来的最大好处不是省资源,而是把「改配置」和「改代码」分开了——调整采样率、临时丢弃某个高噪声 span、给数据加一个环境标签,这些都只需 reload Collector,不用重新发版,也不用担心个别语言的 SDK 不支持某个特性。
6.1 管道模型与部署形态
Collector 的心智模型是一条流水线:receivers 收 → processors 改 → exporters 发,在 service.pipelines 里按信号(traces / metrics / logs)组装。同一个 Collector 可以跑多条互不干扰的管道。有两类组件值得单独记住:connectors(把一条管道的输出接成另一条管道的输入,如 spanmetrics 把 trace 转成指标)和 extensions(不参与数据流的能力,如 health_check、zpages)。
Agent 模式(每主机 / DaemonSet)
- 优点:离应用近、省跨网带宽、可实现「节点级标签注入」
- 代价:实例多、配置管理复杂、无法做全局决策(如尾部采样)
- 适合:批量处理与本地缓冲,然后转发给 gateway
Gateway 模式(中心集群)
- 优点:唯一能正确做尾部采样的位置;配置集中;出口统一
- 代价:需要水平扩展与负载均衡;成为关键路径上的一跳
- 适合:接入 5 个以上服务、需要尾部采样与统一脱敏的团队
6.2 一份完整的配置
下面这份配置可直接用于生产(去掉 debug exporter 后):
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
max_recv_msg_size_mib: 8 # 默认 4MiB,大 trace 会被拒
keepalive:
server_parameters:
max_connection_idle: 120s
http:
endpoint: 0.0.0.0:4318
cors:
allowed_origins: ["http://localhost:3000", "https://grafana.internal"]
processors:
# ① 必须放在管道第一位:先自保,再干活
memory_limiter:
check_interval: 1s
limit_percentage: 75 # 进程内存超过 75% 时开始拒绝/丢弃
spike_limit_percentage: 20 # 预留 20% 给突发,避免硬 OOM
# ② 脱敏:无论应用怎么做,出口前统一清理
attributes/scrub:
actions:
- key: db.statement.parameters
action: delete
- key: http.request.header.authorization
action: delete
- key: http.request.header.cookie
action: delete
- key: baggage
action: delete
# ③ 资源属性归一化:给所有 span 打上集群与环境
resource/enrich:
attributes:
- key: deployment.environment
value: prod
action: upsert
- key: k8s.cluster.name
value: prod-shanghai
action: upsert
# ④ 尾部采样:错误全留、慢请求全留、其余 5%
tail_sampling:
decision_wait: 10s # 等多久收集一个 trace 的全部 span
num_traces: 100000 # 内存中最多缓存多少个待决策 trace
expected_new_traces_per_sec: 2000 # 仅用于内部统计与告警,不影响正确性
policies:
- name: all-errors
type: status_code
status_code:
status_codes: [ERROR]
- name: slow-over-1s
type: latency
latency:
threshold_ms: 1000
- name: baseline-5pct
type: probabilistic
probabilistic:
sampling_percentage: 5
- name: checkout-always # 关键业务路径 100% 保留
type: string_attribute
string_attribute:
key: http.route
values: ["/checkout", "/pay/callback"]
# ⑤ 批处理必须放最后:合并成大批次再发,省网络与连接
batch:
timeout: 5s
send_batch_size: 8192
send_batch_max_size: 16384
exporters:
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
compression: gzip
retry_on_failure:
enabled: true
initial_interval: 5s
max_interval: 30s
max_elapsed_time: 300s
sending_queue:
enabled: true
num_consumers: 10
queue_size: 5000
debug:
verbosity: basic # detailed 会打印每个 span,仅调试用
sampling_initial: 5
sampling_thereafter: 200
extensions:
health_check:
endpoint: 0.0.0.0:13133
zpages:
endpoint: 0.0.0.0:55679
pprof:
endpoint: 0.0.0.0:1777
service:
extensions: [health_check, zpages, pprof]
telemetry:
logs:
level: info
encoding: json
metrics:
level: detailed
address: 0.0.0.0:8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, resource/enrich, tail_sampling, batch]
exporters: [otlp/tempo, debug]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
memory_limiter 必须第一位:它要在任何会放大内存的操作(采样缓存、批处理)之前生效。batch 必须最后一位:它要把前面所有修改都合并后再压缩发送。尾部采样必须放在 batch 之前——因为采样的输入必须是单个 span(它需要按 trace_id 分组),而 batch 之后数据已经变成不可拆的批次。过滤器类 processor(如 filter/drop-noisy)应放在采样之前,让它们省下采样的内存。
6.3 tail_sampling 的容量怎么算
尾部采样在 decision_wait 窗口内必须把整个 trace 的 span 全部驻留内存,这是它唯一的硬成本。估算公式:
num_traces >= 峰值 trace 创建速率 × decision_wait × 安全系数(3~5)
例:峰值 2000 trace/s,decision_wait = 10s
num_traces >= 2000 × 10 × 5 = 100000
单个 trace 的平均内存 ≈ span 数 × 单 span 内存(约 1~2KB,含 attributes)
例:平均 30 span/trace × 1.5KB ≈ 45KB
内存上限 ≈ 100000 × 45KB ≈ 4.5GB ← 这才是 Collector 的 limit 该给的量级
如果 num_traces 设小了会发生什么:超出上限的 trace 被直接丢弃(不是降级采样),并且 Collector 的日志里会出现 tail_sampling 相关告警,指标 otelcol_processor_tail_sampling_sampling_trace_dropped_too_early 会增长。这个指标必须配告警,否则你会以为「慢请求都被采到了」,实际上最慢的那批(span 最多、内存最大)恰好是最先被丢的。
一个 40 节点的 Kubernetes 集群,我们按「每节点一个 Collector DaemonSet」部署,并在 agent 上配了尾部采样。上线后监控显示:错误 trace 的捕获率只有 30% 左右,而理论上应该是 100%。
原因是架构性的:一个 trace 的 8 个 span 分布在 5 个节点上,被送进 5 个不同的 Collector agent。每个 agent 只看到自己那部分 span,decision_wait 到期后各自独立决策——看到 ERROR span 的 agent 保留了它,只看到正常 span 的 agent 按 5% 概率把它丢了。结果是同一条 trace 里只有部分 span 被保存,瀑布图上出现断链,甚至根 span 都没了。
修复分两步:① 把尾部采样从 agent 挪到 gateway 层;② agent 层改成「batch + forward」,但这样同一个 trace 的 span 仍然可能落到不同的 gateway 实例上,所以还要在 agent 的 exporter 前面加 loadbalancing exporter,用 routing_key: traceID 做一致性哈希,保证同一 trace 的所有 span 进同一个 gateway。改完后错误 trace 捕获率到 100%,断链消失。
exporters:
loadbalancing:
protocol:
otlp:
tls:
insecure: true
routing_key: traceID # 关键:按 traceID 哈希,而不是轮询
resolver:
static:
hostnames:
- otel-gateway-0:4317
- otel-gateway-1:4317
- otel-gateway-2:4317
前置:Docker 24+,一个空闲的 4317/4318 端口,以及能把 OTLP 发出去的客户端(otel-cli 或第 11 章的任一服务)。这里用纯 Docker 加一个内联的 echo 替代客户端,验证管道本身是通的。
cat > /tmp/otel-min.yaml <<'YAML'
receivers:
otlp:
protocols:
grpc: {endpoint: 0.0.0.0:4317}
http: {endpoint: 0.0.0.0:4318}
processors:
memory_limiter: {check_interval: 1s, limit_percentage: 75, spike_limit_percentage: 20}
batch: {timeout: 2s, send_batch_size: 128}
exporters:
debug: {verbosity: detailed, sampling_initial: 2, sampling_thereafter: 100}
service:
telemetry:
metrics: {level: detailed, address: 0.0.0.0:8888}
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [debug]
YAML
docker run --rm -d --name otelcol -p 4317:4317 -p 4318:4318 -p 8888:8888 \
-v /tmp/otel-min.yaml:/etc/otelcol/config.yaml \
otel/opentelemetry-collector-contrib:0.103.0 \
--config=/etc/otelcol/config.yaml
# 健康检查与自身指标
curl -s localhost:13133/health || true
curl -s localhost:8888/metrics | grep -E '^otelcol_(receiver_accepted_spans|exporter_sent_spans)' | head
预期:curl 自身指标会返回类似
otelcol_receiver_accepted_spans_total{receiver="otlp",service_instance_id="...",service_name="otelcol"} 137
otelcol_exporter_sent_spans_total{exporter="debug",service_instance_id="...",service_name="otelcol"} 137
然后从任意客户端发一个 span,容器日志里会出现 ResourceSpans 结构,包含 resource: {attributes: [{key: "service.name", value: {stringValue: "demo"}}]} 与 scopeSpans。用 docker logs -f otelcol 观察即可。如果 receiver_accepted_spans 增长而 exporter_sent_spans 不涨,说明 batch 还没触发(默认 200ms~5s 的正常延迟)或管道被 memory_limiter 拒绝(此时会有 otelcol_processor_refused_spans 指标)。
一台 8GB 内存的 gateway Collector,在某个上游批量任务触发(瞬间 5 万 trace/s)时,因为没有 memory_limiter,尾部采样的缓存直接把 RSS 顶到 8GB,被内核 OOM Kill。更糟的是它部署在 Kubernetes 里,重启后 decision_wait 窗口内的所有 trace 全部丢失,而那正好是故障最激烈的一段时间——你最需要数据的时候,数据没了。
配置要点:limit_percentage 要明显低于容器的 memory limit(推荐 75%,给 GC 与突发留空间),spike_limit_percentage 给 15%~25%。同时给 Collector 配 resources.limits.memory,并把 otelcol_processor_refused_spans 与容器 OOM 次数都配上告警。