Search code examples
pythonkuberneteskubernetes-helm

How to get Pod CPU and Memory Usage from metrics-server?


I currently have metric server installed and running in my K8s cluster.

Utilizing the the kubernetes python lib, I am able to make this request to get pod metrics:

from kubernetes import client

api_client = client.ApiClient()
ret_metrics = api_client.call_api(
            '/apis/metrics.k8s.io/v1beta1/namespaces/' + 'default' + '/pods', 'GET',
            auth_settings=['BearerToken'], response_type='json', _preload_content=False)
response = ret_metrics[0].data.decode('utf-8')
print('RESP', json.loads(response))

In the response, for each pod all containers will be listed with their cpu and memory usage:

'containers': [{'name': 'elasticsearch', 'usage': {'cpu': '14122272n', 'memory': '826100Ki'}}]}

Now my question is how do i get these metrics for the pod itself and not its containers? I'd rather not have to sum up the metrics from each container if possible. Is there any way to do this with metrics-server?


Solution

  • Based on the official repository you can query kubelet stats endpoint:

    $ curl --insecure https://<node url>:10250/stats/summary
    

    which will return stats of full pods. If you want to see metrics for pod/container itself, type:

    $ curl --insecure https://<node url>:10250/{namespace}/{podName}/{uid}/{containerName}
    

    Let's take a look for example:

    { "podRef": 
        { "name": "py588590", 
          "namespace": "myapp", 
          "uid": "e0056f1a" 
        }, 
      "startTime": "2019-10-16T03:57:47Z", 
      "containers": 
        [ 
          { "name": "py588590", 
            "startTime": "2019-10-16T03:57:50Z"
          }
        ]
    }
    

    These requests will works:

    http://localhost:10255/stats/myapp/py588590/e0056f1a/py588590
    

    You can also look for this article. I hope it will helps you.