Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use kubectl top node in kubernetes python?

UPDATE

Regarding space, I realized I can mount the root path '/' into the container and use this piece of code to get my stats:

import shutil

total, used, free = shutil.disk_usage("/")

print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))

Still Looking for a way to do it through Kubernetes itself, though.

Original Question

I'm building a service that part of its function is to monitor system resources for my kubernetes cluster (not specific pods - the entire machine the node runs on) And I realized that kubectl top node is a good way to get that information (excluding storage).

Is there a way to get this information using the kubernetes python package?

I've tried to find a solution in the package documentation and realized that action is not there. (maybe under a different name? I couldn't find it)
Also found this issue on Github which partially solves my problem but I'm still looking for something simpler.

My question: How can I check for system resources like Memory, storage, and CPU usage for my kubernetes node through the Kubernetes Python package?

like image 883
Oren_C Avatar asked Oct 30 '25 04:10

Oren_C


1 Answers

Resource usage metrics, such as pod or node CPU and memory usage, are available in Kubernetes through the Metrics API.
You can access the Metrics API using kubectl get --raw command, e.g.:

kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes

More examples can be found in the Metrics API documentation.


Using Kubernetes Python Client you should be able to check memory and cpu usage of Kubernetes nodes, just like with the kubectl top nodes command:
NOTE: Memory is in kilobytes but can easily be converted to megabytes.

#!/usr/bin/python
# Script name: usage_info.py

from kubernetes import client, config

config.load_kube_config()

api = client.CustomObjectsApi()
k8s_nodes = api.list_cluster_custom_object("metrics.k8s.io", "v1beta1", "nodes")


for stats in k8s_nodes['items']:
    print("Node Name: %s\tCPU: %s\tMemory: %s" % (stats['metadata']['name'], stats['usage']['cpu'], stats['usage']['memory']))

And sample output:

$ ./usage_info.py
Node Name: node01     CPU: 82845225n  Memory: 707408Ki
Node Name: node02     CPU: 99717207n  Memory: 613892Ki
Node Name: node03     CPU: 74841362n  Memory: 625316Ki

In terms of storage usage, I think it should be checked in a different way as this information isn't available at the /apis/metrics.k8s.io/v1beta1/nodes endpoint.

like image 87
matt_j Avatar answered Oct 31 '25 18:10

matt_j