Files
metalcheck/app/routes/export.py
2024-12-05 06:46:54 +00:00

35 lines
1.0 KiB
Python

from fastapi import APIRouter, Response
from database import fetch_all
import yaml
import json
from kubernetes import client, config
router = APIRouter()
def fetch_k8s_data():
config.load_incluster_config()
v1 = client.CoreV1Api()
nodes = [{
"node_name": node.metadata.name,
"cpu": node.status.capacity.get("cpu"),
"memory": node.status.capacity.get("memory"),
"pods_allocatable": node.status.allocatable.get("pods"),
} for node in v1.list_node().items]
namespaces = [ns.metadata.name for ns in v1.list_namespace().items]
return {"nodes": nodes, "namespaces": namespaces}
@router.get("/export")
def export_data(format: str = "yaml"):
data = {
"metal_nodes": fetch_all("metal_nodes"),
"virtual_machines": fetch_all("virtual_machines"),
"kubernetes": fetch_k8s_data(),
}
if format.lower() == "yaml":
yaml_data = yaml.safe_dump(data, sort_keys=False)
return Response(content=yaml_data, media_type="text/yaml")
return json.dumps(data, indent=2)