Saltar al contenido

ServiceMonitor y PodMonitor de Prometheus: ¡No te pierdas los nuevos conceptos!

black flat screen tv turned on near black and gray audio component

Descubre las diferencias entre dos de los CRDs más utilizados del Operador Prometheus y cómo usar cada uno de ellos.

Conceptos de Prometheus: ServiceMonitor y PodMonitor

Foto de Ibrahim Boran en Unsplash

ServiceMonitor y PodMonitor son términos que comenzarás a ver más a menudo cuando se hable de usar Prometheus. Hemos cubierto mucho sobre Prometheus en artículos anteriores. Es una de las principales referencias cuando hablamos de monitoreo en un entorno nativo de la nube y está especialmente enfocado en el ecosistema de Kubernetes.

Prometheus tiene un nuevo modelo de implementación bajo el Marco del Operador de Kubernetes en tiempos recientes. Eso ha generado varios cambios en términos de recursos y cómo configuramos varios aspectos del monitoreo de nuestras cargas de trabajo. Algunos de estos conceptos ahora se gestionan como Definición de Recurso Personalizado (CRD) que se incluyen para simplificar la configuración del sistema y estar más alineados con las capacidades de la propia plataforma de Kubernetes. Esto es genial pero, al mismo tiempo, cambia cómo necesitamos usar esta excelente herramienta de monitoreo para cargas de trabajo nativas de la nube.

Hoy, cubriremos dos de estos nuevos CRDs, uno de los más relevantes: ServiceMonitor y PodMonitor. Estos son los nuevos objetos que especifican los recursos que estarán bajo el alcance de monitoreo para la plataforma, y cada uno de ellos cubre un tipo diferente de objeto, como puedes imaginar: Servicios y Pods.

Cada uno de ellos tiene su archivo de definición con sus campos y metadatos particulares, y para destacarlos, presentaré un ejemplo para cada uno de ellos a continuación:

Service Monitor

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  labels:
    serviceMonitorSelector: prometheus
  name: prometheus
  namespace: prometheus
spec:
  endpoints:
  - interval: 30s
    targetPort: 9090
    path: /metrics
  namespaceSelector:
    matchNames:
    - prometheus
  selector:
    matchLabels:
      operated-prometheus: "true"

Pod Monitor

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: front-end
  labels:
    name: front-end
spec:
  namespaceSelector:
    matchNames:
      - sock-shop
  selector:
    matchLabels:
      name: front-end
  podMetricsEndpoints:
  - targetPort: 8079

Como puedes ver, las definiciones de los componentes son muy similares y muy intuitivas, enfocándose en el selector para detectar qué pods o servicios debemos monitorear y algunos datos sobre el objetivo específico del monitoreo, para que Prometheus sepa cómo extraerlos.

Si deseas echar un vistazo más en detalle a cualquier opción que puedas configurar en este CRD, te recomendaría que eches un vistazo a esta URL que incluye una documentación detallada campo por campo de los CRDs más comunes:

Estos componentes pertenecerán a la definición de tus cargas de trabajo, lo que significa que la creación y el mantenimiento de estos objetos serán responsabilidad de los desarrolladores de la aplicación.

Eso es genial por varias razones:

  • Incluirá el aspecto de Monitoreo del propio componente, por lo que nunca olvidarás agregar la configuración de un componente específico. Eso significa que se puede incluir en los archivos YAML duplicados o en el Helm Chart o en recursos de Kustomize como otro recurso necesario.
  • Descentralizará la configuración de monitoreo haciéndola más ágil, y progresará a medida que lo hagan los componentes de software.
  • Reducirá el impacto en otros componentes monitoreados ya que no hay necesidad de actuar en ningún archivo o recurso estándar, por lo que cualquier carga de trabajo diferente continuará funcionando como se espera.

Ambos objetos son muy similares en sus propósitos ya que ambos extraen todos los endpoints que coinciden con el selector que agregamos. Entonces, ¿en qué casos debería usar uno u otro?

La respuesta será sencilla. Por defecto, optarás por un ServiceMonitor porque proporcionará las métricas del propio servicio y de cada uno de los endpoints que tiene el servicio, por lo que cada uno de los pods que están implementando el servicio será descubierto y extraído como parte de esta acción.

Entonces, ¿en qué casos debería usar PodMonitor? Donde la carga de trabajo que estás tratando de monitorear no actúa detrás de un servicio, por lo que al no haber un servicio definido, no puedes usar ServiceMonitor. ¿Quieres algunos ejemplos de eso? ¡Traigamos algunos!

  • Servicios que interactúan usando otros protocolos que no son basados en HTTP, como Kafka, SQS/SNS, JMS, o similares.
  • Componentes como CronJobs, DaemonSets, o que no exponen ningún modelo de conexión entrante.

Así que espero que este artículo te ayude a entender la principal diferencia entre esos objetos y profundizar un poco más en cómo funcionan los nuevos recursos del Marco del Operador Prometheus. Continuaremos cubriendo otros aspectos en próximos artículos.

Prometheus ServiceMonitor and PodMonitor: Don’t Miss The New Concepts!

black flat screen tv turned on near black and gray audio component

Discover the differences between two of the most used CRDs from Prometheus Operator and how to use each of them.

Prometheus Concepts: ServiceMonitor and PodMonitor

Photo by Ibrahim Boran on Unsplash

ServiceMonitor and PodMonitor are terms that you will start to see more often when talking about using Prometheus. We have covered a lot about Prometheus in the past articles. It is one of the primary references when we talk about monitoring in a cloud-native environment and is specially focused on the Kubernetes ecosystem.

Prometheus has a new deployment model under the Kubernetes Operator Framework in recent times. That has generated several changes in terms of resources and how we configure several aspects of the monitoring of our workloads. Some of these concepts are now managed as Customer Resource Definition (CRD) that are included to simplify the system’s configuration and be more aligned with the capabilities of the Kubernetes platform itself. This is great but, at the same time, changes how we need to use this excellent monitoring tool for cloud-native workloads.

Today, we will cover two of these new CRDs, one of the most relevant ones: ServiceMonitor and PodMonitor. These are the new objects that specify the resources that will be under monitoring scope to the platform, and each of them covers a different type of object, as you can imagine: Services and Pods.

Each of them has its definition file with its particular fields and metadata, and to highlight them, I will present a sample for each of them below:

Service Monitor

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  labels:
    serviceMonitorSelector: prometheus
  name: prometheus
  namespace: prometheus
spec:
  endpoints:
  - interval: 30s
    targetPort: 9090
    path: /metrics
  namespaceSelector:
    matchNames:
    - prometheus
  selector:
    matchLabels:
      operated-prometheus: "true"

Pod Monitor

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: front-end
  labels:
    name: front-end
spec:
  namespaceSelector:
    matchNames:
      - sock-shop
  selector:
    matchLabels:
      name: front-end
  podMetricsEndpoints:
  - targetPort: 8079

As you can see, the definitions of the components are very similar and very intuitive, focusing on the selector to detect which pods or services we should monitor and some data regarding the specific target of the monitoring, so Prometheus knows how to scrape them.

If you want to take a look more in detail at any option you can configure on this CRD, I would recommend you to take a look at this URL which includes a detailed field to field documentation of the most common CRDs:

These components will belong to the definition of your workloads, which means that the creation and maintenance of these objects will be from the application’s developers.

That is great because several reasons:

  • It will include the Monitoring aspect of the component itself, so you will never forget the add the configuration from a specific component. That means it can be included in the duplicate YAML files or Helm Chart or a Kustomize resources as another needed resource.
  • It will de-centralize the monitoring configuration making it more agile, and it will progress as the software components do it.
  • It will reduce the impact on other monitored components as there is no need to act in any standard file or resource, so any different workloads will continue to work as expected.

Both objects are very similar in their purposes as both of them scrape all the endpoints that match the selector that we added. So, in which cases should I use one or the other?

The answer will be straightforward. By default, you will go with a ServiceMonitor because it will provide the metrics from the service itself and each of the endpoints that the service has, so each of the pods that are implementing the service will be discovered and scraped as part of this action.

So, in which cases should I use PodMonitor? Where the workload you are trying to monitor doesn’t act behind a service, so as there is no service defined, you cannot use ServiceMonitor. Do you want some examples of those? Let’s bring some!

  • Services that interact using other protocols that are not HTTP-based, such as Kafka, SQS/SNS, JMS, or similar ones.
  • Components such as CronJobs, DaemonSets, or non exposing any incoming connection model.

So I hope this article will help you understand the main difference between those objects and go a little deeper into how the new Prometheus Operator Framework resources work. We will continue covering other aspects in upcoming posts.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *