mirror of
https://github.com/Rainyy21/k3s-health-dashboard.git
synced 2026-10-11 00:50:20 -04:00
finish the main code
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
from fastapi import APIRouter
|
||||
from k8s_client import get_custom_client
|
||||
|
||||
router = APIRouter(prefix="/metrics", tags=["metrics"])
|
||||
|
||||
|
||||
@router.get("/nodes")
|
||||
def node_metrics():
|
||||
api = get_custom_client()
|
||||
try:
|
||||
data = api.list_cluster_custom_object(
|
||||
group="metrics.k8s.io", version="v1beta1", plural="nodes"
|
||||
)
|
||||
return [
|
||||
{
|
||||
"name": item["metadata"]["name"],
|
||||
"cpu_usage": item["usage"]["cpu"], # e.g. "250m"
|
||||
"memory_usage": item["usage"]["memory"], # e.g. "512Mi"
|
||||
}
|
||||
for item in data["items"]
|
||||
]
|
||||
except Exception as e:
|
||||
return {"error": str(e), "hint": "Is metrics-server installed?"}
|
||||
@@ -0,0 +1,31 @@
|
||||
from fastapi import APIRouter
|
||||
from app.k8s_client import get_core_client
|
||||
|
||||
router = APIRouter(prefix="/nodes", tags=["nodes"])
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def list_node():
|
||||
v1 = get_core_client()
|
||||
nodes = v1.list_node().items
|
||||
result = []
|
||||
for n in nodes:
|
||||
conditions = {c.type: c.status for c in n.status.conditions}
|
||||
result.append(
|
||||
{
|
||||
"name": n.metadata.name,
|
||||
"ready": conditions.get("Ready") == "True",
|
||||
"cpu_capacity": n.status.capacity.get("cpu"),
|
||||
"memory_capacity": n.status.capacity.get("memory"),
|
||||
"labels": n.metadata.labels,
|
||||
"age_days": _age(n.metadata.creation_timestamp),
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _age(ts) -> int:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
return (now - ts).days
|
||||
@@ -0,0 +1,31 @@
|
||||
from fastapi import APIRouter, Query
|
||||
from k8s_client import get_core_client
|
||||
|
||||
router = APIRouter(prefix="/pods", tags=["pods"])
|
||||
|
||||
@router.get("/")
|
||||
def list_pods(namespace: str = Query("default")):
|
||||
v1 = get_core_client()
|
||||
pods = v1.list_namespaced_pod(namespace=namespace).items
|
||||
return [
|
||||
{
|
||||
"name": p.metadata.name,
|
||||
"namespace": p.metadata.namespace,
|
||||
"phase": p.status.phase, # Pending/Running/Succeeded/Failed
|
||||
"ready": _is_ready(p),
|
||||
"restarts": _restarts(p),
|
||||
"node": p.spec.node_name,
|
||||
}
|
||||
for p in pods
|
||||
]
|
||||
|
||||
|
||||
def _is_ready(pod) -> bool :
|
||||
if not pod.status.conditions:
|
||||
return False
|
||||
for any(c.type == "Ready" and c.status == "True" for c in pod.status.conditions)
|
||||
|
||||
def _restarts(pod) -> int:
|
||||
if not pod.status.container_statuses:
|
||||
return 0
|
||||
return sum(c.restart_count for c in pod.status.container_statuses)
|
||||
Reference in New Issue
Block a user