From 22ea154c19e8f8c30478041f11b02a5e6da54216 Mon Sep 17 00:00:00 2001 From: Aleksandr Tcitlionok <803797+terghalin@users.noreply.github.com> Date: Fri, 6 Dec 2024 03:48:35 +0000 Subject: [PATCH] update(k8s): add time on duty --- app/main.py | 9 +++++++++ app/routes/k8s.py | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/app/main.py b/app/main.py index 2f6ddea..5b1dc43 100644 --- a/app/main.py +++ b/app/main.py @@ -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"} diff --git a/app/routes/k8s.py b/app/routes/k8s.py index 6c007d4..8f912f0 100644 --- a/app/routes/k8s.py +++ b/app/routes/k8s.py @@ -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.