Skip to content

Instantly share code, notes, and snippets.

@yene
Last active November 11, 2024 18:34
Show Gist options
  • Save yene/3cf7cecb31d1dde532da12db9224bb25 to your computer and use it in GitHub Desktop.
Save yene/3cf7cecb31d1dde532da12db9224bb25 to your computer and use it in GitHub Desktop.
Kubernetes Free CPU Requests
# Print out CPU requests of nodes and free amount of CPU
# This shows at a glance if we have room to deploy more pods.
# needs package kubernetes
import kubernetes.client
import os
from kubernetes import config
def get_pods():
v1 = kubernetes.client.CoreV1Api()
ret = v1.list_pod_for_all_namespaces(watch=False)
pods = ret.items
# sort pods
new_pods = []
for i in pods:
if i.spec.node_name is None:
i.spec.node_name = ""
cpu_request = 0
for container in i.spec.containers:
try:
cpu_request += normalize_cpu(container.resources.requests['cpu'])
except:
pass
new_pods.append({
"node_name": i.spec.node_name,
"namespace": i.metadata.namespace,
"name": i.metadata.name,
"cpu_request": cpu_request
})
new_pods.sort(key=lambda x: x['namespace'])
new_pods.sort(key=lambda x: x['node_name'])
return new_pods
def get_nodes():
v1 = kubernetes.client.CoreV1Api()
ret = v1.list_node(watch=False)
nodes = ret.items
new_nodes = []
for n in nodes:
cpu = normalize_cpu(n.status.allocatable['cpu'])
memory = normalize_memory( n.status.allocatable['memory'])
new_nodes.append({
"name": n.metadata.name,
"cpu": cpu,
"memory": memory,
})
return new_nodes
def main():
home_path = os.path.expanduser("~")
kube_config_path = os.path.join(home_path, ".kube/config")
config.load_kube_config(kube_config_path)
print("Node,Namespace,Name,CPU Request")
pods = get_pods()
nodes_total_cpu = {}
highest_request_pod = {"cpu_request": 0}
nodes = get_nodes()
nodes_cpu = {}
for n in nodes:
nodes_cpu[n["name"]] = n["cpu"]
for p in pods:
if p["node_name"] == "":
continue
print("%s,%s,%s,%s" % (p["node_name"], p["namespace"], p["name"], p["cpu_request"]))
if p["node_name"] in nodes_total_cpu:
nodes_total_cpu[p["node_name"]] += p["cpu_request"]
else:
nodes_total_cpu[p["node_name"]] = p["cpu_request"]
if p["cpu_request"] > highest_request_pod["cpu_request"]:
highest_request_pod = p
for node, total_cpu in nodes_total_cpu.items():
print("Node %s has a total CPU request of %s mCPU, free mCPU: %s" % (node, total_cpu, nodes_cpu[node] - total_cpu))
print("The highest requested pod is %s with %s mCPU" % (highest_request_pod["name"], highest_request_pod["cpu_request"]))
def normalize_cpu(cpu):
if cpu.endswith('m'):
return int(cpu.rstrip('m'))
else:
return int(float(cpu) * 1000)
def normalize_memory(memory):
if memory.endswith('Ki'):
return int(int(memory.rstrip('Ki')) / 1024)
elif memory.endswith('Mi'):
return int(memory.rstrip('Mi'))
elif memory.endswith('Gi'):
return int(int(memory.rstrip('Gi')) * 1024)
else:
return int(memory)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment