fix(export): show kib in mib

This commit is contained in:
Aleksandr Tcitlionok
2024-12-05 07:31:52 +00:00
parent 03a0c10c64
commit 235d23d5a7

View File

@@ -23,6 +23,10 @@ def convert_cpu_to_cores(cpu):
return float(cpu) # Already in cores return float(cpu) # Already in cores
def convert_memory_to_mib(memory): def convert_memory_to_mib(memory):
"""
Convert memory to MiB (mebibytes).
Handles units: Ki (kibibytes), Mi (mebibytes), Gi (gibibytes).
"""
if "Ki" in memory: if "Ki" in memory:
return int(memory.replace("Ki", "")) / 1024 return int(memory.replace("Ki", "")) / 1024
elif "Mi" in memory: elif "Mi" in memory:
@@ -41,7 +45,7 @@ def fetch_k8s_data_with_usage():
nodes = [{ nodes = [{
"node_name": node.metadata.name, "node_name": node.metadata.name,
"cpu": node.status.capacity.get("cpu"), "cpu": node.status.capacity.get("cpu"),
"memory": node.status.capacity.get("memory"), "memory": round(convert_memory_to_mib(node.status.capacity.get("memory")), 2), # Convert to MiB
"pods_allocatable": node.status.allocatable.get("pods"), "pods_allocatable": node.status.allocatable.get("pods"),
} for node in v1.list_node().items] } for node in v1.list_node().items]
@@ -81,6 +85,9 @@ def fetch_k8s_data_with_usage():
# Export endpoint # Export endpoint
@router.get("/export") @router.get("/export")
def export_data(format: str = "yaml"): def export_data(format: str = "yaml"):
"""
API endpoint to export data in YAML or JSON format.
"""
data = { data = {
"metal_nodes": fetch_all("metal_nodes"), "metal_nodes": fetch_all("metal_nodes"),
"virtual_machines": fetch_all("virtual_machines"), "virtual_machines": fetch_all("virtual_machines"),
@@ -93,4 +100,4 @@ def export_data(format: str = "yaml"):
yaml_data = yaml.safe_dump(data, sort_keys=False) yaml_data = yaml.safe_dump(data, sort_keys=False)
return Response(content=yaml_data, media_type="text/yaml") return Response(content=yaml_data, media_type="text/yaml")
return json.dumps(data, indent=2) return Response(content=json.dumps(data, indent=2), media_type="application/json")