update(k8s): add storage and instance type

This commit is contained in:
Aleksandr Tcitlionok
2024-12-05 08:05:15 +00:00
parent 55dd06584c
commit 0ec23d8122
4 changed files with 99 additions and 32 deletions

View File

@@ -9,12 +9,20 @@ def fetch_k8s_data_with_usage():
metrics_client = client.CustomObjectsApi()
# Fetch nodes
nodes = [{
"node_name": node.metadata.name,
"cpu": node.status.capacity.get("cpu"),
"memory": round(convert_memory_to_mib(node.status.capacity.get("memory")), 2), # Convert to MiB
"pods_allocatable": node.status.allocatable.get("pods"),
} for node in v1.list_node().items]
nodes = []
for node in v1.list_node().items:
# Extract storage and instance type from labels or annotations
storage = node.metadata.annotations.get("node.kubernetes.io/storage", "N/A")
instance_type = node.metadata.labels.get("beta.kubernetes.io/instance-type", "N/A")
nodes.append({
"node_name": node.metadata.name,
"cpu": node.status.capacity.get("cpu"),
"memory": round(convert_memory_to_mib(node.status.capacity.get("memory")), 2), # Convert to MiB
"storage": storage,
"instance_type": instance_type,
"pods_allocatable": node.status.allocatable.get("pods"),
})
# Fetch namespaces
namespaces = [ns.metadata.name for ns in v1.list_namespace().items]
@@ -50,24 +58,15 @@ def fetch_k8s_data_with_usage():
def convert_cpu_to_cores(cpu):
"""
Convert CPU usage to cores for human-readable format.
Handles units: n (nano), u (micro), m (milli), or none (cores).
Returns float values for cores, rounded appropriately.
"""
if "n" in cpu: # Nanocores to cores
if "n" in cpu:
return round(int(cpu.replace("n", "")) / 1e9, 4)
elif "u" in cpu: # Microcores to cores
elif "u" in cpu:
return round(int(cpu.replace("u", "")) / 1e6, 4)
elif "m" in cpu: # Millicores to cores
elif "m" in cpu:
return round(int(cpu.replace("m", "")) / 1000, 4)
return float(cpu) # Already in cores
return float(cpu)
def convert_memory_to_mib(memory):
"""
Convert memory to MiB (mebibytes).
Handles units: Ki (kibibytes), Mi (mebibytes), Gi (gibibytes).
"""
if "Ki" in memory:
return int(memory.replace("Ki", "")) / 1024
elif "Mi" in memory:
@@ -78,8 +77,4 @@ def convert_memory_to_mib(memory):
@router.get("/k8s/data")
def get_k8s_data():
"""
API endpoint to fetch Kubernetes data including nodes, namespaces,
and namespace resource usage.
"""
return fetch_k8s_data_with_usage()