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

后端 未结 3 1542
误落风尘
误落风尘 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 07:59

    here is an example.

    package main
    
    import (
        "fmt"
    
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/tools/clientcmd"
        metrics "k8s.io/metrics/pkg/client/clientset/versioned"
    )
    
    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)
        }
        podMetrics, err := mc.MetricsV1beta1().PodMetricses(metav1.NamespaceAll).List(metav1.ListOptions{})
        if err != nil {
            fmt.Println("Error:", err)
            return
        }
        for _, podMetric := range podMetrics.Items {
            podContainers := podMetric.Containers
            for _, container := range podContainers {
                cpuQuantity, ok := container.Usage.Cpu().AsInt64()
                memQuantity, ok := container.Usage.Memory().AsInt64()
                if !ok {
                    return
                }
                msg := fmt.Sprintf("Container Name: %s \n CPU usage: %d \n Memory usage: %d", container.Name, cpuQuantity, memQuantity)
                fmt.Println(msg)
            }
    
        }
    }
    

提交回复
热议问题