Inizia a utilizzare OpenTelemetry Collector

Questo documento descrive come configurare OpenTelemetry Collector per eseguire lo scraping delle metriche Prometheus standard e generare report su queste metriche a Google Cloud Managed Service per Prometheus. OpenTelemetry Collector è un agente di cui puoi eseguire il deployment autonomamente e configurare per l'esportazione in Managed Service per Prometheus. La configurazione è simile all'esecuzione di Managed Service per Prometheus con una raccolta di cui è stato eseguito il deployment autonomo.

Potresti scegliere il raccoglitore OpenTelemetry rispetto alla raccolta di cui è stato eseguito il deployment autonomo per i seguenti motivi:

  • OpenTelemetry Collector consente di instradare i dati di telemetria a più backend configurando diversi esportatori nella pipeline.
  • Il raccoglitore supporta anche gli indicatori di metriche, log e tracce, quindi utilizzando questo strumento puoi gestire tutti e tre i tipi di indicatori in un unico agente.
  • Il formato dei dati indipendente dal fornitore di OpenTelemetry (OpenTelemetry Protocol o OTLP) supporta un solido ecosistema di librerie e componenti collegabili di Collector. Ciò offre una gamma di opzioni di personalizzazione per ricevere, elaborare ed esportare i dati.

Lo svantaggio per questi vantaggi è che l'esecuzione di un raccoglitore OpenTelemetry richiede un approccio al deployment e alla manutenzione autogestito. L'approccio che scegli dipenderà dalle tue esigenze specifiche, ma in questo documento offriamo linee guida consigliate per configurare il raccoglitore OpenTelemetry utilizzando Managed Service per Prometheus come backend.

Prima di iniziare

Questa sezione descrive la configurazione necessaria per le attività descritte in questo documento.

Configura progetti e strumenti

Per utilizzare Google Cloud Managed Service per Prometheus, sono necessarie le seguenti risorse:

  • Un progetto Google Cloud in cui è abilitata l'API Cloud Monitoring.

    • Se non hai un progetto Google Cloud, segui questi passaggi:

      1. Nella console Google Cloud, vai a Nuovo progetto:

        Creare un nuovo progetto

      2. Nel campo Nome progetto, inserisci un nome per il progetto e fai clic su Crea.

      3. Vai a Fatturazione:

        Vai a Fatturazione

      4. Seleziona il progetto appena creato, se non è già selezionato nella parte superiore della pagina.

      5. Ti viene chiesto di scegliere un profilo pagamenti esistente o di crearne uno nuovo.

      L'API Monitoring è abilitata per impostazione predefinita per i nuovi progetti.

    • Se hai già un progetto Google Cloud, assicurati che l'API Monitoring sia abilitata:

      1. Vai ad API e servizi:

        Vai ad API e servizi

      2. Seleziona il progetto.

      3. Fai clic su Abilita API e servizi.

      4. Cerca "Monitoring".

      5. Nei risultati di ricerca, fai clic su "API Cloud Monitoring".

      6. Se non viene visualizzato "API abilitata", fai clic sul pulsante Abilita.

  • Un cluster Kubernetes. Se non disponi di un cluster Kubernetes, segui le istruzioni riportate nella Guida rapida per GKE.

Sono inoltre necessari i seguenti strumenti a riga di comando:

  • gcloud
  • kubectl

Gli strumenti gcloud e kubectl fanno parte di Google Cloud CLI. Per informazioni sull'installazione, consulta Gestione dei componenti di Google Cloud CLI. Per visualizzare i componenti dell'interfaccia a riga di comando gcloud installati, esegui questo comando:

gcloud components list

Configura il tuo ambiente

Per evitare di inserire ripetutamente l'ID progetto o il nome del cluster, esegui questa configurazione:

  • Configura gli strumenti a riga di comando come segue:

    • Configura gcloud CLI per fare riferimento all'ID del tuo progetto Google Cloud:

      gcloud config set project PROJECT_ID
      
    • Configura l'interfaccia a riga di comando kubectl per utilizzare il tuo cluster:

      kubectl config set-cluster CLUSTER_NAME
      

    Per ulteriori informazioni su questi strumenti, consulta le seguenti risorse:

Configura uno spazio dei nomi

Crea lo spazio dei nomi Kubernetes NAMESPACE_NAME per le risorse create come parte dell'applicazione di esempio:

kubectl create ns NAMESPACE_NAME

Verificare le credenziali dell'account di servizio

Puoi saltare questa sezione se nel cluster Kubernetes è abilitata Workload Identity.

Durante l'esecuzione su GKE, Managed Service per Prometheus recupera automaticamente le credenziali dall'ambiente in base all'account di servizio predefinito di Compute Engine. L'account di servizio predefinito dispone delle autorizzazioni necessarie, monitoring.metricWriter e monitoring.viewer, per impostazione predefinita. Se non utilizzi Workload Identity e in precedenza hai rimosso uno di questi ruoli dall'account di servizio del nodo predefinito, dovrai aggiungere di nuovo le autorizzazioni mancanti prima di continuare.

Se non esegui le credenziali su GKE, consulta Fornire le credenziali in modo esplicito.

Configura un account di servizio per Workload Identity

Puoi saltare questa sezione se nel cluster Kubernetes non è abilitata Workload Identity.

Managed Service per Prometheus acquisisce i dati delle metriche utilizzando l'API Cloud Monitoring. Se il cluster utilizza Workload Identity, devi concedere all'API Monitoring l'autorizzazione del tuo account di servizio Kubernetes. In questa sezione vengono descritte le seguenti informazioni:

Crea e associa l'account di servizio

Questo passaggio viene visualizzato in diverse sezioni della documentazione di Managed Service per Prometheus. Se hai già eseguito questo passaggio come parte di un'attività precedente, non è necessario ripeterlo. Vai direttamente ad Autorizzare l'account di servizio.

La seguente sequenza di comandi crea l'account di servizio gmp-test-sa e lo associa all'account di servizio Kubernetes predefinito nello spazio dei nomi NAMESPACE_NAME:

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

Se utilizzi uno spazio dei nomi GKE o un account di servizio diverso, modifica i comandi in modo appropriato.

Autorizza l'account di servizio

I gruppi di autorizzazioni correlate vengono raccolti in ruoli e tu concedi i ruoli a un'entità, in questo esempio, l'account di servizio Google Cloud. Per ulteriori informazioni sui ruoli di Monitoring, consulta Controllo dell'accesso.

Il comando seguente concede all'account di servizio Google Cloud, gmp-test-sa, i ruoli dell'API Monitoring necessari per scrivere i dati delle metriche.

Se hai già concesso all'account di servizio Google Cloud un ruolo specifico nell'ambito di un'attività precedente, non sarà necessario ripeterlo.

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

Debug della configurazione di Workload Identity

Se hai difficoltà a far funzionare Workload Identity, consulta la documentazione per la verifica della configurazione di Workload Identity e la guida alla risoluzione dei problemi di Workload Identity.

Poiché gli errori di battitura e il copia-incolla parziale sono le fonti più comuni di errori durante la configurazione di Workload Identity, ti consigliamo vivamente di utilizzare le variabili modificabili e le icone di copia e incolla cliccabili incorporate negli esempi di codice di queste istruzioni.

Workload Identity in ambienti di produzione

L'esempio descritto in questo documento associa l'account di servizio Google Cloud all'account di servizio Kubernetes predefinito e fornisce all'account di servizio Google Cloud tutte le autorizzazioni necessarie per utilizzare l'API Monitoring.

In un ambiente di produzione, conviene utilizzare un approccio più granulare, con un account di servizio per ogni componente e ciascuno con autorizzazioni minime. Per ulteriori informazioni sulla configurazione degli account di servizio per la gestione dei carichi di lavoro e delle identità, consulta Utilizzo di Workload Identity.

Configurare OpenTelemetry Collector

Questa sezione illustra la configurazione e l'utilizzo del raccoglitore OpenTelemetry per eseguire lo scraping delle metriche da un'applicazione di esempio e per inviare i dati a Google Cloud Managed Service per Prometheus. Per informazioni dettagliate sulla configurazione, consulta le sezioni seguenti:

Il raccoglitore OpenTelemetry è analogo al programma binario dell'agente Managed Service per Prometheus. La community OpenTelemetry pubblica regolarmente release tra cui codice sorgente, programmi binari e immagini container.

Puoi eseguire il deployment di questi artefatti su VM o cluster Kubernetes utilizzando le impostazioni predefinite delle best practice oppure puoi utilizzare il generatore di raccoglitori per creare un raccoglitore personale composto solo dai componenti di cui hai bisogno. Per creare un raccoglitore da utilizzare con Managed Service per Prometheus, sono necessari i seguenti componenti:

  • L'esportatore di Managed Service per Prometheus, che scrive le tue metriche in Managed Service per Prometheus.
  • Un ricevitore per eseguire lo scraping delle tue metriche. In questo documento si presuppone che tu stia utilizzando il ricevitore OpenTelemetry Prometheus, ma l'esportatore di Managed Service per Prometheus è compatibile con qualsiasi ricevitore di metriche OpenTelemetry.
  • Processori per eseguire il batch e il markup delle metriche in modo da includere importanti identificatori di risorse a seconda dell'ambiente.

Questi componenti vengono abilitati utilizzando un file di configurazione che viene passato al raccoglitore con il flag --config.

Le sezioni seguenti spiegano come configurare ciascuno di questi componenti in modo più dettagliato. Questo documento descrive come eseguire il raccoglitore su GKE e altrove.

Configura ed esegui il deployment del raccoglitore

Sia che tu stia eseguendo la tua raccolta su Google Cloud o in un altro ambiente, puoi comunque configurare OpenTelemetry Collector per l'esportazione in Managed Service per Prometheus. La principale differenza sta nella configurazione del raccoglitore. In ambienti non Google Cloud, potrebbe essere necessaria un'ulteriore formattazione dei dati delle metriche affinché siano compatibili con Managed Service per Prometheus. Tuttavia, su Google Cloud, gran parte di questa formattazione può essere rilevata automaticamente dal raccoglitore.

Esegui OpenTelemetry Collector su GKE

Puoi copiare la seguente configurazione in un file denominato config.yaml per configurare il raccoglitore OpenTelemetry su GKE:

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]

La configurazione precedente utilizza il ricevitore Prometheus e l'utilità di esportazione di Managed Service per Prometheus per eseguire lo scraping degli endpoint delle metriche sui pod Kubernetes ed esportarle in Managed Service per Prometheus. I processori della pipeline formattano e in batch i dati.

Per ulteriori dettagli sulle funzioni di ogni parte di questa configurazione e sulle configurazioni per le diverse piattaforme, consulta le sezioni dettagliate riportate di seguito sulle metriche di scraping e sull'aggiunta di processori.

Quando utilizzi una configurazione Prometheus esistente con il ricevitore prometheus di OpenTelemetry Collector, sostituisci eventuali caratteri $ con $$ 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 $$ per evitare di attivare la sostituzione variabile di ambiente. Per maggiori informazioni, consulta Eseguire lo scraping delle metriche di Prometheus.

Per informazioni sulle best practice per la configurazione del raccoglitore su altri cloud, consulta Amazon EKS o Azure AKS.

Esegui il deployment dell'applicazione di esempio

L'applicazione di esempio emette la metrica contatore example_requests_total e l'istogramma example_random_numbers (tra le altre) sulla porta metrics. Il manifest per questo esempio definisce tre repliche.

Per eseguire il deployment dell'applicazione di esempio, esegui questo comando:

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

Crea la configurazione del raccoglitore come ConfigMap

Dopo aver creato la configurazione e averla inserita in un file denominato config.yaml, utilizza questo file per creare un ConfigMap Kubernetes basato sul tuo file config.yaml. Al termine del deployment, il raccoglitore monta il ConfigMap e carica il file.

Per creare un ConfigMap denominato otel-config con la tua configurazione, utilizza il seguente comando:

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

esegui il deployment del raccoglitore

Crea un file denominato collector-deployment.yaml con i seguenti contenuti:

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

Crea il deployment del raccoglitore nel tuo cluster Kubernetes eseguendo questo comando:

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

Dopo l'avvio, il pod esegue lo scraping dell'applicazione di esempio e segnala le metriche a Managed Service per Prometheus.

Per informazioni su come eseguire query sui dati, consulta Eseguire query con Cloud Monitoring o Eseguire query con Grafana.

Fornisci le credenziali in modo esplicito

Durante l'esecuzione su GKE, OpenTelemetry Collector recupera automaticamente le credenziali dall'ambiente in base all'account di servizio del nodo. Nei cluster Kubernetes non GKE, le credenziali devono essere fornite esplicitamente a OpenTelemetry Collector utilizzando flag o la variabile di ambiente GOOGLE_APPLICATION_CREDENTIALS.

  1. Imposta il contesto sul progetto di destinazione:

    gcloud config set project PROJECT_ID
    
  2. Crea un account di servizio:

    gcloud iam service-accounts create gmp-test-sa
    

    Questo passaggio crea l'account di servizio che potresti avere già creato nelle istruzioni di Workload Identity.

  3. Concedi le autorizzazioni richieste all'account di servizio:

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

  4. Crea e scarica una chiave per l'account di servizio:

    gcloud iam service-accounts keys create gmp-test-sa-key.json \
      --iam-account=gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com
    
  5. Aggiungi il file della chiave come secret al cluster non GKE:

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

  6. Apri la risorsa del deployment OpenTelemetry da modificare:

    kubectl -n NAMESPACE_NAME edit deployment otel-collector
    
  1. Aggiungi il testo visualizzato in grassetto alla risorsa:

    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. Salva il file e chiudi l'editor. Una volta applicata la modifica, i pod vengono ricreati e viene avviata l'autenticazione nel backend della metrica con l'account di servizio specificato.

Esegui lo scraping delle metriche di Prometheus

Questa sezione e quella successiva forniscono ulteriori informazioni di personalizzazione per l'utilizzo di OpenTelemetry Collector. Queste informazioni potrebbero essere utili in determinate situazioni, ma nessuna di queste è necessaria per eseguire l'esempio descritto in Configurare il raccoglitore OpenTelemetry.

Se le applicazioni stanno già esponendo gli endpoint Prometheus, OpenTelemetry Collector può eseguire lo scraping di questi endpoint utilizzando lo stesso formato di configurazione di scraping che useresti con qualsiasi configurazione Prometheus standard. A tale scopo, abilita il ricevitore Prometheus nella configurazione del raccoglitore.

Una configurazione ricevitore Prometheus semplice per pod Kubernetes potrebbe essere simile alla seguente:

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]

Questa è una semplice configurazione di scrape basata Service Discovery che puoi modificare secondo necessità per eseguire lo scraping delle applicazioni.

Quando utilizzi una configurazione Prometheus esistente con il ricevitore prometheus di OpenTelemetry, sostituisci tutti i caratteri $ con $$ 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