update(k8s): add time on duty

This commit is contained in:
Aleksandr Tcitlionok
2024-12-06 03:48:35 +00:00
parent 1c130a9271
commit 22ea154c19
2 changed files with 30 additions and 0 deletions

View File

@@ -1,5 +1,6 @@
from fastapi import FastAPI
from database import init_db
from fastapi.middleware.cors import CORSMiddleware
from routes import metal, vm, k8s, export, think
app = FastAPI()
@@ -13,6 +14,14 @@ app.include_router(k8s.router)
app.include_router(export.router)
app.include_router(think.router)
#app.add_middleware(
# CORSMiddleware,
# allow_origins=["http://localhost:3000"],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
#)
@app.get("/")
def root():
return {"message": "Welcome to Metal Check API"}

View File

@@ -1,5 +1,6 @@
from fastapi import APIRouter
from kubernetes import client, config
from datetime import datetime, timezone
router = APIRouter()
@@ -15,6 +16,13 @@ def fetch_k8s_data_with_usage():
ephemeral_storage = node.status.capacity.get("ephemeral-storage", "0")
instance_type = node.metadata.labels.get("beta.kubernetes.io/instance-type", "N/A")
# Calculate time on duty
creation_timestamp = node.metadata.creation_timestamp
if creation_timestamp:
time_on_duty = calculate_time_on_duty(creation_timestamp)
else:
time_on_duty = "N/A"
nodes.append({
"node_name": node.metadata.name,
"cpu": node.status.capacity.get("cpu"),
@@ -22,6 +30,7 @@ def fetch_k8s_data_with_usage():
"storage": f"{round(convert_memory_to_gb(ephemeral_storage), 2)} GB",
"instance_type": instance_type,
"pods_allocatable": node.status.allocatable.get("pods"),
"time_on_duty": time_on_duty, # Add time on duty
})
# Fetch namespaces
@@ -57,6 +66,18 @@ def fetch_k8s_data_with_usage():
return {"nodes": nodes, "namespaces": namespaces, "namespace_usage": namespace_usage}
def calculate_time_on_duty(creation_timestamp):
"""
Calculate the time on duty in hours or days from the creation timestamp.
"""
now = datetime.now(timezone.utc)
delta = now - creation_timestamp
# If less than a day, return hours; otherwise, return days
if delta.days < 1:
return f"{delta.seconds // 3600} hours"
return f"{delta.days} days"
def convert_memory_to_gb(memory):
"""
Convert memory to GB (gigabytes) for ephemeral-storage.