Comenzar a usar el recopilador de OpenTelemetry

En este documento, se describe cómo configurar el recopilador de OpenTelemetry para recopilar métricas estándar de Prometheus y, luego, informarlas a Google Cloud Managed Service para Prometheus. El recopilador de OpenTelemetry es un agente que puedes implementar tú mismo y configurar para exportar al servicio administrado para Prometheus. La configuración es similar a la ejecución de Managed Service para Prometheus con la recopilación implementada de forma automática.

Puedes elegir el recopilador de OpenTelemetry en lugar de la recopilación autoimplementada por los siguientes motivos:

  • El recopilador de OpenTelemetry te permite enrutar tus datos de telemetría a varios backends mediante la configuración de diferentes exportadores en tu canalización.
  • El recopilador también admite señales de métricas, registros y seguimientos, por lo que, cuando lo usas, puedes controlar los tres tipos de señales en un agente.
  • El formato de datos independiente del proveedor de OpenTelemetry (el protocolo de OpenTelemetry o OTLP) es compatible con un ecosistema sólido de bibliotecas y componentes de recopilador conectables. Esto permite una variedad de opciones de personalización para recibir, procesar y exportar tus datos.

La ventaja relativa de estos beneficios es que ejecutar un recopilador de OpenTelemetry requiere un enfoque de implementación y mantenimiento autoadministrado. El enfoque que elijas dependerá de tus necesidades específicas, pero en este documento, ofrecemos lineamientos recomendados para configurar el recopilador de OpenTelemetry con el servicio administrado para Prometheus como backend.

Antes de comenzar

En esta sección, se describe la configuración necesaria para las tareas descritas en este documento.

Configura proyectos y herramientas

Si deseas usar Google Cloud Managed Service para Prometheus, necesitas los siguientes recursos:

  • Un proyecto de Google Cloud con la API de Cloud Monitoring habilitada

    • Si no tienes un proyecto de Google Cloud, haz lo siguiente:

      1. En la consola de Google Cloud, ve a Proyecto Nuevo:

        Crear un proyecto nuevo

      2. En el campo Nombre del proyecto, ingresa un nombre para tu proyecto y, luego, haz clic en Crear.

      3. Ve a facturación:

        Ir a Facturación

      4. Selecciona el proyecto que acabas de crear si aún no está seleccionado en la parte superior de la página.

      5. Se te solicitará que elijas un perfil de pagos existente o que crees uno nuevo.

      La API de Monitoring está habilitada de forma predeterminada para proyectos nuevos.

    • Si ya tienes un proyecto de Google Cloud, asegúrate de que la API de Monitoring esté habilitada:

      1. Ve a API y servicios:

        Ir a API y servicios (APIs & Services)

      2. Selecciona tu proyecto.

      3. Haga clic en Habilitar API y servicios.

      4. Busca “Monitoring”.

      5. En los resultados de la búsqueda, haz clic en "API de Cloud Monitoring".

      6. Si no se muestra "API habilitada", haz clic en el botón Habilitar.

  • Un clúster de Kubernetes. Si no tienes un clúster de Kubernetes, sigue las instrucciones en la Guía de inicio rápido para GKE.

También necesitas las siguientes herramientas de línea de comandos:

  • gcloud
  • kubectl

Las herramientas gcloud y kubectl forman parte de la CLI de Google Cloud. Para obtener información sobre cómo instalarlos, consulta Administra los componentes de la CLI de Google Cloud. Para ver los componentes de la CLI de gcloud que instalaste, ejecuta el siguiente comando:

gcloud components list

Configura tu entorno

Para evitar ingresar repetidamente el ID del proyecto o el nombre del clúster, realiza la siguiente configuración:

  • Configura las herramientas de línea de comandos como se indica a continuación:

    • Configura la CLI de gcloud para hacer referencia al ID del proyecto de Google Cloud:

      gcloud config set project PROJECT_ID
      
    • Configura la CLI de kubectl para usar tu clúster:

      kubectl config set-cluster CLUSTER_NAME
      

    Para obtener más información sobre estas herramientas, consulta lo siguiente:

Configura un espacio de nombres

Crea el espacio de nombres NAMESPACE_NAME de Kubernetes para los recursos que crees como parte de la aplicación de ejemplo:

kubectl create ns NAMESPACE_NAME

Verifica las credenciales de la cuenta de servicio

Puedes omitir esta sección si tu clúster de Kubernetes tiene habilitada Workload Identity.

Cuando se ejecuta en GKE, el servicio administrado para Prometheus recupera credenciales de forma automática del entorno en función de la cuenta de servicio predeterminada de Compute Engine. La cuenta de servicio predeterminada tiene los permisos necesarios, monitoring.metricWriter y monitoring.viewer, de forma predeterminada. Si no usas Workload Identity y ya quitaste cualquiera de esas funciones de la cuenta de servicio de nodo predeterminada, tendrás que volver a agregar esos permisos faltantes antes de continuar.

Si no ejecutas en GKE, consulta Proporciona credenciales explícitamente.

Configura una cuenta de servicio para Workload Identity

Puedes omitir esta sección si tu clúster de Kubernetes no tiene habilitada Workload Identity.

El servicio administrado para Prometheus captura datos de métricas mediante la API de Cloud Monitoring. Si tu clúster usa Workload Identity, debes otorgar permiso a tu cuenta de servicio de Kubernetes a la API de Monitoring. En esta sección, se describe lo siguiente:

Crea y vincula la cuenta de servicio

Este paso aparece en varios lugares en la documentación del servicio administrado para Prometheus. Si ya realizaste este paso como parte de una tarea anterior, no es necesario que lo repitas. Ve a la sección Autoriza la cuenta de servicio.

Con la siguiente secuencia de comandos, se crea la cuenta de servicio gmp-test-sa y se la vincula a la cuenta de servicio de Kubernetes predeterminada en el espacio de nombres 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

Si usas un espacio de nombres o una cuenta de servicio de GKE diferentes, ajusta los comandos de forma adecuada.

Autoriza la cuenta de servicio

Los grupos de permisos relacionados se recopilan en funciones y se otorgan las funciones a una principal, en este ejemplo, la cuenta de servicio de Google Cloud. Para obtener más información sobre las funciones de Monitoring, consulta Control de acceso.

Con el siguiente comando, se otorga a la cuenta de servicio de Google Cloud, gmp-test-sa, las funciones de la API de Monitoring que necesita para leer datos de métricas.

Si ya otorgaste a la cuenta de servicio de Google Cloud una función específica como parte de la tarea anterior, no necesitas volver a hacerlo.

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

Depura la configuración de Workload Identity

Si tienes problemas para lograr que Workload Identity funcione, consulta la documentación a fin de verificar la configuración de Workload Identity y la Guía de solución de problemas de Workload Identity.

Como los errores tipográficos y de copia parcial son las fuentes de errores más comunes en la configuración de Workload Identity, recomendamos usar las variables editables y los íconos de copiar y pegar en los que se puede hacer clic incorporados en las muestras de código de estas instrucciones.

Workload Identity en entornos de producción

En el ejemplo descrito en este documento, se vincula la cuenta de servicio de Google Cloud a la cuenta de servicio de Kubernetes predeterminada y se le otorga a la cuenta de servicio de Google Cloud todos los permisos necesarios para usar la API de Monitoring.

En un entorno de producción, se recomienda usar un enfoque más detallado, con una cuenta de servicio para cada componente, cada una con permisos mínimos. Si deseas obtener más información sobre la configuración de cuentas de servicio para la administración de identidades de cargas de trabajo, consulta Usa Workload Identity.

Configura el recopilador de OpenTelemetry

En esta sección, se explica cómo configurar y usar el recopilador de OpenTelemetry para recopilar métricas de una aplicación de ejemplo y enviar los datos a Google Cloud Managed Service para Prometheus. Para obtener información detallada sobre la configuración, consulta las siguientes secciones:

El recopilador de OpenTelemetry es análogo al objeto binario del agente de Managed Service para Prometheus. La comunidad de OpenTelemetry publica versiones con regularidad, que incluyen el código fuente, los objetos binarios y las imágenes de contenedor.

Puedes implementar estos artefactos en VMs o clústeres de Kubernetes mediante las prácticas recomendadas predeterminadas o puedes usar el compilador de recopilador para compilar tu propio recopilador que consiste solo en un componentes que necesitas. Para compilar un recopilador para usar con el Servicio administrado para Prometheus, necesitas los siguientes componentes:

  • El exportador de Managed Service para Prometheus, que escribe tus métricas en Managed Service para Prometheus.
  • Un receptor para recopilar tus métricas. En este documento, se supone que usas el receptor de OpenTelemetry o Prometheus, pero el exportador de Managed Service para Prometheus es compatible con cualquier receptor de métricas de OpenTelemetry.
  • Procesadores para agrupar por lotes y marcar tus métricas para incluir identificadores de recursos importantes según tu entorno.

Estos componentes se habilitan mediante un archivo de configuración que se pasa al recopilador con la marca --config.

En las siguientes secciones, se analiza cómo configurar cada uno de estos componentes con más detalle. En este documento, se describe cómo ejecutar el recopilador en GKE y en otro lugar.

Configura e implementa el recopilador

Ya sea que ejecutes tu colección en Google Cloud o en otro entorno, aún puedes configurar el recopilador de OpenTelemetry para exportar al servicio administrado para Prometheus. La mayor diferencia estará en cómo configurar el recopilador. En entornos que no son de Google Cloud, puede haber un formato adicional de los datos de métricas que se necesita a fin de que sean compatibles con Managed Service para Prometheus. Sin embargo, en Google Cloud, el recopilador puede detectar automáticamente gran parte de este formato.

Ejecuta el recopilador de OpenTelemetry en GKE

Puedes copiar la siguiente configuración en un archivo llamado config.yaml para configurar el recopilador de OpenTelemetry en 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 configuración anterior usa el receptor de Prometheus y el exportador de servicios administrados para Prometheus a fin de recopilar los extremos de las métricas en los Pods de Kubernetes y exportaresas métricas a Managed Service para Prometheus. Los procesadores de canalizaciones formatean y agrupan los datos por lotes.

Para obtener más información sobre lo que hace cada parte de esta configuración, junto con las opciones de configuración de diferentes plataformas, consulta las secciones detalladas a continuación sobre recopilar métricas y agregar procesadores.

Cuando uses una configuración de Prometheus existente con el receptor prometheus del colector de OpenTelemetry, reemplaza cualquier carácter $ por $$ 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 $$ para evitar activar la sustitución de variables de entorno. Para obtener más información, consulta Recopila métricas de Prometheus.

Si deseas obtener información sobre las prácticas recomendadas para configurar el recopilador en otras nubes, consulta Amazon EKS o Azure AKS.

Implementa la aplicación de ejemplo

La aplicación de ejemplo emite la métrica de contador example_requests_total y la métrica de histograma example_random_numbers (entre otras) en su puerto metrics. El manifiesto para este ejemplo define tres réplicas

Para implementar la aplicación de ejemplo, ejecuta el siguiente comando:

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

Crea tu configuración de recopilador como un ConfigMap

Después de crear tu configuración y colocarla en un archivo llamado config.yaml, usa ese archivo para crear un ConfigMap de Kubernetes basado en tu archivo config.yaml. Cuando se implementa el recopilador, se activa el ConfigMap y carga el archivo.

Para crear un ConfigMap llamado otel-config con tu configuración, usa el siguiente comando:

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

Implementa el recopilador

Crea un archivo llamado collector-deployment.yaml con el siguiente contenido.

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

Para crear la implementación del recopilador en tu clúster de Kubernetes, ejecuta el siguiente comando:

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

Una vez que se inicia el Pod, se recopilan la aplicación de ejemplo y genera informes de las métricas del servicio administrado de Prometheus.

Si deseas obtener información sobre cómo consultar tus datos, visita Consulta mediante Cloud Monitoring o Consulta mediante Grafana.

Proporciona credenciales de forma explícita

Cuando se ejecuta en GKE, el recopilador de OpenTelemetry recupera de forma automática las credenciales del entorno en función de la cuenta de servicio del nodo. En clústeres de Kubernetes que no son de GKE, las credenciales deben proporcionarse de forma explícita al Recopilador de OpenTelemetry mediante marcas o la variable de entorno GOOGLE_APPLICATION_CREDENTIALS.

  1. Configura el contexto en tu proyecto de destino:

    gcloud config set project PROJECT_ID
    
  2. Crear una cuenta de servicio:

    gcloud iam service-accounts create gmp-test-sa
    

    En este paso, se crea la cuenta de servicio que puedes haber creado ya en las instrucciones de Workload Identity.

  3. Otorga permisos obligatorios a la cuenta de servicio:

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

  4. Crea y descarga una clave para la cuenta de servicio:

    gcloud iam service-accounts keys create gmp-test-sa-key.json \
      --iam-account=gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com
    
  5. Agrega el archivo de claves como un secreto a tu clúster que no es de GKE:

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

  6. Abre el recurso de implementación de OpenTelemetry para editarlo:

    kubectl -n NAMESPACE_NAME edit deployment otel-collector
    
  1. Agrega el texto que se muestra en negrita al recurso:

    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. Guarda el archivo y cierra el editor. Después de aplicar el cambio, los Pods se vuelven a crear y comienzan a autenticarse en el backend de la métrica con la cuenta de servicio determinada.

Recopila métricas de Prometheus

En esta sección y la posterior, se proporciona información de personalización adicional para usar el recopilador de OpenTelemetry. Esta información puede ser útil en ciertas situaciones, pero ninguna es necesaria para ejecutar el ejemplo descrito en Configura el recopilador de OpenTelemetry.

Si tus aplicaciones ya exponen extremos de Prometheus, el recopilador de OpenTelemetry puede recopilar esos extremos con el mismo formato de configuración de scraping que usarías con cualquier configuración estándar de Prometheus. Para ello, habilita el receptor de Prometheus en la configuración de recopilador.

Una configuración simple del receptor de Prometheus para los Pods de Kubernetes podría tener el siguiente aspecto:

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]

Esta es una configuración de scraping simple basada en el descubrimiento de servicios que puedes modificar según sea necesario para recopilar tus aplicaciones.

Cuando uses una configuración de Prometheus existente con el receptor prometheus del colector de OpenTelemetry, reemplaza cualquier carácter $ por $$ 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