简体   繁体   English

如何通过 client-go 和 golang 检索 kubernetes 指标

[英]How to retrieve kubernetes metrics via client-go and golang

I want to access metrics from kubernetes with golang.我想使用 golang 从 kubernetes 访问指标。 Something like cpu and memory per node as well as the same for pods and/or namespaces.每个节点的 CPU 和内存以及 Pod 和/或命名空间的类似内容。

I am kind of lost here because the documentation is not as clear as it could be.我有点迷失在这里,因为文档不够清晰。

I have learned that there is heapster (which is deprecated according to the github repo).我了解到有heapster (根据 github repo 已弃用)。 There is also metric server and a rest api.还有metric server和休息 api。

Where can I find some examples to get started?在哪里可以找到一些入门示例? I do not want to install another app, package or service in kubernetes.我不想在 kubernetes 中安装另一个应用程序、包或服务。 I'd like to get the information as native as possible.我想获得尽可能本地化的信息。 What is the preferred way to access these information with client-go and golang?使用 client-go 和 golang 访问这些信息的首选方式是什么?

There's a much better API for this: https://github.com/kubernetes/metrics .有一个更好的 API: https : //github.com/kubernetes/metrics Using this, you don't have to create the data structs or handle row byte slices.使用它,您不必创建数据结构或处理行字节切片。

import (
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
  ...
)

...
clientset, err := metricsv.NewForConfig(config)
podMetricsList, err := clientset.MetricsV1beta1().PodMetricses("").List(metav1.ListOptions{})

As explained in the question, the documentations are not clear for a beginner. 正如问题中所解释的那样,对于初学者来说, 文档并不清楚。 Even go-client examples retrieve the data, I wanted to get Type support. 即使是go-client示例也会检索数据,我想获得Type支持。

As it explained by above answer , you can get the data in []byte in JSON format. 正如上面的答案所解释的那样,你可以用JSON格式的[]字节获取数据。 This is how I did it. 这就是我做到的。

package main

import (
    "encoding/json"
    "fmt"
    "time"

    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
)

// PodMetricsList : PodMetricsList
type PodMetricsList struct {
    Kind       string `json:"kind"`
    APIVersion string `json:"apiVersion"`
    Metadata   struct {
        SelfLink string `json:"selfLink"`
    } `json:"metadata"`
    Items []struct {
        Metadata struct {
            Name              string    `json:"name"`
            Namespace         string    `json:"namespace"`
            SelfLink          string    `json:"selfLink"`
            CreationTimestamp time.Time `json:"creationTimestamp"`
        } `json:"metadata"`
        Timestamp  time.Time `json:"timestamp"`
        Window     string    `json:"window"`
        Containers []struct {
            Name  string `json:"name"`
            Usage struct {
                CPU    string `json:"cpu"`
                Memory string `json:"memory"`
            } `json:"usage"`
        } `json:"containers"`
    } `json:"items"`
}

func getMetrics(clientset *kubernetes.Clientset, pods *PodMetricsList) error {
    data, err := clientset.RESTClient().Get().AbsPath("apis/metrics.k8s.io/v1beta1/pods").DoRaw()
    if err != nil {
        return err
    }
    err = json.Unmarshal(data, &pods)
    return err
}

func main() {
    // creates the in-cluster config
    // https://github.com/kubernetes/client-go/tree/master/examples#configuration
    config, err := rest.InClusterConfig()
    if err != nil {
        panic(err.Error())
    }
    // creates the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
    var pods PodMetricsList
    err = getMetrics(clientset, &pods)
    if err != nil {
        panic(err.Error())
    }
    for _, m := range pods.Items {
        fmt.Println(m.Metadata.Name, m.Metadata.Namespace, m.Timestamp.String())
    }
}

Install following Go packages: go get -u k8s.io/client-go/kubernetes k8s.io/client-go/rest 安装以下Go包: go get -u k8s.io/client-go/kubernetes k8s.io/client-go/rest

You can use following endpoints to retrieve the data as you want; 您可以使用以下端点来根据需要检索数据;

  • Nodes: apis/metrics.k8s.io/v1beta1/nodes 节点: apis/metrics.k8s.io/v1beta1/nodes
  • Pods: apis/metrics.k8s.io/v1beta1/pods Pods: apis/metrics.k8s.io/v1beta1/pods
  • Pods of default namespace: apis/metrics.k8s.io/v1beta1/namespaces/default/pods default命名空间的apis/metrics.k8s.io/v1beta1/namespaces/default/podsapis/metrics.k8s.io/v1beta1/namespaces/default/pods
  • Specific Pod: /apis/metrics.k8s.io/v1beta1/namespaces/default/pods/<POD-NAME> 具体Pod: /apis/metrics.k8s.io/v1beta1/namespaces/default/pods/<POD-NAME>

NOTE : You may need to change the Type before json.Unmarshal . 注意 :您可能需要在json.Unmarshal之前更改类型。 You can define the Type only for the field which you are interested with. 您可以仅为您感兴趣的字段定义类型。

Here's an example of using the REST API to query node metrics and return a []byte in JSON format. 下面是使用REST API查询节点指标并以JSON格式返回[]字节的示例。 Replace "nodes" with "pods" to get pod/container metrics. 将“节点”替换为“pods”以获取pod / container指标。

data, err := clientset.RESTClient().Get().AbsPath("apis/metrics.k8s.io/v1beta1/nodes").DoRaw()

From the latest version of client-go you have to add a Context to DoRaw() .从最新版本的 client-go 开始,您必须将 Context 添加到DoRaw() For example use context.TODO() importing the context library.例如使用context.TODO()导入上下文库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM