GH GambleHub

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至關重要)。

命名spans:
  • 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內幕。

Collector中的過濾器示例:
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和風險。

Contact

與我們聯繫

如有任何問題或支援需求,歡迎隨時聯絡我們。我們隨時樂意提供協助!

Telegram
@Gamble_GC
開始整合

Email 為 必填。Telegram 或 WhatsApp 為 選填

您的姓名 選填
Email 選填
主旨 選填
訊息內容 選填
Telegram 選填
@
若您填寫 Telegram,我們將在 Email 之外,同步於 Telegram 回覆您。
WhatsApp 選填
格式:國碼 + 電話號碼(例如:+886XXXXXXXXX)。

按下此按鈕即表示您同意我們處理您的資料。