update(app): try k8s fetch

This commit is contained in:
Aleksandr Tcitlionok
2024-12-05 02:12:56 +00:00
parent 209bf98fb4
commit 4451037a37
3 changed files with 29 additions and 26 deletions

View File

@@ -1,2 +1,3 @@
# hk24-metalcheck # Metal Check
MetalCheck - Hackathon 2024
Metal Check - Get tips and information about your Kubernetes and on-premise servers.

View File

@@ -3,3 +3,4 @@ fastapi
uvicorn uvicorn
pyyaml pyyaml
rich rich
kubernetes

View File

@@ -1,32 +1,33 @@
from fastapi import APIRouter from fastapi import APIRouter
from pydantic import BaseModel from kubernetes import client, config
from typing import List
from database import insert_kubernetes_node, fetch_all
router = APIRouter() router = APIRouter()
class KubernetesNode(BaseModel): # Initialize Kubernetes client
cluster_name: str def init_k8s_client():
node_name: str try:
cpu: int config.load_incluster_config()
memory: str except:
storage: str config.load_kube_config() # local testing
type: str
namespaces: List[str]
@router.get("/k8s/data") @router.get("/k8s/data")
def get_k8s_data(): def get_k8s_data():
return {"kubernetes_nodes": fetch_all("kubernetes_nodes")} init_k8s_client()
v1 = client.CoreV1Api()
@router.post("/k8s/data") # Fetch nodes
def add_k8s_data(node: KubernetesNode): nodes = v1.list_node()
insert_kubernetes_node( node_data = []
cluster_name=node.cluster_name, for node in nodes.items:
node_name=node.node_name, node_data.append({
cpu=node.cpu, "node_name": node.metadata.name,
memory=node.memory, "cpu": node.status.capacity.get("cpu"),
storage=node.storage, "memory": node.status.capacity.get("memory"),
node_type=node.type, "pods_allocatable": node.status.allocatable.get("pods"),
namespaces=node.namespaces })
)
return {"message": f"Kubernetes node '{node.node_name}' in cluster '{node.cluster_name}' added successfully."} # Fetch namespaces
namespaces = v1.list_namespace()
namespace_data = [ns.metadata.name for ns in namespaces.items]
return {"nodes": node_data, "namespaces": namespace_data}