Get current resource usage of a pod in Kubernetes with Go client

后端 未结 3 1452
误落风尘
误落风尘 2021-02-06 07:45

The kubernetes go client has tons of methods and I can\'t find how I can get the current CPU & RAM usage of a specific (or all pods).

Can someone tell me what method

3条回答
  •  攒了一身酷
    2021-02-06 08:00

    It is correct that go-client does not have support for metrics type, but in the metrics package there is a pregenerated client that can be used for fetching metrics objects and assign them right away to the appropriate structure. The only thing you need to do first is to generate a config and pass it to metrics client. So a simple client for metrics would look like this:

    package main
    
    
    import (
        "k8s.io/client-go/tools/clientcmd"
        metrics "k8s.io/metrics/pkg/client/clientset/versioned"
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    )
    
    
    
    func main() {
        var kubeconfig, master string //empty, assuming inClusterConfig
        config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
        if err != nil{
            panic(err)
        }
    
        mc, err := metrics.NewForConfig(config)
        if err != nil {
            panic(err)
        }
    
        mc.MetricsV1beta1().NodeMetricses().Get("your node name", metav1.GetOptions{})
        mc.MetricsV1beta1().NodeMetricses().List(metav1.ListOptions{})
        mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).List(metav1.ListOptions{})
        mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).Get("your pod name", metav1.GetOptions{})
    }
    

    Each of the above methods from metric client returns an appropriate structure (you can check those here) and an error (if any) which you should process according to your requirements.

提交回复
热议问题