update(k8s): add storage and instance type
This commit is contained in:
71
app/routes/think.py
Normal file
71
app/routes/think.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from kubernetes import client, config
|
||||
from typing import List, Dict
|
||||
import requests
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
def fetch_ai_summary(cluster_name: str, nodes: List[Dict], api_url: str, auth_token: str) -> str:
|
||||
"""
|
||||
Sends node data to an external AI API endpoint and retrieves a summary response.
|
||||
"""
|
||||
payload = {
|
||||
"data": {
|
||||
"cluster_name": cluster_name,
|
||||
"nodes": nodes
|
||||
}
|
||||
}
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {auth_token}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(api_url, json=payload, headers=headers)
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
if result.get("success"):
|
||||
return result.get("result", "No result provided by the API.")
|
||||
else:
|
||||
return "API responded with success=false."
|
||||
else:
|
||||
return f"API request failed with status code {response.status_code}: {response.text}"
|
||||
except requests.RequestException as e:
|
||||
return f"An error occurred while contacting the API: {str(e)}"
|
||||
|
||||
@router.get("/think/k8s")
|
||||
def think_k8s():
|
||||
"""
|
||||
Fetch Kubernetes data, send it to the AI API, and return the AI-generated summary.
|
||||
"""
|
||||
config.load_incluster_config()
|
||||
v1 = client.CoreV1Api()
|
||||
|
||||
cluster_name = "k8s-cluster"
|
||||
|
||||
# Format node data
|
||||
nodes = []
|
||||
for node in v1.list_node().items:
|
||||
node_data = {
|
||||
"name": node.metadata.name,
|
||||
"cpu": f"{node.status.capacity.get('cpu')} cores",
|
||||
"memory": f"{round(int(node.status.capacity.get('memory').replace('Ki', '')) / 1024 / 1024, 2)} GB",
|
||||
"storage": "N/A",
|
||||
"type": "N/A",
|
||||
"namespaces": [ns.metadata.name for ns in v1.list_namespace().items()]
|
||||
}
|
||||
nodes.append(node_data)
|
||||
|
||||
# Fetch token from environment
|
||||
api_url = os.getenv("AI_API_URL")
|
||||
auth_token = os.getenv("AI_API_TOKEN")
|
||||
|
||||
if not auth_token:
|
||||
raise HTTPException(status_code=500, detail="AI API token is not set. Please set the AI_API_TOKEN environment variable.")
|
||||
|
||||
# Call AI API
|
||||
summary = fetch_ai_summary(cluster_name, nodes, api_url, auth_token)
|
||||
|
||||
return {"summary": summary}
|
||||
Reference in New Issue
Block a user