snippets > read-kubernetes-metrics-server-data-using-golang

August 02, 2020

Read Kubernetes metrics-server data using Golang

First, get the metrics API client.

import (
  "fmt"
  "context"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/tools/clientcmd"
  metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)

// Get the config
config, err := clientcmd.BuildConfigFromFlags("", "<path_to_KUBECONFIG>")
if err != nil {
  panic(err.Error())
}

// Get the metrics client
metricsClientset, err := metricsv.NewForConfig(config)
if err != nil {
  panic(err.Error())
}

Get the data and store it in podMetricsList array.

namespace := "example"  // leave empty to get data from all namespaces
podMetricsList, err := metricsClientset.MetricsV1beta1().PodMetricses(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
  panic(err.Error())
}

Iterate over the results found.

for _, v := range podMetricsList.Items {
  fmt.Printf("%s\n", v.GetName())
  fmt.Printf("%s\n", v.GetNamespace())
  fmt.Printf("%vm\n", v.Containers[0].Usage.Cpu().MilliValue())
  fmt.Printf("%vMi\n", v.Containers[0].Usage.Memory().Value()/(1024*1024))
}

Note: if you’re inspecting pods that may have more than one container, you’ll need to iterate over v.Containers as well.