Prometheus 迎來 OpenTelemetry—使用新體驗

OpenTelemetry 經過幾年發展,其 SDK 已然成爲數據埋點、採集、上報的默認選擇,在去年 【Mimir 原生支持 OTLP,離大一統又近了一步】一文中我們講到,Mimir 從 v2.3.0 開始原生支持 OTLP,它底層存儲引擎用的是 Prometheus TSDB,所以這部分改動很容易反饋給上游,今天(2023/07/28)相關代碼終於合併到了 main 分支,相信很快就會發布正式版本。

下面我們就來快速測試並體驗該功能。

啓動 Prometheus 測試容器

因爲 Prometheus 還沒發佈對應功能的正式版本,所以使用最新主分支的鏡像 prom/prometheus:main來測試,對應 docker 命令如下:

docker run --name prometheus-otlp \
    -d -p 9090:9090 \
    prom/prometheus:main \
    --config.file=/etc/prometheus/prometheus.yml \
    --storage.tsdb.path=/prometheus \
    --web.console.libraries=/usr/share/prometheus/console_libraries \
    --web.console.templates=/usr/share/prometheus/consoles \
    --enable-feature=otlp-write-receiver

注意 otlp-write-receiver 屬於實驗性功能,需要通過 --enable-feature 開啓。

成功啓動後,可以通過 HTTP 接口(api/v1/otlp/v1/metrics)進行驗證,此時執行 curl -X POST http://localhost:9090/api/v1/otlp/v1/metrics 應該響應 400 而不是 404。

測試代碼

使用 OpenTelemetry Go SDK(v0.39.0)編寫測試代碼,主要分爲以下幾步。

Step1: 新建 otlpmetrichttp exporter

ep, _ := otlpmetrichttp.New(
    context.Background(),
    otlpmetrichttp.WithEndpoint("localhost:9090"),
    otlpmetrichttp.WithURLPath("/api/v1/otlp/v1/metrics"),
    otlpmetrichttp.WithInsecure(),
  )

使用 Prometheus(localhost:9090) 作爲 otlpmetrichttp 接收地址,路徑爲 /api/v1/otlp/v1/metrics, 在測試的時候,我們發現 Prometheus 的 otlp 僅支持 HTTP 協議,GRPC 暫不支持。

Step2: 新建 resource 和 provider

ctx := context.Background()
res, _ := resource.New(ctx,
    resource.WithAttributes(
        semconv.ServiceName("service1"),
        semconv.ServiceNamespace("staging"),
        semconv.ServiceVersion("v0.1"),
        semconv.ServiceInstanceID("instance1"),
    ),
)
provider := metric.NewMeterProvider(
    metric.WithResource(res),
    metric.WithReader(
        metric.NewPeriodicReader(ep, metric.WithInterval(15*time.Second)),
    ),
)

通過 resource 標註了該測試程序對應的服務名、命令空間、版本和實例 ID 等信息,這個比較重要,因爲最終會對應 Prometheus 的 job 和 instance 標籤。

Step3: 使用 provider 新建指標並進行採樣

meter := provider.Meter("http",
    api.WithInstrumentationVersion("v0.0.1"),
)
httpDurationsHistogram, _ := meter.Float64Histogram(
    "http_durations_histogram_seconds",
    api.WithDescription("Http latency distributions."),
)
opt := api.WithAttributes(
    attribute.Key("method").String(http.MethodGet),
    attribute.Key("status").String("200"),
)
elapsed := float64(rand.Intn(100))
httpDurationsHistogram.Record(context.Background(), elapsed, opt)

運行結果

測試程序的指標數據可以通過 Prometheus 的看板進行查詢。

通過該圖可知,OTLP 協議解析和轉化後,生成 Prometheus 指標的標籤對應關係如下:

resource 標籤:

meter 標籤:分別對應 Prometheus metrics 標籤(全部保留)。

簡單總結

當我們開啓 otlp-write-receiver 試驗功能後, Prometheus 具備了 otlpmetrichttp 協議數據的接收能力,非常方便實現從客戶端程序或者 OTel Collector 直接將數據通過 OTLP 格式發送給 Prometheus。

在測試 Prometheus 進行 OTLP 協議數據接收的時候,需要注意以下幾點。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/LDt-Tj0DsL1ww8dQ7e7kmg