Distributed Tracing: OpenTelemetry
Distributed Tracing: OpenTelemetry
1)为什么OTel和它给什么
OpenTelemetry(OTel)是具有单个OTLP协议的用于遥测(跟踪器,度量,logi)的开放标准和SDK/Agent/收集器集。目标是:- 端到端查询路径可见性(网关→服务→ DB/缓存/队列)。
- 快速RCA/调试降级和发布(金丝雀/蓝绿色)。
- 与SLO和自动回滚(数据操作解决方案)捆绑在一起。
- 供应商不可知性:导出到任何后端,而不涉及单个APM。
基准: 标准化,标准智能,安全由默认,correlate everything.
2)基本面: 上下文,spanes,属性
Trace是调用树/图形;Span-操作(RPC、SQL、队列调用)。
Span Kind: `SERVER`, `CLIENT`, `PRODUCER`, `CONSUMER`, `INTERNAL`.
W3C Trace Context:标题"traceparent","tracestate";上下文是跨服务的。
Attributes-关键值(低基数!),Events-时间戳,Status-错误/说明。
链接是严格层次结构之外的span链接(对于async/fan-out/fan-in至关重要)。
- HTTP: 'HTTP{METHOD} ('GET/withdraw'作为属性)
- DB: `DB SELECT` / `DB INSERT`
- Queue: `QUEUE publish topic=X` / `QUEUE consume topic=X`
3)语义约定(semconv)
使用稳定的属性图:- HTTP/GRPC: `http.method`, `http.route`, `http.status_code`, `url.full`.
- DB: `db.system=postgresql`, `db.statement'(仅限安全挤压!),'db.name`.
- Messaging: `messaging.system=kafka`, `messaging.operation=receive`, `messaging.destination`.
- Cloud/K8s/Host: `cloud.region`, `k8s.pod.name`, `container.id`.
- 资源署名(必需):"服务"。name`, `service.version`, `deployment.environment`.
通过SDK/Collector资源中的"schemaUrl"指定模式稳定性。
4) Sampling: head, tail, adaptive
基于头部(在SDK中):预先解决,便宜;对于high-QPS有利,但可能会错过"有趣"的轨道。
基于Tail(在Collector中):确定路线完成后;允许有关状态,潜伏期和属性的规则。
Adaptive/Dynamic:在p95错误/生长时提高样本比例。
Prod Level配方:全球1-5%的头部+Tail选择"重要":"status=ERROR","latency> p95","现金路线",PSP/KYC错误。
5)相关性: 度量标准,logies, tracks
Exemplars:在度量直方图中带有"trace_id"的标签(快速跳到赛道)。
Logs:添加"trace_id"/"span_id",然后从日志切换到路径。
SpanMetrics (processor):从RED度量("requests, errors, duration")路径聚合到SLO/alert。
6)部署架构
每个节点上的代理(DaemonSet)从应用程序(OTLP)和前进中收集。
网关(Cluster/Region)是中央收藏家(许多复制品),带有路由/采样/富集管道。
OTLP: gRPC `4317`, HTTP `4318`;启用TLS/mTLS。
"agent+gateway"优点:隔离、缓冲、本地回传、简化网络。
7) OpenTelemetry Collector-基本模板(网关)
yaml receivers:
otlp:
protocols:
grpc: { endpoint: 0. 0. 0. 0:4317 }
http: { endpoint: 0. 0. 0. 0:4318 }
processors:
memory_limiter: { check_interval: 5s, limit_percentage: 75 }
batch: { timeout: 2s, send_batch_size: 8192 }
attributes:
actions:
- key: deployment. environment action: upsert value: prod resource:
attributes:
- key: service. namespace action: upsert value: core tail_sampling:
decision_wait: 5s policies:
- name: errors type: status_code status_code: { status_codes: [ERROR] }
- name: slow_traces type: latency latency: { threshold_ms: 800 }
- name: important_routes type: string_attribute string_attribute:
key: http. route values: ["/withdraw", "/deposit"]
- name: baseline_prob type: probabilistic probabilistic: { sampling_percentage: 5 }
exporters:
otlp/apm:
endpoint: apm-backend:4317 tls: { insecure: true }
prometheus:
endpoint: 0. 0. 0. 0:9464
extensions:
health_check: {}
pprof: { endpoint: 0. 0. 0. 0:1777 }
zpages: { endpoint: 0. 0. 0. 0:55679 }
service:
extensions: [health_check, pprof, zpages]
pipelines:
traces: { receivers: [otlp], processors: [memory_limiter,attributes,resource,batch,tail_sampling], exporters: [otlp/apm] }
metrics: { receivers: [otlp], processors: [batch], exporters: [prometheus] }
logs: { receivers: [otlp], processors: [batch], exporters: [] }
8) SpanMetrics和RED for SLO
添加处理器:yaml processors:
spanmetrics:
metrics_exporter: prometheus histogram:
explicit:
buckets: [50ms,100ms,200ms,400ms,800ms,1600ms,3200ms]
service:
pipelines:
traces: { receivers: [otlp], processors: [spanmetrics,batch,tail_sampling], exporters: [otlp/apm] }
metrics: { receivers: [otlp], processors: [batch], exporters: [prometheus] }
现在有SLO/Alert的"traces_spanmetrics_calls {service, route, code}和'duration_bucket'。
9)K8s: Collector部署(DaemonSet+部署)
Agent (DaemonSet)片段:yaml apiVersion: apps/v1 kind: DaemonSet metadata: { name: otel-agent, namespace: observability }
spec:
template:
spec:
containers:
- name: otelcol image: otel/opentelemetry-collector:latest args: ["--config=/conf/agent. yaml"]
ports:
- { containerPort: 4317, name: otlp-grpc }
- { containerPort: 4318, name: otlp-http }
网关(部署)-几种复制品,即服务ClusterIP/Ingress,CPU/QPS下的HPA。
10)安全和隐私
TLS/mTLS между SDK → Agent → Gateway → Backend.
Gateway入口处的身份验证(基本/OAuth/Headers);限制起源。
PII修订版:过滤或掩盖属性('user.收藏家处理器中的电子邮件","卡")。
限制:在SDK中,限制事件大小/属性数(基数保护)。
后端RBAC+单独的项目/tenant内幕。
yaml processors:
attributes/redact:
actions:
- key: user. email action: delete
- key: payment. card action: delete
11)指导: 快速启动
Node.js
js import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc";
import { Resource } from "@opentelemetry/resources";
import { SemanticResourceAttributes as R } from "@opentelemetry/semantic-conventions";
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter({ url: "http://otel-agent. observability:4317" }),
resource: new Resource({
[R.SERVICE_NAME]: "payments-api",
[R.SERVICE_VERSION]: "1. 14. 2",
[R.DEPLOYMENT_ENVIRONMENT]: "prod"
}),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk. start();
Java (Spring)
java
// Gradle: io. opentelemetry. instrumentation:opentelemetry-spring-boot-starter
// application. yml otel:
service:
name: orders-api exporter:
otlp:
endpoint: http://otel-agent. observability:4317 traces:
sampler: parentbased_traceidratio sampler-arg: 0. 05
Python (FastAPI)
python from opentelemetry import trace from opentelemetry. sdk. resources import Resource from opentelemetry. exporter. otlp. proto. grpc. trace_exporter import OTLPSpanExporter from opentelemetry. sdk. trace import TracerProvider from opentelemetry. sdk. trace. export import BatchSpanProcessor
provider = TracerProvider(resource=Resource. create({"service. name":"fraud-scoring","deployment. environment":"prod"}))
provider. add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://otel-agent. observability:4317", insecure=True)))
trace. set_tracer_provider(provider)
Go
go exp, _:= otlptracegrpc. New(ctx, otlptracegrpc. WithEndpoint("otel-agent. observability:4317"), otlptracegrpc. WithInsecure())
res:= resource. NewWithAttributes(semconv. SchemaURL, semconv. ServiceNameKey. String("gateway"), semconv. DeploymentEnvironmentKey. String("prod"))
tp:= sdktrace. NewTracerProvider(sdktrace. WithBatcher(exp), sdktrace. WithResource(res), sdktrace. WithSampler(sdktrace. ParentBased(sdktrace. TraceIDRatioBased(0. 05))))
otel. SetTracerProvider(tp)
12)异步: 队列,总线,cron
通过"链接"进行通信的PRODUCER/CONSUMER(消息具有自己的生命周期)。
将上下文传播到消息标题("traceparent"/"baggage")。
在batch-consume中,通过每条消息的旋转创建或使用"消息"属性聚合。batch.size`.
对于cron/jobs:新的trace to run+links to main event(如果有)。
13) Baggage和目标
将最小稳定键("tenant_id","region","vip_tier")存储在baggage中;禁止PII。
穿过gateway/gateway-logger以后按段聚合度量。
14)与发行版和SLO游戏集成
金丝雀步骤→ 检查路线/yuz段上的"traces_spanmetrics_"。
降解(5xx/p95)-自动停止和回滚(Argo Rollouts AnalysisTemplate+PromQL)。
来自度量的实例直接导致发布间隔的"不良"路径。
15)限制和性能
Ограничивайте: `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`, `OTEL_SPAN_EVENT_COUNT_LIMIT`, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`.
按概率/频率对例外/堆栈进行采样。
SDK和Collector中的Batch处理器;保持队列,以免在激增时失去轨道。
16)互操作性和迁移
宣传员:使用W3C;支持在迁移时读取B3/X-Ray (dual-propagation)。
导出:OTLP → APM (Jaeger/Tempo/Elastic/X-Ray等)。
semconv的稳定版本-固定"schemaUrl"并计划升级。
17)反模式
高属性基数(标记中的"user_id",动态键)。
没有"trace_id"的逻辑→没有相关性。
直接从应用程序导出到Internet APM(没有网关,没有TLS/mTLS)。
在销售中收集"全部"100%是昂贵且毫无意义的。
在'db中包含用户数据的SQL查询转储。statement`.
不一致的服务/版本名称-指标"崩溃"。
18)实施清单(0-45天)
0-10天
在2-3项关键服务上启用SDK/自动工程。
配置Agent (DaemonSet)+Gateway(部署),OTLP 4317/4318和TLS。
添加"服务"。name`, `service.version`, `deployment.环境无处不在。
11-25天
通过错误/潜伏期/"货币"路线进行尾随采样。
SpanMetrics → Prometheus,启用Exemplars和RED/SLO行列板。
通过API 网关/NGINX/mesh宣传W3C;关联日志。
26-45天
覆盖队列/DB/缓存;links for async。
Collector中的PII修订政策;SDK中的属性限制。
集成了SLO登录版本和自动回滚。
19)成熟度量标准
传入请求的跟踪覆盖率≥ 95%(包括采样头/尾部)。
Exemplars的指标份额≥ 80%。
RCA时间"从指标到轨道"≤ 2分钟(p50)。
0属性/事件(扫描仪)中的PII泄漏。
所有服务均具有'服务'。名称/版本/环境"和一致的语义。
20)应用程序: 有用的片段
NGINX宣传:nginx proxy_set_header traceparent $http_traceparent;
proxy_set_header tracestate $http_tracestate;
proxy_set_header baggage $http_baggage;
Prometheus с Exemplars (Grafana):
histogram_quantile(0. 95, sum(rate(traces_spanmetrics_duration_bucket{route="/withdraw"}[5m])) by (le))
政策: 禁止PII属性(伪林特)
yaml forbid_attributes:
- user. email
- payment. card
- personal.
21)结论
OpenTelemetry将可观察性转变为标准化,可管理的轮廓:单一语义,安全的宣传,聪明的采样以及与度量和日志的强烈相关性。排队agent+gateway,添加尾随采样,spanmetrics和Exemplars,关注PII和基数-跟踪将不仅成为调试工具,而且成为自动化SRE/Release解决方案的工具,减少每次发布时的MTTR和风险。