cloudmon/monitor/views.py

112 lines
5 KiB
Python
Raw Normal View History

2026-11-01 16:35:19 +00:00
import json
import logging
2026-11-01 12:39:17 +00:00
from django.http import JsonResponse
from django.views.generic import TemplateView, View
2026-11-01 16:35:19 +00:00
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
logger = logging.getLogger(__name__)
# Globaler In-Memory Speicher
2026-11-01 16:35:19 +00:00
CLUSTER_STATES = {}
2026-11-01 12:39:17 +00:00
class DashboardView(TemplateView):
template_name = "monitor/dashboard.html"
2026-11-01 16:35:19 +00:00
@method_decorator(csrf_exempt, name='dispatch')
class StatePushReceiverView(View):
def post(self, request, *args, **kwargs):
token = request.headers.get("Authorization")
if token != "Bearer boday-cloudmon-super-token-2026":
return JsonResponse({"error": "Unauthorized"}, status=401)
2026-11-01 12:39:17 +00:00
try:
2026-11-01 16:35:19 +00:00
tf_data = json.loads(request.body.decode('utf-8'))
repo_name = request.GET.get("repo", "boday_tf")
# KOMBI-PARSER: Erkennt automatisch, ob ein Plan-JSON oder ein State-JSON gepusht wurde
resources = []
if "values" in tf_data and "root_module" in tf_data["values"]:
# Format aus 'terraform show -json' (Plan)
resources = tf_data["values"]["root_module"].get("resources", [])
elif "resources" in tf_data:
# Format aus dem rohen '.tfstate' (State)
resources = tf_data.get("resources", [])
2026-11-01 12:39:17 +00:00
ingresses = []
services = {}
deployments = {}
for res in resources:
2026-11-01 12:39:17 +00:00
res_type = res.get("type")
res_name = res.get("name")
# Attribut-Extraktion je nach JSON-Typ flexibel auflösen
instances = res.get("instances", [])
if isinstance(instances, list) and len(instances) > 0:
attributes = instances[0].get("attributes", {})
else:
attributes = res.get("values", {})
2026-11-01 12:39:17 +00:00
if not attributes:
continue
# JSON-Struktur-Normalisierung für Kubernetes-Metadaten
metadata = attributes.get("metadata", [{}])
actual_name = metadata[0].get("name", res_name) if isinstance(metadata, list) else metadata.get("name", res_name)
if res_type == "kubernetes_ingress_v1" or res_type == "kubernetes_ingress":
spec = attributes.get("spec", [{}])
rules = spec[0].get("rule", []) if isinstance(spec, list) else spec.get("rule", [])
2026-11-01 12:39:17 +00:00
ingresses.append({
"name": actual_name,
"rules": rules
2026-11-01 12:39:17 +00:00
})
2026-11-01 16:35:19 +00:00
elif res_type in ["kubernetes_service", "kubernetes_service_v1"]:
services[actual_name] = {"name": actual_name, "type": "Service"}
2026-11-01 16:35:19 +00:00
elif res_type in ["kubernetes_deployment", "kubernetes_deployment_v1"]:
deployments[actual_name] = {"name": actual_name, "type": "Deployment"}
2026-11-01 12:39:17 +00:00
# D3.js Baumhierarchie aufbauen
2026-11-01 12:39:17 +00:00
root_node = {
"name": f"Repository: {repo_name}",
2026-11-01 12:39:17 +00:00
"type": "Root",
"children": []
}
for ing in ingresses:
ing_node = {"name": ing["name"], "type": "Ingress", "children": []}
for rule in ing["rules"]:
http = rule.get("http", [{}])
paths = http[0].get("path", []) if isinstance(http, list) else http.get("path", [])
2026-11-01 16:35:19 +00:00
for path in paths:
backend = path.get("backend", [{}])
service_block = backend[0].get("service", {}) if isinstance(backend, list) else backend.get("service", {})
backend_svc = service_block.get("name")
2026-11-01 12:39:17 +00:00
if backend_svc in services:
svc_node = {"name": backend_svc, "type": "Service", "children": []}
for dep_name in deployments.keys():
if dep_name in backend_svc or backend_svc in dep_name:
2026-11-01 16:35:19 +00:00
svc_node["children"].append({"name": dep_name, "type": "Deployment", "children": []})
2026-11-01 12:39:17 +00:00
ing_node["children"].append(svc_node)
root_node["children"].append(ing_node)
2026-11-01 16:35:19 +00:00
CLUSTER_STATES[repo_name] = root_node
return JsonResponse({"status": "success", "message": f"State für {repo_name} erfolgreich verarbeitet!"})
2026-11-01 12:39:17 +00:00
except Exception as e:
logger.error(f"Push-Verarbeitung fehlgeschlagen: {str(e)}")
2026-11-01 16:35:19 +00:00
return JsonResponse({"error": str(e)}, status=400)
class ClusterGraphDataView(View):
def get(self, request, *args, **kwargs):
# Holt das spezifische Repo aus dem Query-Parameter, Fallback auf boday_tf
repo_name = request.GET.get("repo", "bast/boday_tf")
2026-11-01 16:35:19 +00:00
data = CLUSTER_STATES.get(repo_name, {
"name": f"Warte auf Push für '{repo_name}'...",
2026-11-01 16:35:19 +00:00
"type": "Root",
"children": []
})
return JsonResponse(data)