How to get kubernetes resource information(overall CPU and memory usage) through APIs

7/29/2019

I have installed minikube in a VIM and I have service account token with all the privileges. Is there any API from kubernetes to fetch the resource usage(Overall).

-- Akshay chittal
google-kubernetes-engine
kubectl
kubernetes
kubernetes-pod
minikube

2 Answers

7/29/2019

If you install the kubernetes metrics server it will expose those metrics as an api https://github.com/kubernetes-incubator/metrics-server

-- TowmeyKaw
Source: StackOverflow

7/29/2019

To get CPU and Memory usage you can use (depending on the object you like to see) the following:

kubectl top pods or kubectl top nodes which will show you

$ kubectl top pods
NAME                       CPU(cores)   MEMORY(bytes)
nginx-1-5d4f8f66d9-xmhnh   0m           1Mi

Api reference might look like the following:

$ curl http://localhost:8080/apis/metrics.k8s.io/v1beta1/pods

...
{
      "metadata": {
        "name": "nginx-1-5d4f8f66d9-xmhnh",
        "namespace": "default",
        "selfLink": "/apis/metrics.k8s.io/v1beta1/namespaces/default/pods/nginx-1-5d4f8f66d9-xmhnh",
        "creationTimestamp": "2019-07-29T11:48:13Z"
      },
      "timestamp": "2019-07-29T11:48:11Z",
      "window": "30s",
      "containers": [
        {
          "name": "nginx",
          "usage": {
            "cpu": "0",
            "memory": "1952Ki"
          }
        }
      ]
    }
...

As for API there is few ways of accessing it.

You can use proxy by running kubectl proxy --port:8080 &

The following command runs kubectl in a mode where it acts as a reverse proxy. It handles locating the API server and authenticating.

See kubectl proxy for more details.

Then you can explore the API with curl, wget, or a browser, like so:

curl http://localhost:8080/api/

You can access it without proxy by using authentication token.

It is possible to avoid using kubectl proxy by passing an authentication token directly to the API server, like this:

Using grep/cut approach:

# Check all possible clusters, as you .KUBECONFIG may have multiple contexts:
kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'

# Select name of cluster you want to interact with from above output:
export CLUSTER_NAME="some_server_name"

# Point to the API server refering the cluster name
APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")

# Gets the token value
TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 -d)

# Explore the API with TOKEN
curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

And you can also access the API using several official client libraries for example Go or Python. Other libraries are available to see here.

-- Crou
Source: StackOverflow