5.9.3. 服务监控器

ServiceMonitor 是 Prometheus Operator 提供的自定义资源,用于发现 Service 对象中的 Endpoints,配置 Prometheus 以监控这些 pod。

在使用 Operator SDK 生成的基于 Go 的 Operator 中,GenerateServiceMonitor() 帮助函数可以获取 Service 对象并基于该对象生成 ServiceMonitor 对象。

其他资源

5.9.3.1. 创建服务监控器

Operator 作者可使用 metrics.CreateServiceMonitor() 帮助函数来添加已创建监控服务的服务目标发现,该函数接受新创建的 Service。

先决条件

  • 使用 Operator SDK 生成基于 Go 的 Operator
  • 基于 Kubernetes 的集群已部署 Prometheus Operator

流程

  • metrics.CreateServiceMonitor() 帮助函数添加至您的 Operator 代码中:

    import(
        "k8s.io/api/core/v1"
        "github.com/operator-framework/operator-sdk/pkg/metrics"
        "machine.openshift.io/controller-runtime/pkg/client/config"
    )
    func main() {
    
        ...
        // Populate below with the Service(s) for which you want to create ServiceMonitors.
        services := []*v1.Service{}
        // Create one ServiceMonitor per application per namespace.
        // Change the below value to name of the Namespace you want the ServiceMonitor to be created in.
        ns := "default"
        // restConfig is used for talking to the Kubernetes apiserver
        restConfig := config.GetConfig()
    
        // Pass the Service(s) to the helper function, which in turn returns the array of ServiceMonitor objects.
        serviceMonitors, err := metrics.CreateServiceMonitors(restConfig, ns, services)
        if err != nil {
            // Handle errors here.
        }
        ...
    }