import json import logging from django.http import JsonResponse from django.views.generic import TemplateView, View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) # Globaler In-Memory Speicher CLUSTER_STATES = {} class DashboardView(TemplateView): template_name = "monitor/dashboard.html" @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) try: 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", []) ingresses = [] services = {} deployments = {} for res in resources: 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", {}) 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", []) ingresses.append({ "name": actual_name, "rules": rules }) elif res_type in ["kubernetes_service", "kubernetes_service_v1"]: services[actual_name] = {"name": actual_name, "type": "Service"} elif res_type in ["kubernetes_deployment", "kubernetes_deployment_v1"]: deployments[actual_name] = {"name": actual_name, "type": "Deployment"} # D3.js Baumhierarchie aufbauen root_node = { "name": f"Repository: {repo_name}", "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", []) 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") 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: svc_node["children"].append({"name": dep_name, "type": "Deployment", "children": []}) ing_node["children"].append(svc_node) root_node["children"].append(ing_node) CLUSTER_STATES[repo_name] = root_node return JsonResponse({"status": "success", "message": f"State für {repo_name} erfolgreich verarbeitet!"}) except Exception as e: logger.error(f"Push-Verarbeitung fehlgeschlagen: {str(e)}") 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") data = CLUSTER_STATES.get(repo_name, { "name": f"Warte auf Push für '{repo_name}'...", "type": "Root", "children": [] }) return JsonResponse(data)