From 2ac0ddb6ba59d0663dc2e3610bd5c5b1039ffaf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D1=82=D0=B0=D0=BB=D0=B8=D0=B9=20=D0=A7=D0=B5?= =?UTF-8?q?=D1=84=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Wed, 23 Sep 2026 18:56:50 +0300 Subject: [PATCH] Add pod logs by click: /api/pods + /api/logs endpoints Deployment/StatefulSet/DaemonSet/CronJob details now show a pod + container picker with the pod's recent log tail (500 lines, no follow), sitting alongside the existing raw-manifest view. Pod resolution reuses buildGraph's ownerReferences-walking logic (ownerWorkloadID) so it stays consistent with the schedules-on edges already shown on the graph. Co-Authored-By: Claude Sonnet 5 --- main.go | 84 +++++++++++++++++++++++++++++++++++++++++++++++ static/index.html | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) diff --git a/main.go b/main.go index 5613939..ce4db1c 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ package main import ( "context" "encoding/json" + "io" "log" "net/http" "os" @@ -65,6 +66,8 @@ func main() { mux := http.NewServeMux() mux.HandleFunc("/api/graph", handleGraph) mux.HandleFunc("/api/resource", handleResource) + mux.HandleFunc("/api/pods", handlePods) + mux.HandleFunc("/api/logs", handleLogs) mux.Handle("/", http.FileServer(http.Dir("./static"))) addr := ":8080" @@ -445,4 +448,85 @@ func handleResource(w http.ResponseWriter, r *http.Request) { w.Write(out) } +// podsForWorkload finds the live pods currently owned by a given workload, +// reusing the same ownerReferences-walking logic buildGraph uses for the +// schedules-on edges -- so "which pods back this node" stays consistent +// with what the graph already shows for placement. +func podsForWorkload(ctx context.Context, ns, kind, name string) ([]corev1.Pod, error) { + target := workloadID(ns, kind, name) + pods, err := clientset.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + var out []corev1.Pod + for _, p := range pods.Items { + if ownerWorkloadID(p) == target { + out = append(out, p) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +type PodInfo struct { + Name string `json:"name"` + NodeName string `json:"nodeName"` + Phase string `json:"phase"` + Containers []string `json:"containers"` +} + +// handlePods lists the pods backing a workload node, with their containers -- +// the frontend uses this to build the pod/container pickers before fetching +// logs, since a Deployment/StatefulSet/DaemonSet/CronJob isn't itself a log +// source, its pods are. +func handlePods(w http.ResponseWriter, r *http.Request) { + kind := r.URL.Query().Get("kind") + ns := r.URL.Query().Get("namespace") + name := r.URL.Query().Get("name") + if kind == "" || ns == "" || name == "" { + http.Error(w, "kind, namespace and name are required", http.StatusBadRequest) + return + } + pods, err := podsForWorkload(r.Context(), ns, kind, name) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + out := make([]PodInfo, 0, len(pods)) + for _, p := range pods { + var containers []string + for _, c := range p.Spec.Containers { + containers = append(containers, c.Name) + } + out = append(out, PodInfo{Name: p.Name, NodeName: p.Spec.NodeName, Phase: string(p.Status.Phase), Containers: containers}) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(out) +} + +// handleLogs streams a single container's recent log tail. Read-only, +// no follow -- this is a click-to-inspect tool, not a live tail viewer. +func handleLogs(w http.ResponseWriter, r *http.Request) { + ns := r.URL.Query().Get("namespace") + pod := r.URL.Query().Get("pod") + container := r.URL.Query().Get("container") + if ns == "" || pod == "" { + http.Error(w, "namespace and pod are required", http.StatusBadRequest) + return + } + var tail int64 = 500 + opts := &corev1.PodLogOptions{TailLines: &tail} + if container != "" { + opts.Container = container + } + stream, err := clientset.CoreV1().Pods(ns).GetLogs(pod, opts).Stream(r.Context()) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer stream.Close() + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + io.Copy(w, stream) +} + var _ = os.Stdout // keep the os import if logging grows; avoids an unused-import edit later diff --git a/static/index.html b/static/index.html index d58cd8b..14cef68 100644 --- a/static/index.html +++ b/static/index.html @@ -27,6 +27,8 @@ #status { position: absolute; top: 8px; left: 8px; font-size: 11px; color: #666; } button { background: #1a1d24; color: #eee; border: 1px solid #333; border-radius: 4px; padding: 4px 8px; cursor: pointer; margin-bottom: 8px; } button:hover { background: #23262e; } + select { background: #1a1d24; color: #eee; border: 1px solid #333; border-radius: 4px; padding: 4px; margin: 0 6px 8px 0; max-width: 100%; } + #details-logs { max-height: 320px; overflow-y: auto; background: #0b0c0f; } @@ -55,6 +57,14 @@

+ +

Манифест

загрузка...
@@ -70,6 +80,8 @@ const KIND_SHAPE = { let fullGraph = { nodes: [], edges: [] }; let cy; +let currentNode = null; +const WORKLOAD_KINDS = new Set(['deployment', 'statefulset', 'daemonset', 'cronjob']); async function loadGraph() { document.getElementById('status').textContent = 'загрузка...'; @@ -161,6 +173,7 @@ function render() { } async function showDetails(n) { + currentNode = n; document.getElementById('details').classList.add('open'); document.getElementById('details-title').textContent = `${n.kind}: ${n.label}`; const factsEl = document.getElementById('details-facts'); @@ -170,8 +183,57 @@ async function showDetails(n) { const params = new URLSearchParams({ kind: n.kind, namespace: n.namespace || '', name: n.label }); const resp = await fetch('/api/resource?' + params); yamlEl.textContent = resp.ok ? await resp.text() : 'не удалось получить манифест: ' + resp.status; + + const logsSection = document.getElementById('details-logs-section'); + if (!WORKLOAD_KINDS.has(n.kind)) { + logsSection.style.display = 'none'; + return; + } + logsSection.style.display = 'block'; + await loadPodPickers(n, params); } +async function loadPodPickers(n, params) { + const podSelect = document.getElementById('pod-select'); + const containerSelect = document.getElementById('container-select'); + const logsEl = document.getElementById('details-logs'); + podSelect.innerHTML = ''; + containerSelect.innerHTML = ''; + logsEl.textContent = ''; + + const resp = await fetch('/api/pods?' + params); + const pods = resp.ok ? await resp.json() : []; + if (currentNode !== n) return; // user clicked a different node while this was in flight + + if (!pods.length) { + podSelect.innerHTML = ''; + logsEl.textContent = 'нет подов для этого workload прямо сейчас.'; + return; + } + podSelect.innerHTML = pods.map(p => ``).join(''); + + const fillContainers = () => { + const p = pods.find(p => p.name === podSelect.value); + containerSelect.innerHTML = (p ? p.containers : []).map(c => ``).join(''); + }; + podSelect.onchange = () => { fillContainers(); fetchLogs(); }; + containerSelect.onchange = fetchLogs; + fillContainers(); + await fetchLogs(); +} + +async function fetchLogs() { + const pod = document.getElementById('pod-select').value; + const container = document.getElementById('container-select').value; + const logsEl = document.getElementById('details-logs'); + if (!pod) return; + logsEl.textContent = 'загрузка логов...'; + const params = new URLSearchParams({ namespace: currentNode.namespace || '', pod, container: container || '' }); + const resp = await fetch('/api/logs?' + params); + logsEl.textContent = resp.ok ? (await resp.text() || '(логи пустые)') : 'не удалось получить логи: ' + resp.status; +} + +document.getElementById('load-logs').addEventListener('click', fetchLogs); document.getElementById('reload').addEventListener('click', loadGraph); document.getElementById('close-details').addEventListener('click', () => document.getElementById('details').classList.remove('open')); document.getElementById('show-system').addEventListener('change', () => { buildNsList(); render(); });