開始使用 OpenTelemetry Collector

本文說明如何設定 OpenTelemetry Collector,以擷取標準 Prometheus 指標,並將這些指標回報給 Google Cloud Managed Service for Prometheus。OpenTelemetry Collector 是可自行部署的代理程式,設定後可匯出至 Managed Service for Prometheus。設定方式與透過自行部署的收集作業執行 Managed Service for Prometheus 類似。

您可能會基於下列原因,選擇使用 OpenTelemetry 收集器,而非自行部署收集:

  • OpenTelemetry Collector 可讓您在管道中設定不同的匯出工具,將遙測資料轉送至多個後端。
  • 收集器也支援指標、記錄和追蹤記錄的信號,因此您可以使用單一代理程式處理這三種信號類型。
  • OpenTelemetry 的供應商中立資料格式 (OpenTelemetry Protocol,簡稱 OTLP) 支援強大的程式庫和可外掛收集器元件生態系統。這可讓您自訂接收、處理及匯出資料的方式。

不過,執行 OpenTelemetry 收集器時,必須自行管理部署和維護作業。您選擇的方法取決於您的特定需求,但本文件提供使用 Managed Service for Prometheus 做為後端,設定 OpenTelemetry Collector 的建議指南。

事前準備

本節說明本文所述工作所需的設定。

設定專案和工具

如要使用 Google Cloud Managed Service for Prometheus,您需要下列資源:

  • 已啟用 Cloud Monitoring API 的 Google Cloud 專案。

    • 如果您沒有 Google Cloud 專案,請按照下列步驟操作:

      1. 前往 Google Cloud 控制台的「New Project」(新增專案):

        建立新專案

      2. 在「Project Name」(專案名稱) 欄位中輸入專案名稱,然後按一下「Create」(建立)。

      3. 前往「帳單」:

        前往「帳單」頁面

      4. 如果頁面頂端尚未選取您剛建立的專案,請選取該專案。

      5. 系統會提示您選擇現有的付款資料或是建立新的付款資料。

      新專案預設會啟用 Monitoring API。

    • 如果您已有 Google Cloud 專案,請確認 Monitoring API 已啟用:

      1. 前往Google Cloud 控制台的 Monitoring API 程式庫頁面:

        前往「Library」(程式庫) 頁面

      2. 選取專案。

      3. 如果程式庫頁面顯示「Manage」(管理) 按鈕,表示 Monitoring API 已啟用。如果看到「Enable」(啟用) 按鈕,代表 API 尚未啟用,必須點選「Enable」(啟用) 按鈕才能啟用。

  • Kubernetes 叢集。如果您沒有 Kubernetes 叢集,請按照 GKE 快速入門導覽課程中的操作說明操作。

您還需要下列指令列工具:

  • gcloud
  • kubectl

gcloud 和 kubectl 工具是 Google Cloud CLI 的一部分。如要瞭解如何安裝,請參閱「管理 Google Cloud CLI 元件」。如要查看已安裝的 gcloud CLI 元件,請執行下列指令:

gcloud components list

設定環境

為避免重複輸入專案 ID 或叢集名稱,請執行下列設定:

  • 請按照下列步驟設定指令列工具:

    • 設定 gcloud CLI,參照Google Cloud 專案的 ID:

      gcloud config set project PROJECT_ID
      
    • 如果是在 GKE 上執行,請使用 gcloud CLI 設定叢集:

      gcloud container clusters get-credentials CLUSTER_NAME --location LOCATION --project PROJECT_ID
      
    • 否則,請使用 kubectl CLI 設定叢集:

      kubectl config set-cluster CLUSTER_NAME
      

    如要進一步瞭解這些工具,請參閱下列資源:

設定命名空間

建立 NAMESPACE_NAME Kubernetes 命名空間,用於存放您在範例應用程式中建立的資源。使用本文件設定 Prometheus 範例時,建議使用命名空間名稱 gmp-test。

執行下列指令,建立命名空間:

kubectl create ns NAMESPACE_NAME

驗證服務帳戶憑證

如果 Kubernetes 叢集已啟用 Workload Identity Federation for GKE,則可略過本節。

在 GKE 上執行時,Managed Service for Prometheus 會根據 Compute Engine 預設服務帳戶,自動從環境擷取憑證。預設服務帳戶具備必要權限。如果您未使用 GKE 的 Workload Identity 聯盟,且先前已從預設節點服務帳戶中移除 monitoring.metricWriter 和 monitoring.viewer 角色授權,則必須先重新新增這些缺少的角色,才能繼續操作。

設定 Workload Identity Federation for GKE 的服務帳戶

如果 Kubernetes 叢集未啟用 Workload Identity Federation for GKE,可以略過本節。

Managed Service for Prometheus 會使用 Cloud Monitoring API 擷取指標資料。如果叢集使用 Workload Identity Federation for GKE,您必須將 Monitoring API 的權限授予 Kubernetes 服務帳戶。本節說明下列事項:

建立及繫結服務帳戶

Managed Service for Prometheus 說明文件中的多個位置都會顯示這個步驟。如果您先前已執行過這個步驟,就不必重複執行。請直接跳到「授權服務帳戶」一節。

首先,請建立服務帳戶 (如果尚未建立):

gcloud config set project PROJECT_ID \
&&
gcloud iam service-accounts create gmp-test-sa

接著,使用下列指令序列,將 gmp-test-sa 服務帳戶繫結至 NAMESPACE_NAME 命名空間中的預設 Kubernetes 服務帳戶:

gcloud config set project PROJECT_ID \
&&
gcloud iam service-accounts add-iam-policy-binding \
  --role roles/iam.workloadIdentityUser \
  --condition=None \
  --member "serviceAccount:PROJECT_ID.svc.id.goog[NAMESPACE_NAME/default]" \
  gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com \
&&
kubectl annotate serviceaccount \
  --namespace NAMESPACE_NAME \
  default \
  iam.gke.io/gcp-service-account=gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com

如果您使用其他 GKE 命名空間或服務帳戶,請適當調整指令。

授權給服務帳戶

相關權限會歸類為角色,您可將角色授予主體,在本例中為 Google Cloud服務帳戶。如要進一步瞭解 Monitoring 角色,請參閱「存取控管」。

下列指令會將 Google Cloud 服務帳戶gmp-test-sa授予寫入指標資料所需的 Monitoring API 角色。

如果您在先前的任務中,已將特定角色授予 Google Cloud 服務帳戶,就不必再次執行這項操作。

gcloud projects add-iam-policy-binding PROJECT_ID\
  --member=serviceAccount:gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com \
  --role=roles/monitoring.metricWriter \
  --condition=None \
&& \
gcloud projects add-iam-policy-binding PROJECT_ID \
  --member=serviceAccount:gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com \
  --role=roles/iam.serviceAccountTokenCreator \
  --condition=None

對 Workload Identity Federation for GKE 設定進行偵錯

如果無法順利使用 Workload Identity Federation for GKE,請參閱說明文件,瞭解如何驗證 Workload Identity Federation for GKE 設定,以及 Workload Identity Federation for GKE 疑難排解指南。

為 GKE 設定 Workload Identity Federation 時,最常見的錯誤來源是拼寫錯誤和部分複製貼上,因此我們強烈建議您使用可編輯的變數,以及這些操作說明中程式碼範例內嵌的可點選複製貼上圖示。

在正式環境中使用 Workload Identity Federation for GKE

本文所述的範例會將 Google Cloud 服務 帳戶繫結至預設 Kubernetes 服務帳戶,並授予 Google Cloud 服務帳戶使用 Monitoring API 所需的所有權限。

在正式環境中,建議您採用更精細的方法,為每個元件建立服務帳戶,並分別授予最低權限。如要進一步瞭解如何設定服務帳戶來管理 Workload Identity,請參閱「使用 Workload Identity Federation for GKE」。

設定 OpenTelemetry Collector

本節將引導您設定及使用 OpenTelemetry Collector,從範例應用程式擷取指標,並將資料傳送至 Google Cloud Managed Service for Prometheus。如需詳細設定資訊,請參閱下列各節:

OpenTelemetry Collector 類似於 Managed Service for Prometheus 代理程式二進位檔。OpenTelemetry 社群會定期發布版本,包括原始碼、二進位檔和容器映像檔。

您可以使用最佳做法預設值,將這些構件部署至 VM 或 Kubernetes 叢集,也可以使用收集器建構工具,建構僅包含所需元件的專屬收集器。如要建構與 Managed Service for Prometheus 搭配使用的收集器,您需要下列元件:

如要啟用這些元件,請使用設定檔,並透過 --config 旗標傳遞至收集器。

以下各節將詳細說明如何設定這些元件。本文說明如何在 GKE 和其他位置執行收集器。

設定及部署收集器

無論是在 Google Cloud 還是其他環境中執行收集作業,您仍可設定 OpenTelemetry Collector,將資料匯出至 Managed Service for Prometheus。最大的差異在於 Collector 的設定方式。在非Google Cloud 環境中,指標資料可能需要額外格式設定,才能與 Managed Service for Prometheus 相容。不過,在 Google Cloud上,收集器可以自動偵測大部分的格式。

在 GKE 執行 OpenTelemetry Collector

您可以將下列設定複製到名為 config.yaml 的檔案,在 GKE 上設定 OpenTelemetry Collector:

receivers:
  prometheus:
    config:
      scrape_configs:
      - job_name: 'SCRAPE_JOB_NAME'
        kubernetes_sd_configs:
        - role: pod
        relabel_configs:
        - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name]
          action: keep
          regex: prom-example
        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
          action: replace
          target_label: __metrics_path__
          regex: (.+)
        - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
          action: replace
          regex: (.+):(?:\d+);(\d+)
          replacement: $$1:$$2
          target_label: __address__
        - action: labelmap
          regex: __meta_kubernetes_pod_label_(.+)

processors:
  resourcedetection:
    detectors: [gcp]
    timeout: 10s

  transform:
    # "location", "cluster", "namespace", "job", "instance", and "project_id" are reserved, and
    # metrics containing these labels will be rejected.  Prefix them with exported_ to prevent this.
    metric_statements:
    - context: datapoint
      statements:
      - set(attributes["exported_location"], attributes["location"])
      - delete_key(attributes, "location")
      - set(attributes["exported_cluster"], attributes["cluster"])
      - delete_key(attributes, "cluster")
      - set(attributes["exported_namespace"], attributes["namespace"])
      - delete_key(attributes, "namespace")
      - set(attributes["exported_job"], attributes["job"])
      - delete_key(attributes, "job")
      - set(attributes["exported_instance"], attributes["instance"])
      - delete_key(attributes, "instance")
      - set(attributes["exported_project_id"], attributes["project_id"])
      - delete_key(attributes, "project_id")

  batch:
    # batch metrics before sending to reduce API usage
    send_batch_max_size: 200
    send_batch_size: 200
    timeout: 5s

  memory_limiter:
    # drop metrics if memory usage gets too high
    check_interval: 1s
    limit_percentage: 65
    spike_limit_percentage: 20

# Note that the googlemanagedprometheus exporter block is intentionally blank
exporters:
  googlemanagedprometheus:

service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [batch, memory_limiter, resourcedetection, transform]
      exporters: [googlemanagedprometheus]

上述設定會使用 Prometheus 接收器和 Managed Service for Prometheus 匯出工具,抓取 Kubernetes Pod 上的指標端點,並將這些指標匯出至 Managed Service for Prometheus。管道處理器會設定資料格式並批次處理資料。

如要進一步瞭解這項設定各部分的作用,以及不同平台的設定,請參閱下列有關抓取指標和新增處理器的詳細章節。

搭配使用現有的 Prometheus 設定和 OpenTelemetry Collector 的 prometheus 接收器時,請將所有單一錢幣符號字元 替換為雙錢幣符號字元 ,以免觸發環境變數替換。詳情請參閱「抓取 Prometheus 指標」。

您可以根據環境、供應商和要擷取的指標修改這項設定,但建議您先使用範例設定,在 GKE 上執行。

在 Google Cloud外部執行 OpenTelemetry Collector

在 Google Cloud外部 (例如地端部署或其他雲端服務供應商) 執行 OpenTelemetry Collector,與在 GKE 上執行 Collector 類似。不過,您抓取的指標不太可能自動包含最適合 Managed Service for Prometheus 的資料格式。因此,您必須特別留意設定收集器,將指標格式化,使其與 Managed Service for Prometheus 相容。

您可以將下列設定複製到名為 config.yaml 的檔案,設定 OpenTelemetry Collector,以便在非 GKE Kubernetes 叢集上部署:

receivers:
  prometheus:
    config:
      scrape_configs:
      - job_name: 'SCRAPE_JOB_NAME'
        kubernetes_sd_configs:
        - role: pod
        relabel_configs:
        - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name]
          action: keep
          regex: prom-example
        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
          action: replace
          target_label: __metrics_path__
          regex: (.+)
        - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
          action: replace
          regex: (.+):(?:\d+);(\d+)
          replacement: $$1:$$2
          target_label: __address__
        - action: labelmap
          regex: __meta_kubernetes_pod_label_(.+)

processors:
  resource:
    attributes:
    - key: "cluster"
      value: "CLUSTER_NAME"
      action: upsert
    - key: "namespace"
      value: "NAMESPACE_NAME"
      action: upsert
    - key: "location"
      value: "REGION"
      action: upsert

  transform:
    # "location", "cluster", "namespace", "job", "instance", and "project_id" are reserved, and
    # metrics containing these labels will be rejected.  Prefix them with exported_ to prevent this.
    metric_statements:
    - context: datapoint
      statements:
      - set(attributes["exported_location"], attributes["location"])
      - delete_key(attributes, "location")
      - set(attributes["exported_cluster"], attributes["cluster"])
      - delete_key(attributes, "cluster")
      - set(attributes["exported_namespace"], attributes["namespace"])
      - delete_key(attributes, "namespace")
      - set(attributes["exported_job"], attributes["job"])
      - delete_key(attributes, "job")
      - set(attributes["exported_instance"], attributes["instance"])
      - delete_key(attributes, "instance")
      - set(attributes["exported_project_id"], attributes["project_id"])
      - delete_key(attributes, "project_id")

  batch:
    # batch metrics before sending to reduce API usage
    send_batch_max_size: 200
    send_batch_size: 200
    timeout: 5s

  memory_limiter:
    # drop metrics if memory usage gets too high
    check_interval: 1s
    limit_percentage: 65
    spike_limit_percentage: 20

exporters:
  googlemanagedprometheus:
    project: "PROJECT_ID"

service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [batch, memory_limiter, resource, transform]
      exporters: [googlemanagedprometheus]

這項設定會執行下列操作:

  • 設定 Prometheus 的 Kubernetes 服務探索抓取設定。詳情請參閱「抓取 Prometheus 指標」。
  • 手動設定 cluster、namespace 和 location 資源屬性。如要進一步瞭解資源屬性,包括 Amazon EKS 和 Azure AKS 的資源偵測,請參閱「偵測資源屬性」。
  • 在 googlemanagedprometheus 匯出工具中設定 project 選項。如要進一步瞭解匯出工具,請參閱「設定 googlemanagedprometheus 匯出工具」。

搭配使用現有的 Prometheus 設定和 OpenTelemetry Collector 的 prometheus 接收器時,請將所有單一錢幣符號字元 替換為雙錢幣符號字元 ,以免觸發環境變數替換。詳情請參閱「抓取 Prometheus 指標」。

如要瞭解在其他雲端設定收集器的最佳做法,請參閱 Amazon EKS 或 Azure AKS。

部署範例應用程式

範例應用程式會在 metrics 通訊埠發出 example_requests_total 計數器指標和 example_random_numbers 直方圖指標 (以及其他指標)。這個範例的資訊清單定義了三個副本。

執行下列指令來部署範例應用程式:

kubectl -n NAMESPACE_NAME apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/v0.19.4/examples/example-app.yaml

將收集器設定建立為 ConfigMap

建立設定並放入名為 config.yaml 的檔案後,請使用該檔案,根據 config.yaml 檔案建立 Kubernetes ConfigMap。部署收集器時,系統會掛接 ConfigMap 並載入檔案。

如要使用設定建立名為 otel-config 的 ConfigMap,請使用下列指令:

kubectl -n NAMESPACE_NAME create configmap otel-config --from-file config.yaml

部署收集器

建立名為 collector-deployment.yaml 的檔案,並加入以下內容:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: NAMESPACE_NAME:prometheus-test
rules:
- apiGroups: [""]
  resources:
  - pods
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: NAMESPACE_NAME:prometheus-test
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: NAMESPACE_NAME:prometheus-test
subjects:
- kind: ServiceAccount
  namespace: NAMESPACE_NAME
  name: default
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: otel-collector
spec:
  replicas: 1
  selector:
    matchLabels:
      app: otel-collector
  template:
    metadata:
      labels:
        app: otel-collector
    spec:
      containers:
      - name: otel-collector
        image: otel/opentelemetry-collector-contrib:0.165.1
        args:
        - --config
        - /etc/otel/config.yaml
        - --feature-gates=exporter.googlemanagedprometheus.intToDouble
        volumeMounts:
        - mountPath: /etc/otel/
          name: otel-config
      volumes:
      - name: otel-config
        configMap:
          name: otel-config

執行下列指令,在 Kubernetes 叢集中建立收集器 Deployment:

kubectl -n NAMESPACE_NAME create -f collector-deployment.yaml

Pod 啟動後,會抓取範例應用程式,並將指標回報給 Managed Service for Prometheus。

如要瞭解如何查詢資料,請參閱「使用 Cloud Monitoring 查詢」或「使用 Grafana 查詢」。

明確提供憑證

在 GKE 上執行時,OpenTelemetry Collector 會根據節點的服務帳戶,自動從環境擷取憑證。在非 GKE Kubernetes 叢集中,必須使用旗標或 GOOGLE_APPLICATION_CREDENTIALS 環境變數,明確將憑證提供給 OpenTelemetry Collector。

  1. 將背景資訊設為目標專案:

    gcloud config set project PROJECT_ID
    
  2. 建立服務帳戶:

    gcloud iam service-accounts create gmp-test-sa
    

    這個步驟會建立服務帳戶,您可能已在 Workload Identity Federation for GKE 操作說明中建立過。

  3. 將必要權限授予服務帳戶:

    gcloud projects add-iam-policy-binding PROJECT_ID\
      --member=serviceAccount:gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com \
      --role=roles/monitoring.metricWriter
    

  4. 為服務帳戶建立並下載金鑰:

    gcloud iam service-accounts keys create gmp-test-sa-key.json \
      --iam-account=gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com
    
  5. 將金鑰檔案新增為非 GKE 叢集的 Secret:

    kubectl -n NAMESPACE_NAME create secret generic gmp-test-sa \
      --from-file=key.json=gmp-test-sa-key.json
    

  6. 開啟 OpenTelemetry Deployment 資源進行編輯:

    kubectl -n NAMESPACE_NAME edit deployment otel-collector
    
  1. 將粗體文字新增至資源:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      namespace: NAMESPACE_NAME
      name: otel-collector
    spec:
      template
        spec:
          containers:
          - name: otel-collector
            env:
            - name: "GOOGLE_APPLICATION_CREDENTIALS"
              value: "/gmp/key.json"
    ...
            volumeMounts:
            - name: gmp-sa
              mountPath: /gmp
              readOnly: true
    ...
          volumes:
          - name: gmp-sa
            secret:
              secretName: gmp-test-sa
    ...
    

  2. 儲存檔案並關閉編輯器。套用變更後,系統會重新建立 Pod,並開始使用指定的服務帳戶向指標後端進行驗證。

抓取 Prometheus 指標

本節和後續章節將提供使用 OpenTelemetry Collector 的其他自訂資訊。這項資訊在某些情況下可能很有幫助,但並非執行「設定 OpenTelemetry Collector」中所述範例的必要資訊。

如果應用程式已公開 Prometheus 端點,OpenTelemetry Collector 可以使用與任何標準 Prometheus 設定相同的抓取設定格式,抓取這些端點。如要這麼做,請在收集器設定中啟用 Prometheus 接收器。

Kubernetes Pod 的 Prometheus 接收器設定可能如下所示:

receivers:
  prometheus:
    config:
      scrape_configs:
      - job_name: 'kubernetes-pods'
        kubernetes_sd_configs:
        - role: pod
        relabel_configs:
        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
          action: keep
          regex: true
        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
          action: replace
          target_label: __metrics_path__
          regex: (.+)
        - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
          action: replace
          regex: (.+):(?:\d+);(\d+)
          replacement: $$1:$$2
          target_label: __address__
        - action: labelmap
          regex: __meta_kubernetes_pod_label_(.+)

service:
  pipelines:
    metrics:
      receivers: [prometheus]

這項抓取設定是以服務探索為基礎,您可以視需要修改,以便抓取應用程式。

搭配使用現有的 Prometheus 設定和 OpenTelemetry Collector 的 prometheus 接收器時,請將所有單一錢幣符號字元 替換為雙錢幣符號字元 ,以免觸發環境變數替換。對於 relabel_configs 區段中的 replacement 值,這點尤為重要。舉例來說,假設您有以下 relabel_config 區段:

- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
  action: replace
  regex: (.+):(?:\d+);(\d+)
  replacement: $1:$2
  target_label: __address__

然後改寫為:

- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
  action: replace
  regex: (.+):(?:\d+);(\d+)
  replacement: $$1:$$2
  target_label: __address__

詳情請參閱 OpenTelemetry 說明文件。

接下來,強烈建議您使用處理器設定指標格式。在許多情況下,您必須使用處理器,才能正確設定指標格式。

新增處理器

OpenTelemetry 處理器會在匯出前修改遙測資料。您可以使用下列處理器,確保指標寫入格式與 Managed Service for Prometheus 相容。

偵測資源屬性

OpenTelemetry 適用的 Managed Service for Prometheus 匯出工具會使用 prometheus_target 受監控資源,不重複識別時間序列資料點。匯出工具會從指標資料點的資源屬性中,剖析必要的受監控資源欄位。系統會從下列欄位和屬性擷取值:

  • project_id:由應用程式預設憑證、gcp.project.id 或匯出工具設定中的 project 自動偵測 (請參閱設定匯出工具)
  • location:location、cloud.availability_zone、cloud.region
  • cluster:cluster、k8s.cluster.name
  • namespace:namespace、k8s.namespace.name
  • job:service.name + service.namespace
  • instance:service.instance.id

如果未將這些標籤設為不重複的值,匯出至 Managed Service for Prometheus 時,可能會發生「時間序列重複」錯誤。在許多情況下,系統會自動偵測這些標籤的值,但有時您可能需要自行對應。本節其餘部分將說明這些情境。

Prometheus 接收器會根據抓取設定中的 job_name 自動設定 service.name 屬性,並根據抓取目標的 instance 設定 service.instance.id 屬性。在抓取設定中使用 role: pod 時,接收器也會設定 k8s.namespace.name。

如果可以,請使用資源偵測處理器自動填入其他屬性。不過,視環境而定,系統可能無法自動偵測某些屬性。在這種情況下,您可以使用其他處理器,手動插入這些值或從指標標籤剖析這些值。以下各節說明如何設定偵測各平台上的資源。

GKE

在 GKE 上執行 OpenTelemetry 時,您必須啟用資源偵測處理器,才能填寫資源標籤。請確認指標不含任何保留的資源標籤。如果無法避免這種情況,請參閱「重新命名屬性,避免資源屬性衝突」。

processors:
  resourcedetection:
    detectors: [gcp]
    timeout: 10s

您可以直接將這個部分複製到設定檔,取代現有的 processors 部分。

Amazon EKS

EKS 資源偵測工具不會自動填入 cluster 或 namespace 屬性。您可以使用資源處理器手動提供這些值,如下例所示:

processors:
  resourcedetection:
    detectors: [eks]
    timeout: 10s

  resource:
    attributes:
    - key: "cluster"
      value: "my-eks-cluster"
      action: upsert
    - key: "namespace"
      value: "my-app"
      action: upsert

您也可以使用 groupbyattrs 處理器,從指標標籤轉換這些值 (請參閱下方的「將指標標籤移至資源標籤」)。

Azure AKS

AKS 資源偵測工具不會自動填入 cluster 或 namespace 屬性。您可以使用資源處理器手動提供這些值,如下例所示:

processors:
  resourcedetection:
    detectors: [aks]
    timeout: 10s

  resource:
    attributes:
    - key: "cluster"
      value: "my-eks-cluster"
      action: upsert
    - key: "namespace"
      value: "my-app"
      action: upsert

您也可以使用 groupbyattrs 處理器,從指標標籤轉換這些值;請參閱「將指標標籤移至資源標籤」。

地端部署和非雲端環境

如果使用地端部署或非雲端環境,您可能無法自動偵測任何必要的資源屬性。在這種情況下,您可以在指標中發出這些標籤,並將其移至資源屬性 (請參閱「將指標標籤移至資源標籤」),或手動設定所有資源屬性,如以下範例所示:

processors:
  resource:
    attributes:
    - key: "cluster"
      value: "my-on-prem-cluster"
      action: upsert
    - key: "namespace"
      value: "my-app"
      action: upsert
    - key: "location"
      value: "us-east-1"
      action: upsert

將收集器設定建立為 ConfigMap 說明如何使用設定。該部分假設您已將設定放入名為 config.yaml 的檔案中。

使用應用程式預設憑證執行收集器時,系統仍可自動設定 project_id 資源屬性。如果收集器無法存取應用程式預設憑證,請參閱「設定 project_id」。

或者,您也可以在環境變數 OTEL_RESOURCE_ATTRIBUTES 中,以半形逗號分隔的鍵/值組合清單,手動設定所需的資源屬性,例如:

export OTEL_RESOURCE_ATTRIBUTES="cluster=my-cluster,namespace=my-app,location=us-east-1"

接著,使用 env 資源偵測工具處理器設定資源屬性:

processors:
  resourcedetection:
    detectors: [env]

重新命名屬性,避免資源屬性衝突

如果指標已包含與必要資源屬性 (例如 location、cluster 或 namespace) 衝突的標籤,請重新命名,以免發生衝突。Prometheus 的慣例是在標籤名稱中加入前置字串 exported_。如要新增這個前置字串,請使用轉換處理器。

下列 processors 設定會重新命名任何潛在衝突,並解決指標中的任何衝突鍵:

processors:
  transform:
    # "location", "cluster", "namespace", "job", "instance", and "project_id" are reserved, and
    # metrics containing these labels will be rejected.  Prefix them with exported_ to prevent this.
    metric_statements:
    - context: datapoint
      statements:
      - set(attributes["exported_location"], attributes["location"])
      - delete_key(attributes, "location")
      - set(attributes["exported_cluster"], attributes["cluster"])
      - delete_key(attributes, "cluster")
      - set(attributes["exported_namespace"], attributes["namespace"])
      - delete_key(attributes, "namespace")
      - set(attributes["exported_job"], attributes["job"])
      - delete_key(attributes, "job")
      - set(attributes["exported_instance"], attributes["instance"])
      - delete_key(attributes, "instance")
      - set(attributes["exported_project_id"], attributes["project_id"])
      - delete_key(attributes, "project_id")

將指標標籤移至資源標籤

在某些情況下,指標可能會刻意回報 namespace 等標籤,因為匯出工具會監控多個命名空間。例如執行 kube-state-metrics 匯出工具時。

在這種情況下,您可以使用 groupbyattrs 處理器,將這些標籤移至資源屬性:

processors:
  groupbyattrs:
    keys:
    - namespace
    - cluster
    - location

在上述範例中,如果指標含有 namespace、cluster 或 location 標籤,這些標籤會轉換為相符的資源屬性。

限制 API 要求和記憶體用量

另外兩個處理器,即批次處理器和記憶體限制器處理器,可讓您限制收集器的資源消耗量。

批次處理

批次處理要求可讓您定義單一要求中要傳送的資料點數量。請注意,Cloud Monitoring 的限制為每項要求 200 個時間序列。使用下列設定啟用批次處理器:

processors:
  batch:
    # batch metrics before sending to reduce API usage
    send_batch_max_size: 200
    send_batch_size: 200
    timeout: 5s

記憶體限制

建議您啟用記憶體限制處理器,避免收集器在高處理量時當機。使用下列設定啟用處理功能:

processors:
  memory_limiter:
    # drop metrics if memory usage gets too high
    check_interval: 1s
    limit_percentage: 65
    spike_limit_percentage: 20

設定 googlemanagedprometheus 匯出工具

根據預設,在 GKE 上使用 googlemanagedprometheus 匯出工具時,不需要額外設定。在許多用途中,您只需要在 exporters 區段中使用空白區塊啟用這項功能:

exporters:
  googlemanagedprometheus:

不過,匯出工具確實提供一些選用的設定。以下各節將說明其他設定。

設定 project_id

如要將時間序列與 Google Cloud 專案建立關聯,prometheus_target受監控資源必須設定 project_id。

在 Google Cloud上執行 OpenTelemetry 時,Managed Service for Prometheus 匯出工具會根據找到的應用程式預設憑證,預設設定這個值。如果沒有可用的憑證,或您想覆寫預設專案,可以採取下列兩種做法:

  • 在匯出工具設定中設定 project
  • 在指標中加入 gcp.project.id 資源屬性。

強烈建議您盡可能使用 project_id 的預設 (未設定) 值,而非明確設定。

在匯出工具設定中設定 project

下列設定摘錄會將指標傳送至 Google Cloud 專案MY_PROJECT中的 Managed Service for Prometheus:

receivers:
  prometheus:
    config:
    ...

processors:
  resourcedetection:
    detectors: [gcp]
    timeout: 10s

exporters:
  googlemanagedprometheus:
    project: MY_PROJECT

service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [resourcedetection]
      exporters: [googlemanagedprometheus]

與先前範例相比,唯一的變更是新行 project: MY_PROJECT。如果您知道透過這個收集器傳送的所有指標都應傳送至 MY_PROJECT,這項設定就非常實用。

設定 gcp.project.id 資源屬性

您可以為指標新增 gcp.project.id 資源屬性,依指標設定專案關聯。將屬性值設為指標應關聯的專案名稱。

舉例來說,如果指標已有標籤 project,您可以使用 Collector 設定中的處理器,將這個標籤移至資源屬性,並重新命名為 gcp.project.id,如以下範例所示:

receivers:
  prometheus:
    config:
    ...

processors:
  resourcedetection:
    detectors: [gcp]
    timeout: 10s

  groupbyattrs:
    keys:
    - project

  resource:
    attributes:
    - key: "gcp.project.id"
      from_attribute: "project"
      action: upsert

exporters:
  googlemanagedprometheus:

service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [resourcedetection, groupbyattrs, resource]
      exporters: [googlemanagedprometheus]

設定用戶端選項

googlemanagedprometheus 匯出工具會使用 Managed Service for Prometheus 的 gRPC 用戶端。因此,您可以使用選用設定來設定 gRPC 用戶端:

  • compression:啟用 gRPC 要求的 gzip 壓縮功能,有助於在將資料從其他雲端傳送至 Managed Service for Prometheus 時,盡可能降低資料移轉費用 (有效值:gzip)。
  • user_agent:覆寫傳送至 Cloud Monitoring 的要求中的使用者代理程式字串;僅適用於指標。預設為 OpenTelemetry Collector 的版本和版本號碼,例如 opentelemetry-collector-contrib 0.165.1。
  • endpoint:設定指標資料的傳送端點。
  • use_insecure:如果設為 true,則使用 gRPC 做為通訊傳輸。只有在 endpoint 值不是「」時,才會生效。
  • grpc_pool_size:設定 gRPC 用戶端中的連線集區大小。
  • prefix:設定傳送至 Managed Service for Prometheus 的指標前置字串。預設值為 prometheus.googleapis.com。請勿變更這個前置字串,否則無法在 Cloud Monitoring UI 中使用 PromQL 查詢指標。

在多數情況下,您不需要變更這些值的預設值。不過,您可以視特殊情況變更這些設定。

所有這些設定都是在 googlemanagedprometheus 匯出工具區段的 metric 區塊下設定,如以下範例所示:

receivers:
  prometheus:
    config:
    ...

processors:
  resourcedetection:
    detectors: [gcp]
    timeout: 10s

exporters:
  googlemanagedprometheus:
    metric:
      compression: gzip
      user_agent: opentelemetry-collector-contrib 0.165.1
      endpoint: ""
      use_insecure: false
      grpc_pool_size: 1
      prefix: prometheus.googleapis.com

service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [resourcedetection]
      exporters: [googlemanagedprometheus]

後續步驟