OpenTelemetry Collector 시작하기

이 문서에서는 표준 Prometheus 측정항목을 스크래핑하고 이러한 측정항목을 Google Cloud Managed Service for Prometheus로 보고하도록 OpenTelemetry Collector를 설정하는 방법을 설명합니다. OpenTelemetry Collector는 Managed Service for Prometheus로 내보내도록 직접 배포 및 구성할 수 있는 에이전트입니다. 설정은 자체 배포된 컬렉션으로 Managed Service for Prometheus를 실행하는 것과 비슷합니다.

다음과 같은 이유로 자체 배포된 컬렉션에 대해 OpenTelemetry Collector를 선택할 수 있습니다.

  • OpenTelemetry Collector를 사용하면 파이프라인에 서로 다른 내보내기 도구를 구성하여 원격 분석 데이터를 여러 백엔드로 라우팅할 수 있습니다.
  • Collector는 또한 측정항목, 로그, trace 신호를 지원하므로, 이를 사용해서 하나의 에이전트에서 3개의 신호 유형을 모두 처리할 수 있습니다.
  • 공급업체에 영향을 받지 않는 OpenTelemetry 데이터 형식(OpenTelemetry 프로토콜 또는 OTLP)은 라이브러리 및 플러그인할 수 있는 Collector 구성요소의 강력한 에코시스템을 지원합니다. 이를 통해 데이터 수신, 처리, 내보내기에 대해 다양한 맞춤설정 옵션이 허용됩니다.

이러한 이점의 단점은 OpenTelemetry Collector를 실행하기 위해 자체 관리형 배포 및 유지보수 접근 방법이 필요하다는 것입니다. 사용할 접근 방법은 특정 요구에 따라 달라지지만, 이 문서에서는 Managed Service for Prometheus를 백엔드로 사용하여 OpenTelemetry Collector를 구성하는 권장 지침을 제공합니다.

시작하기 전에

이 섹션에서는 이 문서에 설명된 태스크에 필요한 구성에 대해 설명합니다.

프로젝트 및 도구 설정

Google Cloud Managed Service for Prometheus를 사용하려면 다음 리소스가 필요합니다.

  • Cloud Monitoring API가 사용 설정된 Google Cloud 프로젝트가 필요합니다.

    • Google Cloud 프로젝트가 없으면 다음을 수행합니다.

      1. Google Cloud 콘솔에서 새 프로젝트로 이동합니다.

        새 프로젝트 만들기

      2. 프로젝트 이름 필드에서 프로젝트 이름을 입력한 후 만들기를 클릭합니다.

      3. 결제로 이동:

        결제로 이동

      4. 페이지 상단에서 아직 선택하지 않았으면 바로 전에 만든 프로젝트를 선택합니다.

      5. 기존 결제 프로필을 선택하거나 새 결제 프로필을 만들라는 메시지가 표시됩니다.

      Monitoring API는 새 프로젝트에 대해 기본적으로 사용 설정됩니다.

    • Google Cloud 프로젝트가 이미 있으면 Monitoring API가 사용 설정되었는지 확인합니다.

      1. API 및 서비스로 이동합니다.

        API 및 서비스로 이동

      2. 프로젝트를 선택합니다.

      3. API 및 서비스 사용 설정을 클릭합니다.

      4. 'Monitoring'을 검색합니다.

      5. 검색 결과에서 'Cloud Monitoring API'를 클릭합니다.

      6. 'API 사용 설정'이 표시되지 않으면 사용 설정 버튼을 클릭합니다.

  • Kubernetes 클러스터가 필요합니다. Kubernetes 클러스터가 없으면 GKE 빠른 시작 안내를 따르세요.

또한 다음 명령줄 도구가 필요합니다.

  • gcloud
  • kubectl

gcloudkubectl 도구는 Google Cloud CLI의 일부입니다. 설치에 대한 자세한 내용은 Google Cloud CLI 구성요소 관리를 참조하세요. 설치한 gcloud CLI 구성요소를 보려면 다음 명령어를 실행하세요.

gcloud components list

환경 구성

프로젝트 ID 또는 클러스터 이름을 반복해서 입력하지 않으려면 다음 구성을 수행합니다.

  • 다음과 같이 명령줄 도구를 구성합니다.

    • Google Cloud 프로젝트의 ID를 참조하도록 gcloud CLI를 구성합니다.

      gcloud config set project PROJECT_ID
      
    • 클러스터를 사용하도록 kubectl CLI를 구성합니다.

      kubectl config set-cluster CLUSTER_NAME
      

    이러한 도구에 대한 자세한 내용은 다음을 참조하세요.

네임스페이스 설정

예시 애플리케이션의 일부로 만드는 리소스에 대해 NAMESPACE_NAME Kubernetes 네임스페이스를 만듭니다.

kubectl create ns NAMESPACE_NAME

서비스 계정 사용자 인증 정보 확인

Kubernetes 클러스터에 워크로드 아이덴티티가 사용 설정되어 있으면 이 섹션을 건너뛸 수 있습니다.

GKE에서 실행될 때 Managed Service for Prometheus는 Compute Engine 기본 서비스 계정을 기반으로 환경에서 사용자 인증 정보를 자동으로 검색합니다. 기본적으로 기본 서비스 계정에는 필요한 권한 monitoring.metricWritermonitoring.viewer가 있습니다. 워크로드 아이덴티티를 사용하지 않고 이전에 기본 노드 서비스 계정에서 이러한 역할 중 하나를 삭제한 경우 계속하기 전에 누락된 권한을 다시 추가해야 합니다.

GKE에서 실행하지 않는 경우 명시적으로 사용자 인증 정보 제공을 참조하세요.

워크로드 아이덴티티에 대한 서비스 계정 구성

Kubernetes 클러스터에 워크로드 아이덴티티가 사용 설정되어 있지 않으면 이 섹션을 건너뛰어도 됩니다.

Managed Service for Prometheus는 Cloud Monitoring API를 사용하여 측정항목 데이터를 캡처합니다. 클러스터가 워크로드 아이덴티티를 사용하는 경우 Kubernetes 서비스 계정에 Monitoring API에 대한 권한을 부여할 수 있습니다. 이 섹션에서는 다음을 설명합니다.

서비스 계정 만들기 및 바인딩

이 단계는 Managed Service for Prometheus 문서의 여러 위치에 표시됩니다. 이미 이전 태스크를 수행하는 동안 이 단계를 수행했으면 이를 반복할 필요가 없습니다. 서비스 계정 승인으로 건너뛰세요.

다음 명령어 시퀀스는 gmp-test-sa 서비스 계정을 만들고 NAMESPACE_NAME 네임스페이스의 기본 Kubernetes 서비스 계정에 바인딩합니다.

gcloud config set project PROJECT_ID \
&&
gcloud iam service-accounts create gmp-test-sa \
&&
gcloud iam service-accounts add-iam-policy-binding \
  --role roles/iam.workloadIdentityUser \
  --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 서비스 계정)에 역할을 부여합니다. 모니터링 역할에 대한 자세한 내용은 액세스 제어를 참조하세요.

다음 명령어는 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

워크로드 아이덴티티 구성 디버그

워크로드 아이덴티티 작동에 문제가 있으면 워크로드 아이덴티티 설정 확인워크로드 아이덴티티 문제 해결 가이드 문서를 참조하세요.

워크로드 아이덴티티를 구성할 때 오타 및 부분 복사-붙여넣기가 가장 일반적인 오류 소스이므로 이 안내의 코드 샘플에 삽입된 수정 가능한 변수 및 클릭 가능한 복사-붙여넣기 아이콘을 사용하는 것이 좋습니다.

프로덕션 환경의 워크로드 아이덴티티

이 문서에 설명된 예시에서는 Google Cloud 서비스 계정을 기본 Kubernetes 서비스 계정에 바인딩하고 Google Cloud 서비스 계정에 Monitoring API를 사용하기 위해 필요한 모든 권한을 부여합니다.

프로덕션 환경에서는 각 구성요소에 대해 서비스 계정이 있고, 각각 최소 권한이 포함된 세분화된 방법을 사용해야 할 수 있습니다. 워크로드 아이덴티티 관리를 위한 서비스 계정 구성에 대한 자세한 내용은 워크로드 아이덴티티 사용을 참조하세요.

OpenTelemetry Collector 설정

이 섹션에서는 예시 애플리케이션에서 측정항목을 스크래핑하고 데이터를 Google Cloud Managed Service for Prometheus로 전송하도록 OpenTelemetry Collector를 설정하고 사용하는 과정을 안내합니다. 자세한 구성 정보는 다음 섹션을 참조하세요.

OpenTelemetry Collector는 Managed Service for Prometheus 에이전트 바이너리와 동일합니다. OpenTelemetry 커뮤니티는 소스 코드, 바이너리, 컨테이너 이미지가 포함된 버전을 정기적으로 게시합니다.

권장사항 기본값을 사용하여 VM 또는 Kubernetes 클러스터에 이러한 아티팩트를 배포하거나 수집기 빌더를 사용하여 필요한 구성요소로만 구성된 자체 수집기를 빌드할 수 있습니다. Managed Service for Prometheus에 사용할 수집기를 빌드하려면 다음 구성요소가 필요합니다.

  • Managed Service for Prometheus에 측정항목을 기록하는 Managed Service for Prometheus 내보내기 도구
  • 측정항목을 스크래핑하는 수신자. 이 문서에서는 OpenTelemetry Prometheus 수신자를 사용한다고 가정하지만 Managed Service for Prometheus 내보내기 도구는 모든 OpenTelemetry 측정항목 수신자와 호환됩니다.
  • 환경에 따라 중요한 리소스 식별자를 포함하도록 측정항목을 일괄 처리하고 표시하는 프로세서

이러한 구성요소는 --config 플래그로 수집기에 전달되는 구성 파일을 사용하여 사용 설정됩니다.

다음 섹션에서는 이러한 각 구성요소를 구성하는 방법을 더 자세히 설명합니다. 이 문서에서는 GKE기타 위치에서 수집기를 실행하는 방법을 설명합니다.

수집기 구성 및 배포

Google Cloud 또는 다른 환경에서 컬렉션을 실행하는지에 관계없이 Managed Service for Prometheus로 내보내도록 OpenTelemetry 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 포드에서 측정항목 엔드포인트를 스크래핑하고 이러한 측정항목을 Managed Service for Prometheus로 내보냅니다. 파이프라인 프로세서는 데이터를 형식 지정하고 일괄 처리합니다.

서로 다른 플랫폼의 구성과 함께 이 구성의 각 부분이 수행하는 작업에 대한 자세한 내용은 아래에서 측정항목 스크래핑프로세서 추가에 대한 세부 섹션을 참조하세요.

OpenTelemetry Collector의 prometheus 수신기에서 기존 Prometheus 구성을 사용하는 경우 환경 변수 대체가 발생하지 않도록 모든 $ 문자를 $$ to avoid triggering environment variable substitution. For more information, see Scrape Prometheus metrics.

You can modify this config based on your environment, provider, and the metrics you want to scrape, but the example config is a recommended starting point for running on GKE.

Run the OpenTelemetry Collector outside Google Cloud

Running the OpenTelemetry Collector outside Google Cloud, such as on-premises or on other cloud providers, is similar to running the Collector on GKE. However, the metrics you scrape are less likely to automatically include data that best formats it for Managed Service for Prometheus. Therefore, you must take extra care to configure the collector to format the metrics so they are compatible with Managed Service for Prometheus.

You can the following config into a file called config.yaml to set up the OpenTelemetry Collector for deployment on a non-GKE Kubernetes cluster:

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]

This config does the following:

When using an existing Prometheus configuration with the OpenTelemetry Collector's prometheus receiver, replace any $ characters with $$으로 바꿉니다. 자세한 내용은 Prometheus 측정항목 스크래핑을 참조하세요.

다른 클라우드에서 수집기 구성에 대한 권장사항은 Amazon EKS 또는 Azure AKS를 참조하세요.

예시 애플리케이션 배포

예시 애플리케이션metrics 포트에서 example_requests_total 카운터 측정항목 및 example_random_numbers 히스토그램 측정항목을 내보냅니다. 이 예시의 매니페스트는 3개 복제본을 정의합니다.

예시 애플리케이션을 배포하려면 다음 명령어를 실행합니다.

kubectl -n NAMESPACE_NAME apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/v0.10.0/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.101.0
        args:
        - --config
        - /etc/otel/config.yaml
        volumeMounts:
        - mountPath: /etc/otel/
          name: otel-config
      volumes:
      - name: otel-config
        configMap:
          name: otel-config

다음 명령어를 실행하여 Kubernetes 클러스터에 수집기 배포를 만듭니다.

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

포드가 시작된 다음 샘플 애플리케이션을 스크래핑하고 측정항목을 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
    

    이 단계에서는 워크로드 아이덴티티 안내에 따라 이미 생성되었을 수 있는 서비스 계정을 만듭니다.

  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 클러스터 외의 클러스터에 보안 비밀로 추가합니다.

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

  6. 수정할 OpenTelemetry 배포 리소스를 엽니다.

    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. 파일을 저장하고 편집기를 닫습니다. 변경사항이 적용되고 포드가 다시 생성된 후 제공된 서비스 계정을 사용하여 측정항목 백엔드에 대해 인증을 시작합니다.

Prometheus 측정항목 스크래핑

이 섹션 및 이후 섹션에서는 OpenTelemetry Collector 사용에 대한 추가 맞춤설정 정보를 제공합니다. 이 정보는 특정 상황에서 유용할 수 있지만 OpenTelemetry Collector 설정에 설명된 예시를 실행하는 데 필수가 아닙니다.

애플리케이션이 이미 Prometheus 엔드포인트를 노출하는 경우 OpenTelemetry Collector는 표준 Prometheus 구성에 사용되는 동일한 스크래핑 구성 형식을 사용하여 이러한 엔드포인트를 스크래핑할 수 있습니다. 이렇게 하려면 수집기 구성에서 Prometheus 수신자를 사용 설정합니다.

Kubernetes 포드에 대한 간단한 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]

이것은 애플리케이션을 스크래핑하기 위해 필요에 따라 수정할 수 있는 간단한 서비스 검색 기반 스크래핑 구성입니다.

OpenTelemetry 수집기의 prometheus 수신기에서 기존 Prometheus 구성을 사용하는 경우 모든 $ 문자를 $$ to avoid triggering environment variable substitution. This is especially important to do for the replacement value within your relabel_configs section. For example, if you have the following relabel_config section:

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

Then rewrite it to be:

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


로 바꿉니다.

For more information, see the OpenTelemetry documentation.

Next, we strongly recommend that you use processors to format your metrics. In many cases, processors must be used to properly format your metrics.

Add processors

OpenTelemetry processors modify telemetry data before it is exported. You can use the processors below to ensure that your metrics are written in a format compatible with Managed Service for Prometheus.

Detect resource attributes

The Managed Service for Prometheus exporter for OpenTelemetry uses the prometheus_target monitored resource to uniquely identify time series data points. The exporter parses the required monitored-resource fields from resource attributes on the metric data points. The fields and the attributes from which the values are scraped are:

  • project_id: auto-detected by Application Default Credentials, gcp.project.id, or project in exporter config (see configuring the exporter)
  • 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

Failure to set these labels to unique values can result in "duplicate timeseries" errors when exporting to Managed Service for Prometheus.

The Prometheus receiver automatically sets the service.name attribute based on the job_name in the scrape config, and service.instance.id attribute based on the scrape target's instance. The receiver also sets k8s.namespace.name when using role: pod in the scrape config.

We recommend populating the other attributes automatically using the resource detection processor. However, depending on your environment, some attributes might not be automatically detectable. In this case, you can use other processors to either manually insert these values or parse them from metric labels. The following sections illustration configurations for doing this processing on various platforms

GKE

When running OpenTelemetry on GKE, you only need to enable the resource-detection processor to fill out the resource labels. Be sure that your metrics don't already contain any of the reserved resource labels. If this is unavoidable, see Avoid resource attribute collisions by renaming attributes.

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

This section can be copied directly into your config file, replacing the processors section if it already exists.

Amazon EKS

The EKS resource detector does not automatically fill in the cluster or namespace attributes. You can provide these values manually by using the resource processor, as shown in the following example:

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

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

You can also convert these values from metric labels using the groupbyattrs processor (see move metric labels to resource labels below).

Azure AKS

The AKS resource detector does not automatically fill in the cluster or namespace attributes. You can provide these values manually by using the resource processor, as shown in the following example:

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

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

You can also convert these values from metric labels by using the groupbyattrs processor; see Move metric labels to resource labels.

On-premises and non-cloud environments

With on-premises or non-cloud environments, you probably can't detect any of the necessary resource attributes automatically. In this case, you can emit these labels in your metrics and move them to resource attributes (see Move metric labels to resource labels), or manually set all of the resource attributes as shown in the following example:

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

Create your collector config as a ConfigMap describes how to use the config. That section assumes you have put your config in a file called config.yaml.

The project_id resource attribute can still be automatically set when running the Collector with Application Default Credentials. If your Collector does not have access to Application Default Credentials, see Setting project_id.

Alternatively, you can manually set the resource attributes you need in an environment variable, OTEL_RESOURCE_ATTRIBUTES, with a comma-separated list of key/value pairs, for example:

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

Then use the env resource detector processor to set the resource attributes:

processors:
  resourcedetection:
    detectors: [env]

Avoid resource attribute collisions by renaming attributes

If your metrics already contain labels that collide with the required resource attributes (such as location, cluster, or namespace), rename them to avoid the collision. The Prometheus convention is to add the prefix exported_ to the label name. To add this prefix, use the transform processor.

The following processors config renames any potential collisions and resolves any conflicting keys from the metric:

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")

Move metric labels to resource labels

In some cases, your metrics might be intentionally reporting labels such as namespace because your exporter is monitoring multiple namespaces. For example, when running the kube-state-metrics exporter.

In this scenario, these labels can be moved to resource attributes using the groupbyattrs processor:

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

In the above example, given a metric with the labels namespace, cluster, and/or location, those labels will be converted to the matching resource attributes.

Limit API requests and memory usage

Two other processors, the batch processor and memory limiter processor allow you to limit the resource consumption of your collector.

Batch processing

Batching requests lets you define how many data points to send in a single request. Note that Cloud Monitoring has a limit of 200 time series per request. Enable the batch processor by using the following settings:

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

Memory limiting

We recommend enabling the memory-limiter processor to prevent your collector from crashing at times of high throughput. Enable the processing by using the following settings:

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

Configure the googlemanagedprometheus exporter

By default, using the googlemanagedprometheus exporter on GKE requires no additional configuration. For many use cases you only need to enable it with an empty block in the exporters section:

exporters:
  googlemanagedprometheus:

However, the exporter does provide some optional configuration settings. The following sections describe the other configuration settings.

Setting project_id

To associate your time series with a Google Cloud project, the prometheus_target monitored resource must have project_id set.

When running OpenTelemetry on Google Cloud, the Managed Service for Prometheus exporter defaults to setting this value based on the Application Default Credentials it finds. If no credentials are available, or you want to override the default project, you have two options:

  • Set project in the exporter config
  • Add a gcp.project.id resource attribute to your metrics.

We strongly recommend using the default (unset) value for project_id rather than explicitly setting it, when possible.

Set project in the exporter config

The following config excerpt sends metrics to Managed Service for Prometheus in the Google Cloud project MY_PROJECT:

receivers:
  prometheus:
    config:
    ...

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

exporters:
  googlemanagedprometheus:
    project: MY_PROJECT

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

The only change from previous examples is the new line project: MY_PROJECT. This setting is useful if you know that every metric coming through this Collector should be sent to MY_PROJECT.

Set gcp.project.id resource attribute

You can set project association on a per-metric basis by adding a gcp.project.id resource attribute to your metrics. Set the value of the attribute to the name of the project the metric should be associated with.

For example, if your metric already has a label project, this label can be moved to a resource attribute and renamed to gcp.project.id by using processors in the Collector config, as shown in the following example:

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]

Setting client options

The googlemanagedprometheus exporter uses gRPC clients for Managed Service for Prometheus. Therefore, optional settings are available for configuring the gRPC client:

  • compression: Enables gzip compression for gRPC requests, which is useful for minimizing data transfer fees when sending data from other clouds to Managed Service for Prometheus (valid values: gzip).
  • user_agent: Overrides the user-agent string sent on requests to Cloud Monitoring; only applies to metrics. Defaults to the build and version number of your OpenTelemetry Collector, for example, opentelemetry-collector-contrib 0.101.0.
  • endpoint: Sets the endpoint to which metric data is going to be sent.
  • use_insecure: If true, uses gRPC as the communication transport. Has an effect only when the endpoint value is not "".
  • grpc_pool_size: Sets the size of the connection pool in the gRPC client.
  • prefix: Configures the prefix of metrics sent to Managed Service for Prometheus. Defaults to prometheus.googleapis.com. Don't change this prefix; doing so causes metrics to not be queryable with PromQL in the Cloud Monitoring UI.

In most cases, you don't need to change these values from their defaults. However, you can change them to accommodate special circumstances.

All of these settings are set under a metric block in the googlemanagedprometheus exporter section, as shown in the following example:

receivers:
  prometheus:
    config:
    ...

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

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

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

What's next