UI rework: inventory tree, compact cards, live Hubble traffic

Frontend rewritten around three panes. Inventory tree on the left
(namespaces by kind, or nodes by namespace) with search and keyboard
navigation replaces the namespace checkbox list. The map shows only the
selected namespace(s) or node: fixed-size cards inside namespace boxes,
laid out in two elk passes so a big namespace packs into rows instead of
one tall column; zoom is capped so the view no longer jumps. Details
panel has Overview / Links / YAML / Logs tabs. Light and dark themes.
Libraries are vendored, no CDN.

Backend: /api/flows reads recent flows from hubble-relay (TLS verified
with the hubble CA, no client cert needed) and aggregates them per
source/destination/port. Pods are resolved to workloads with the same
rules as the graph, since Hubble leaves Workloads empty on some flows.
Pods under non-native controllers (kruise DaemonSet, CNPG clusters,
bare Jobs, static pods) are now graph nodes too. Probes move to
/healthz: /api/graph was timing out the 1s probe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Vitaliy Chefanov
2026-09-23 19:50:53 +03:00
co-authored by Claude Opus 5.5
parent 2ac0ddb6ba
commit cf84e9976f
11 changed files with 8711 additions and 395 deletions
+69 -233
View File
@@ -2,244 +2,80 @@
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>cluster-map</title>
<script src="https://unpkg.com/cytoscape@3.30.2/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/dagre@0.8.5/dist/dagre.min.js"></script>
<script src="https://unpkg.com/cytoscape-dagre@2.5.0/cytoscape-dagre.js"></script>
<style>
:root { color-scheme: dark; }
html, body { margin: 0; height: 100%; background: #0f1115; color: #e6e6e6; font: 13px/1.4 -apple-system, Segoe UI, sans-serif; }
#app { display: flex; height: 100%; }
#sidebar { width: 260px; flex: none; padding: 12px; border-right: 1px solid #262a33; overflow-y: auto; }
#graph { flex: 1; position: relative; }
#cy { position: absolute; inset: 0; }
#details { width: 420px; flex: none; padding: 12px; border-left: 1px solid #262a33; overflow-y: auto; display: none; }
#details.open { display: block; }
h1 { font-size: 15px; margin: 0 0 12px; }
h2 { font-size: 13px; margin: 0 0 6px; color: #8fb8ff; }
label { display: block; margin: 4px 0; cursor: pointer; }
input[type=checkbox] { margin-right: 6px; }
input[type=text] { width: 100%; box-sizing: border-box; padding: 6px; background: #1a1d24; border: 1px solid #333; color: #eee; border-radius: 4px; margin-bottom: 8px; }
pre { white-space: pre-wrap; word-break: break-word; font-size: 11px; background: #14161b; padding: 8px; border-radius: 4px; }
.fact { margin: 2px 0; }
.fact b { color: #9aa4b2; }
.legend-swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 6px; vertical-align: middle; }
#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; }
</style>
<link rel="stylesheet" href="app.css">
<script src="vendor/cytoscape.min.js"></script>
<script src="vendor/elk.bundled.js"></script>
</head>
<body>
<div id="app">
<div id="sidebar">
<h1>cluster-map</h1>
<button id="reload">Обновить граф</button>
<h2>Namespaces</h2>
<label><input type="checkbox" id="show-system"> показать системные (d8-*, kube-*)</label>
<input type="text" id="ns-filter" placeholder="фильтр по имени namespace...">
<div id="ns-list"></div>
<h2 style="margin-top:16px">Легенда</h2>
<div class="fact"><span class="legend-swatch" style="background:#4c8bf5"></span>deployment</div>
<div class="fact"><span class="legend-swatch" style="background:#7a5cf0"></span>statefulset</div>
<div class="fact"><span class="legend-swatch" style="background:#c0567a"></span>daemonset</div>
<div class="fact"><span class="legend-swatch" style="background:#9a9a9a"></span>cronjob</div>
<div class="fact"><span class="legend-swatch" style="background:#37b37e"></span>service</div>
<div class="fact"><span class="legend-swatch" style="background:#e0a800"></span>ingress</div>
<div class="fact"><span class="legend-swatch" style="background:#2a2d36;border:1px solid #555"></span>node (физический)</div>
<header class="topbar">
<div class="brand">cluster-map</div>
<nav class="crumbs" id="crumbs" aria-label="Текущий вид"></nav>
<div class="topbar-actions">
<label class="toggle"><input type="checkbox" id="traffic-on" checked> Трафик</label>
<select id="traffic-window" aria-label="Окно трафика">
<option value="300">5 мин</option>
<option value="900">15 мин</option>
<option value="3600">1 час</option>
</select>
<label class="toggle" title="Проверки kubelet, cilium health, трафик между нодами"><input type="checkbox" id="infra-traffic"> Служебный</label>
<button type="button" id="reload" class="btn">Обновить</button>
<span class="muted small" id="updated"></span>
</div>
<div id="graph">
<div id="cy"></div>
<div id="status">загрузка...</div>
</div>
<div id="details">
<button id="close-details">закрыть</button>
<h2 id="details-title"></h2>
<div id="details-facts"></div>
<div id="details-logs-section" style="display:none">
<h2>Логи</h2>
<select id="pod-select"></select>
<select id="container-select"></select>
<button id="load-logs">Обновить логи</button>
<pre id="details-logs"></pre>
</header>
<div class="layout">
<aside class="sidebar" aria-label="Инвентарь">
<div class="seg" role="tablist" aria-label="Группировка">
<button type="button" role="tab" id="view-ns" aria-selected="true" aria-controls="tree">Namespaces</button>
<button type="button" role="tab" id="view-nodes" aria-selected="false" aria-controls="tree">Ноды</button>
</div>
<h2>Манифест</h2>
<pre id="details-yaml">загрузка...</pre>
</div>
<input type="search" id="tree-filter" placeholder="Поиск: имя, namespace, образ…" aria-label="Поиск по инвентарю">
<ul class="tree" id="tree" role="tree" aria-label="Объекты кластера"></ul>
<p class="hint">Клик — открыть на карте. Ctrl+клик по namespace — добавить к текущему виду.</p>
</aside>
<main class="stage">
<div id="cy" aria-label="Карта"></div>
<div class="stage-status" id="stage-status" role="status" aria-live="polite"></div>
<div class="zoom" role="group" aria-label="Масштаб">
<button type="button" class="btn icon" id="zoom-in" aria-label="Приблизить">+</button>
<button type="button" class="btn icon" id="zoom-out" aria-label="Отдалить">−</button>
<button type="button" class="btn icon" id="zoom-fit" aria-label="Показать всё">⤢</button>
</div>
<div class="legend" id="legend"></div>
</main>
<aside class="details" id="details" aria-label="Детали объекта" hidden>
<div class="details-head">
<div class="details-title">
<span class="kind-chip" id="d-kind"></span>
<h2 id="d-name"></h2>
<div class="muted small" id="d-sub"></div>
</div>
<button type="button" class="btn icon" id="d-close" aria-label="Закрыть панель">×</button>
</div>
<div class="tabs" role="tablist" aria-label="Разделы">
<button type="button" role="tab" data-tab="overview" aria-selected="true">Обзор</button>
<button type="button" role="tab" data-tab="links" aria-selected="false">Связи</button>
<button type="button" role="tab" data-tab="yaml" aria-selected="false">YAML</button>
<button type="button" role="tab" data-tab="logs" aria-selected="false">Логи</button>
</div>
<section class="tab-panel" data-panel="overview" role="tabpanel"></section>
<section class="tab-panel" data-panel="links" role="tabpanel" hidden></section>
<section class="tab-panel" data-panel="yaml" role="tabpanel" hidden><pre class="code" id="d-yaml"></pre></section>
<section class="tab-panel" data-panel="logs" role="tabpanel" hidden>
<div class="logs-bar">
<select id="pod-select" aria-label="Под"></select>
<select id="container-select" aria-label="Контейнер"></select>
<button type="button" class="btn" id="logs-reload">Обновить</button>
</div>
<pre class="code" id="d-logs"></pre>
</section>
</aside>
</div>
<script>
const KIND_COLOR = {
deployment: '#4c8bf5', statefulset: '#7a5cf0', daemonset: '#c0567a', cronjob: '#9a9a9a',
service: '#37b37e', ingress: '#e0a800', node: '#2a2d36',
};
const KIND_SHAPE = {
deployment: 'round-rectangle', statefulset: 'round-rectangle', daemonset: 'round-rectangle', cronjob: 'round-rectangle',
service: 'ellipse', ingress: 'diamond', node: 'hexagon',
};
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 = 'загрузка...';
const resp = await fetch('/api/graph');
fullGraph = await resp.json();
document.getElementById('status').textContent = `${fullGraph.nodes.length} узлов, ${fullGraph.edges.length} рёбер`;
buildNsList();
render();
}
function buildNsList() {
const el = document.getElementById('ns-list');
const showSystem = document.getElementById('show-system').checked;
const filterText = document.getElementById('ns-filter').value.toLowerCase();
const namespaces = fullGraph.nodes.filter(n => n.kind === 'namespace');
el.innerHTML = '';
namespaces
.filter(n => (showSystem || n.facts.system !== 'true') && n.label.toLowerCase().includes(filterText))
.sort((a, b) => a.label.localeCompare(b.label))
.forEach(n => {
const id = 'ns-cb-' + n.label;
const lbl = document.createElement('label');
lbl.innerHTML = `<input type="checkbox" class="ns-cb" data-ns="${n.label}" id="${id}" checked> ${n.label}`;
el.appendChild(lbl);
});
el.querySelectorAll('.ns-cb').forEach(cb => cb.addEventListener('change', render));
}
function selectedNamespaces() {
return new Set([...document.querySelectorAll('.ns-cb:checked')].map(cb => cb.dataset.ns));
}
function render() {
const selected = selectedNamespaces();
const visibleNodeIds = new Set();
const elements = [];
fullGraph.nodes.forEach(n => {
if (n.kind === 'namespace') {
if (!selected.has(n.label)) return;
} else if (n.kind === 'node') {
// physical nodes are always shown -- they're the "where" layer, not namespaced
} else {
if (n.namespace && !selected.has(n.namespace)) return;
}
visibleNodeIds.add(n.id);
elements.push({
group: 'nodes',
data: {
id: n.id, label: n.label, kind: n.kind, parent: n.kind === 'node' ? undefined : n.parent,
color: KIND_COLOR[n.kind] || '#666', shape: KIND_SHAPE[n.kind] || 'ellipse',
namespace: n.namespace, facts: n.facts,
},
});
});
fullGraph.edges.forEach(e => {
if (!visibleNodeIds.has(e.source) || !visibleNodeIds.has(e.target)) return;
elements.push({ group: 'edges', data: { id: e.id, source: e.source, target: e.target, kind: e.kind } });
});
if (cy) cy.destroy();
cy = cytoscape({
container: document.getElementById('cy'),
elements,
style: [
{ selector: 'node[kind = "namespace"]', style: {
'background-color': '#1a1d24', 'background-opacity': 0.5, 'border-color': '#333', 'border-width': 1,
label: 'data(label)', 'font-size': 11, color: '#8fb8ff', 'text-valign': 'top', 'text-halign': 'left',
'padding': '14px', shape: 'round-rectangle',
}},
{ selector: 'node[kind != "namespace"]', style: {
'background-color': 'data(color)', shape: 'data(shape)', label: 'data(label)',
'font-size': 10, color: '#fff', 'text-outline-width': 1, 'text-outline-color': '#0009',
width: 'label', height: 24, padding: '6px', 'text-valign': 'center',
}},
{ selector: 'edge[kind = "selects"]', style: { 'line-color': '#37b37e', width: 1.5, 'target-arrow-color': '#37b37e', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier' } },
{ selector: 'edge[kind = "routes"]', style: { 'line-color': '#e0a800', width: 1.5, 'target-arrow-color': '#e0a800', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier' } },
{ selector: 'edge[kind = "schedules-on"]', style: { 'line-color': '#3a3f4b', width: 1, 'line-style': 'dashed', 'curve-style': 'bezier', 'target-arrow-shape': 'none' } },
],
layout: { name: 'dagre', rankDir: 'LR', nodeSep: 20, rankSep: 60, animate: false },
});
cy.on('tap', 'node', evt => {
const n = evt.target.data();
if (n.kind === 'namespace') return;
showDetails(n);
});
}
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');
factsEl.innerHTML = Object.entries(n.facts || {}).map(([k, v]) => `<div class="fact"><b>${k}:</b> ${v || '—'}</div>`).join('');
const yamlEl = document.getElementById('details-yaml');
yamlEl.textContent = 'загрузка манифеста...';
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 = '<option>загрузка подов...</option>';
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 = '<option value="">нет живых подов</option>';
logsEl.textContent = 'нет подов для этого workload прямо сейчас.';
return;
}
podSelect.innerHTML = pods.map(p => `<option value="${p.name}">${p.name} (${p.phase})</option>`).join('');
const fillContainers = () => {
const p = pods.find(p => p.name === podSelect.value);
containerSelect.innerHTML = (p ? p.containers : []).map(c => `<option value="${c}">${c}</option>`).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(); });
document.getElementById('ns-filter').addEventListener('input', buildNsList);
loadGraph();
</script>
<script src="app.js"></script>
</body>
</html>