The ring buffer on each agent holds 4095 flows, ~10 s at the observed ~380 flows/s, so the 5/15/60 min windows were really showing the last few seconds. A background follow stream now fills per-minute buckets for the last hour, and counts are distinct connections (5-tuples) instead of Hubble events, with opened (SYN) and dropped broken out. /api/flows reports coveredSec so the UI can say how much of the window the collector has seen since start. /api/graph reads informer caches instead of listing every kind per request (~0.9 s before). Pod-to-workload resolution for flows uses the same cache. YAML view drops managedFields. Frontend: traffic refreshes in place every 30 s without relayout; dash animation rationed (12 fps, only highlighted edges in dense views, paused after a minute idle) since each step redraws the whole element layer, ~15 ms on a 200-element view. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1170 lines
53 KiB
JavaScript
1170 lines
53 KiB
JavaScript
'use strict';
|
||
/* cluster-map frontend: inventory tree (left), scoped topology map (centre),
|
||
details with tabs (right). Plain JS, no build step. */
|
||
|
||
|
||
const KIND = {
|
||
namespace: { title: 'Namespace', color: '#7c8595' },
|
||
deployment: { title: 'Deployment', color: '#3b82f6' },
|
||
statefulset: { title: 'StatefulSet', color: '#8b5cf6' },
|
||
daemonset: { title: 'DaemonSet', color: '#d9467a' },
|
||
cronjob: { title: 'CronJob', color: '#8a93a3' },
|
||
service: { title: 'Service', color: '#14a37f' },
|
||
ingress: { title: 'Ingress', color: '#d99a06' },
|
||
node: { title: 'Node', color: '#64748b' },
|
||
pod: { title: 'Контроллер', color: '#0ea5e9' },
|
||
external: { title: 'Внешний', color: '#94a3b8' },
|
||
};
|
||
const WORKLOAD = new Set(['deployment', 'statefulset', 'daemonset', 'cronjob']);
|
||
const KIND_ORDER = ['ingress', 'service', 'deployment', 'statefulset', 'daemonset', 'cronjob', 'pod'];
|
||
const FOLDER_TITLE = { pod: 'Другие контроллеры' };
|
||
const hasPods = (n) => WORKLOAD.has(n.kind) || n.facts?.foreign === 'true';
|
||
const controllerKind = (n) => (n.facts?.controller || '').startsWith('static') ? 'static pod' : (n.facts?.controller || '').split(' ').pop();
|
||
const HEALTH_TEXT = { ok: 'в норме', warn: 'готов частично', error: 'не готов', idle: 'выключен' };
|
||
const HEALTH_RANK = { error: 3, warn: 2, ok: 1, idle: 0 };
|
||
const ICON = {
|
||
deployment: '<rect x="3" y="6" width="11" height="11" rx="2"/><path d="M6 3h9a2 2 0 0 1 2 2v9"/>',
|
||
statefulset: '<ellipse cx="10" cy="5" rx="6" ry="2.5"/><path d="M4 5v10c0 1.4 2.7 2.5 6 2.5s6-1.1 6-2.5V5"/><path d="M4 10c0 1.4 2.7 2.5 6 2.5s6-1.1 6-2.5"/>',
|
||
daemonset: '<rect x="3" y="3" width="5" height="5" rx="1"/><rect x="12" y="3" width="5" height="5" rx="1"/><rect x="3" y="12" width="5" height="5" rx="1"/><rect x="12" y="12" width="5" height="5" rx="1"/>',
|
||
cronjob: '<circle cx="10" cy="10" r="7"/><path d="M10 6v4l3 2"/>',
|
||
service: '<circle cx="10" cy="10" r="2.5"/><circle cx="4" cy="4" r="1.8"/><circle cx="16" cy="4" r="1.8"/><circle cx="4" cy="16" r="1.8"/><circle cx="16" cy="16" r="1.8"/><path d="M5.3 5.3l2.9 2.9M14.7 5.3l-2.9 2.9M5.3 14.7l2.9-2.9M14.7 14.7l-2.9-2.9"/>',
|
||
ingress: '<path d="M2 10h10M9 6l4 4-4 4"/><path d="M13 3h3a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1h-3"/>',
|
||
node: '<rect x="3" y="3" width="14" height="6" rx="1.5"/><rect x="3" y="11" width="14" height="6" rx="1.5"/><path d="M6 6h.01M6 14h.01"/>',
|
||
pod: '<path d="M10 2.5L16.5 6v8L10 17.5 3.5 14V6z"/>',
|
||
external: '<circle cx="10" cy="10" r="7"/><path d="M3 10h14M10 3c2 2 3 4.5 3 7s-1 5-3 7c-2-2-3-4.5-3-7s1-5 3-7z"/>',
|
||
namespace: '<rect x="2.5" y="4" width="15" height="12" rx="2" stroke-dasharray="2 2"/>',
|
||
};
|
||
const FONT = 'system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
|
||
const CARD = { w: 196, h: 48 };
|
||
const PILL = { w: 164, h: 36 };
|
||
const NSCARD = { w: 232, h: 56 };
|
||
const QUIET_AT = 30; // above this many traffic edges they stay faint until hovered
|
||
const INFRA_PREFIXES = ['ext/host/', 'ext/health', 'ext/remote-node'];
|
||
|
||
const $ = (sel) => document.querySelector(sel);
|
||
const el = (tag, props = {}, ...children) => {
|
||
const e = document.createElement(tag);
|
||
for (const [k, v] of Object.entries(props)) {
|
||
if (k === 'class') e.className = v;
|
||
else if (k === 'html') e.innerHTML = v;
|
||
else if (k.startsWith('on')) e.addEventListener(k.slice(2), v);
|
||
else if (v !== undefined && v !== null && v !== false) e.setAttribute(k, v === true ? '' : v);
|
||
}
|
||
for (const c of children.flat()) if (c !== null && c !== undefined) e.append(c);
|
||
return e;
|
||
};
|
||
const plural = (n, one, few, many) => {
|
||
const m10 = n % 10, m100 = n % 100;
|
||
const w = m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many;
|
||
return `${n} ${w}`;
|
||
};
|
||
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
const iconSvg = (kind, size = 14) =>
|
||
`<svg class="icon" viewBox="0 0 20 20" width="${size}" height="${size}" fill="none" stroke="${(KIND[kind] || KIND.external).color}" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICON[kind] || ''}</svg>`;
|
||
|
||
/* ---------- theme ---------- */
|
||
let T = {};
|
||
function readTheme() {
|
||
const probe = el('span', { style: 'display:none' });
|
||
document.body.append(probe);
|
||
const tok = (name) => { probe.style.color = `var(--${name})`; return getComputedStyle(probe).color; };
|
||
T = {
|
||
bg: tok('bg'), panel: tok('panel'), panel2: tok('panel-2'), line: tok('line'), text: tok('text'), muted: tok('muted'),
|
||
accent: tok('accent'), ok: tok('ok'), warn: tok('warn'), error: tok('error'), idle: tok('idle'),
|
||
};
|
||
probe.remove();
|
||
}
|
||
|
||
/* ---------- card images ---------- */
|
||
const measure = document.createElement('canvas').getContext('2d');
|
||
function fitText(text, font, max) {
|
||
measure.font = font;
|
||
if (measure.measureText(text).width <= max) return text;
|
||
let lo = 0, hi = text.length;
|
||
while (lo < hi) {
|
||
const mid = (lo + hi + 1) >> 1;
|
||
if (measure.measureText(text.slice(0, mid) + '…').width <= max) lo = mid; else hi = mid - 1;
|
||
}
|
||
return text.slice(0, lo) + '…';
|
||
}
|
||
const imgCache = new Map();
|
||
function cardImage({ kind, title, sub, health, ghost, w, h }) {
|
||
const key = [kind, title, sub, health, ghost, w, h].join('|');
|
||
if (imgCache.has(key)) return imgCache.get(key);
|
||
const c = (KIND[kind] || KIND.external).color;
|
||
const name = fitText(title, `600 12.5px ${FONT}`, w - 58);
|
||
const line2 = sub ? fitText(sub, `11px ${FONT}`, w - 50) : '';
|
||
const nameY = sub ? h / 2 - 3 : h / 2 + 4.5;
|
||
const dot = health ? `<circle cx="${w - 12}" cy="12" r="4" fill="${T[health]}"/>` : '';
|
||
// Drawn at 2x so cards stay crisp up to the max zoom.
|
||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w * 2}" height="${h * 2}" viewBox="0 0 ${w} ${h}">
|
||
<defs><clipPath id="r"><rect x="0.5" y="0.5" width="${w - 1}" height="${h - 1}" rx="8"/></clipPath></defs>
|
||
<rect x="0.5" y="0.5" width="${w - 1}" height="${h - 1}" rx="8" fill="${ghost ? T.panel2 : T.panel}" stroke="${ghost ? T.muted : T.line}"${ghost ? ' stroke-dasharray="4 3"' : ''}/>
|
||
<rect x="0" y="0" width="4" height="${h}" fill="${c}" clip-path="url(#r)"/>
|
||
<g transform="translate(13 ${h / 2 - 10})" fill="none" stroke="${c}" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">${ICON[kind] || ''}</g>
|
||
<text x="41" y="${nameY}" font-family="${FONT}" font-size="12.5" font-weight="600" fill="${ghost ? T.muted : T.text}">${esc(name)}</text>
|
||
${sub ? `<text x="41" y="${h / 2 + 12}" font-family="${FONT}" font-size="11" fill="${T.muted}">${esc(line2)}</text>` : ''}
|
||
${dot}</svg>`;
|
||
const url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
|
||
imgCache.set(key, url);
|
||
return url;
|
||
}
|
||
|
||
/* ---------- data ---------- */
|
||
const G = {
|
||
raw: null, byId: new Map(), byNs: new Map(), nsNodes: [], hostNodes: [],
|
||
cfgEdges: [], placement: new Map(), onNode: new Map(), loadedAt: null,
|
||
};
|
||
|
||
function indexGraph(raw) {
|
||
G.raw = raw;
|
||
G.byId = new Map(raw.nodes.map((n) => [n.id, n]));
|
||
G.byNs = new Map();
|
||
G.nsNodes = [];
|
||
G.hostNodes = [];
|
||
for (const n of raw.nodes) {
|
||
if (n.kind === 'namespace') { G.nsNodes.push(n); if (!G.byNs.has(n.label)) G.byNs.set(n.label, []); }
|
||
else if (n.kind === 'node') G.hostNodes.push(n);
|
||
}
|
||
for (const n of raw.nodes) {
|
||
if (n.namespace && n.kind !== 'namespace') {
|
||
if (!G.byNs.has(n.namespace)) G.byNs.set(n.namespace, []);
|
||
G.byNs.get(n.namespace).push(n);
|
||
}
|
||
}
|
||
G.cfgEdges = [];
|
||
G.placement = new Map();
|
||
G.onNode = new Map();
|
||
for (const e of raw.edges) {
|
||
if (e.kind === 'routes' && G.byId.has(e.target)) {
|
||
G.cfgEdges.push({ id: 'cfg:' + e.id, source: e.source, target: e.target, kind: 'routes' });
|
||
} else if (e.kind === 'selects') {
|
||
// stored as workload->service; drawn in request direction service->workload
|
||
G.cfgEdges.push({ id: 'cfg:' + e.id, source: e.target, target: e.source, kind: 'selects' });
|
||
} else if (e.kind === 'schedules-on') {
|
||
const host = e.target.slice('node/'.length);
|
||
if (!G.placement.has(e.source)) G.placement.set(e.source, new Set());
|
||
G.placement.get(e.source).add(host);
|
||
if (!G.onNode.has(host)) G.onNode.set(host, new Set());
|
||
G.onNode.get(host).add(e.source);
|
||
}
|
||
}
|
||
G.nsNodes.sort((a, b) => a.label.localeCompare(b.label));
|
||
G.hostNodes.sort((a, b) => a.label.localeCompare(b.label));
|
||
}
|
||
|
||
const isSystemNs = (ns) => G.byId.get('ns/' + ns)?.facts?.system === 'true';
|
||
function nsHealth(ns) {
|
||
let worst = 'ok', any = false;
|
||
for (const n of G.byNs.get(ns) || []) {
|
||
const h = n.facts?.health;
|
||
if (!h || !hasPods(n)) continue;
|
||
any = true;
|
||
if (HEALTH_RANK[h] > HEALTH_RANK[worst]) worst = h;
|
||
}
|
||
return any ? worst : 'idle';
|
||
}
|
||
function subline(n) {
|
||
const f = n.facts || {};
|
||
if (f.foreign === 'true') return `${f.ready}/${f.pods} готово · ${controllerKind(n)}`;
|
||
switch (n.kind) {
|
||
case 'deployment': case 'statefulset': return `${f.readyReplicas ?? '?'}/${f.replicas ?? '?'} готово`;
|
||
case 'daemonset': return `${f.ready ?? '?'}/${f.desired ?? '?'} на нодах`;
|
||
case 'cronjob': return f.suspended === 'true' ? `${f.schedule} · пауза` : f.schedule;
|
||
case 'service': return [f.type, f.ports].filter(Boolean).join(' · ');
|
||
case 'ingress': return f.hosts || f.class || '';
|
||
case 'node': return f.ready === 'True' ? 'Ready' : 'NotReady';
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/* ---------- state ---------- */
|
||
const state = {
|
||
scope: { mode: 'cluster' }, // {mode:'ns', ns:[...]} | {mode:'node', node}
|
||
selected: null,
|
||
treeView: 'ns',
|
||
expanded: new Set(['t:grp:user']),
|
||
filter: '',
|
||
traffic: true,
|
||
trafficWindow: 300,
|
||
infra: false,
|
||
flows: null,
|
||
flowsError: null,
|
||
};
|
||
|
||
let lastHash = '';
|
||
function readHash() {
|
||
const p = new URLSearchParams(location.hash.slice(1));
|
||
if (p.get('ns')) state.scope = { mode: 'ns', ns: p.get('ns').split(',').filter(Boolean) };
|
||
else if (p.get('node')) state.scope = { mode: 'node', node: p.get('node') };
|
||
state.selected = p.get('sel') || null;
|
||
if (p.get('view') === 'nodes') state.treeView = 'nodes';
|
||
}
|
||
function writeHash() {
|
||
const p = new URLSearchParams();
|
||
if (state.scope.mode === 'ns') p.set('ns', state.scope.ns.join(','));
|
||
if (state.scope.mode === 'node') p.set('node', state.scope.node);
|
||
if (state.selected) p.set('sel', state.selected);
|
||
if (state.treeView === 'nodes') p.set('view', 'nodes');
|
||
const h = p.toString();
|
||
history.replaceState(null, '', h ? '#' + h : location.pathname);
|
||
lastHash = location.hash;
|
||
}
|
||
|
||
/* ---------- inventory tree ---------- */
|
||
function objectItem(n) {
|
||
return { id: 't:obj:' + n.id, label: n.label, icon: n.kind, health: n.facts?.health, match: [n.label, n.facts?.image, n.facts?.hosts].join(' '), activate: () => selectObject(n.id) };
|
||
}
|
||
function nsKindFolders(ns, objs) {
|
||
const folders = [];
|
||
for (const kind of KIND_ORDER) {
|
||
const list = objs.filter((n) => n.kind === kind).sort((a, b) => a.label.localeCompare(b.label));
|
||
if (!list.length) continue;
|
||
folders.push({ id: `t:kind:${ns}:${kind}`, label: FOLDER_TITLE[kind] || KIND[kind].title, icon: kind, count: list.length, children: list.map(objectItem), activate: (add) => scopeNs(ns, add) });
|
||
}
|
||
return folders;
|
||
}
|
||
function buildTreeModel() {
|
||
if (state.treeView === 'nodes') {
|
||
return G.hostNodes.map((h) => {
|
||
const wls = [...(G.onNode.get(h.label) || [])].map((id) => G.byId.get(id)).filter(Boolean);
|
||
const byNs = new Map();
|
||
for (const w of wls) { if (!byNs.has(w.namespace)) byNs.set(w.namespace, []); byNs.get(w.namespace).push(w); }
|
||
const nsItems = [...byNs.keys()].sort().map((ns) => ({
|
||
id: `t:nodens:${h.label}:${ns}`, label: ns, icon: 'namespace', count: byNs.get(ns).length,
|
||
children: byNs.get(ns).sort((a, b) => a.label.localeCompare(b.label)).map(objectItem),
|
||
activate: () => scopeNode(h.label),
|
||
}));
|
||
return { id: 't:node:' + h.label, label: h.label, icon: 'node', health: h.facts?.health, count: wls.length, children: nsItems, activate: () => scopeNode(h.label) };
|
||
});
|
||
}
|
||
const nsItem = (n) => {
|
||
const objs = G.byNs.get(n.label) || [];
|
||
return { id: 't:ns:' + n.label, label: n.label, icon: 'namespace', health: nsHealth(n.label), count: objs.length, children: nsKindFolders(n.label, objs), activate: (add) => scopeNs(n.label, add), nsName: n.label };
|
||
};
|
||
const user = G.nsNodes.filter((n) => n.facts?.system !== 'true').map(nsItem);
|
||
const sys = G.nsNodes.filter((n) => n.facts?.system === 'true').map(nsItem);
|
||
return [{
|
||
id: 't:cluster', label: 'Кластер', icon: 'node', activate: scopeCluster, forceOpen: true,
|
||
children: [
|
||
{ id: 't:grp:user', label: 'Приложения', icon: 'namespace', count: user.length, children: user, activate: scopeCluster },
|
||
{ id: 't:grp:sys', label: 'Системные (d8-*, kube-*)', icon: 'namespace', count: sys.length, children: sys, activate: scopeCluster },
|
||
],
|
||
}];
|
||
}
|
||
function filterModel(items, q) {
|
||
if (!q) return items;
|
||
const out = [];
|
||
for (const it of items) {
|
||
const kids = it.children ? filterModel(it.children, q) : [];
|
||
const hit = (it.match || it.label).toLowerCase().includes(q);
|
||
if (hit || kids.length) out.push({ ...it, children: hit && !kids.length ? it.children : kids, forceOpen: kids.length > 0, hit });
|
||
}
|
||
return out;
|
||
}
|
||
function highlight(label, q) {
|
||
const frag = document.createDocumentFragment();
|
||
const i = q ? label.toLowerCase().indexOf(q) : -1;
|
||
if (i < 0) { frag.append(label); return frag; }
|
||
frag.append(label.slice(0, i), el('mark', {}, label.slice(i, i + q.length)), label.slice(i + q.length));
|
||
return frag;
|
||
}
|
||
|
||
let treeIndex = new Map();
|
||
function renderTree() {
|
||
const root = $('#tree');
|
||
const q = state.filter.trim().toLowerCase();
|
||
const model = filterModel(buildTreeModel(), q);
|
||
treeIndex = new Map();
|
||
const selectedTreeId = currentTreeSelection();
|
||
const render = (items, level) => items.map((it) => {
|
||
treeIndex.set(it.id, it);
|
||
const hasKids = it.children && it.children.length > 0;
|
||
const open = it.forceOpen || state.expanded.has(it.id);
|
||
const inScope = state.scope.mode === 'ns' && it.nsName && state.scope.ns.includes(it.nsName);
|
||
const li = el('li', {
|
||
role: 'treeitem', 'data-id': it.id, 'aria-level': level, tabindex: '-1',
|
||
'aria-expanded': hasKids ? String(open) : null,
|
||
'aria-selected': it.id === selectedTreeId ? 'true' : 'false',
|
||
class: inScope ? 'in-scope' : null,
|
||
});
|
||
const row = el('div', { class: 'row' },
|
||
el('span', { class: 'twisty', 'aria-hidden': 'true' }),
|
||
it.health ? el('span', { class: 'dot ' + it.health, title: HEALTH_TEXT[it.health] }) : null,
|
||
el('span', { html: iconSvg(it.icon) }).firstChild,
|
||
el('span', { class: 'label' }, highlight(it.label, q)),
|
||
it.count !== undefined ? el('span', { class: 'count' }, String(it.count)) : null,
|
||
);
|
||
li.append(row);
|
||
if (hasKids && open) li.append(el('ul', { role: 'group' }, render(it.children, level + 1)));
|
||
return li;
|
||
});
|
||
root.replaceChildren(...render(model, 1));
|
||
const focusable = root.querySelector('[aria-selected="true"]') || root.querySelector('[role="treeitem"]');
|
||
if (focusable) focusable.tabIndex = 0;
|
||
}
|
||
function currentTreeSelection() {
|
||
if (state.selected && G.byId.has(state.selected)) return 't:obj:' + state.selected;
|
||
if (state.scope.mode === 'ns' && state.scope.ns.length === 1) return 't:ns:' + state.scope.ns[0];
|
||
if (state.scope.mode === 'node') return 't:node:' + state.scope.node;
|
||
return 't:cluster';
|
||
}
|
||
function revealInTree(id) {
|
||
const n = G.byId.get(id);
|
||
if (!n) return;
|
||
if (state.treeView === 'ns') {
|
||
state.expanded.add('t:cluster');
|
||
state.expanded.add(isSystemNs(n.namespace) ? 't:grp:sys' : 't:grp:user');
|
||
state.expanded.add('t:ns:' + n.namespace);
|
||
state.expanded.add(`t:kind:${n.namespace}:${n.kind}`);
|
||
} else {
|
||
for (const host of G.placement.get(id) || []) {
|
||
state.expanded.add('t:node:' + host);
|
||
state.expanded.add(`t:nodens:${host}:${n.namespace}`);
|
||
}
|
||
}
|
||
}
|
||
function treeToggle(li, open) {
|
||
const id = li.dataset.id;
|
||
if (open) state.expanded.add(id); else state.expanded.delete(id);
|
||
renderTree();
|
||
$(`#tree [data-id="${CSS.escape(id)}"]`)?.focus();
|
||
}
|
||
function visibleTreeItems() { return [...$('#tree').querySelectorAll('[role="treeitem"]')]; }
|
||
function focusTreeItem(li) {
|
||
for (const x of $('#tree').querySelectorAll('[tabindex="0"]')) x.tabIndex = -1;
|
||
li.tabIndex = 0;
|
||
li.focus();
|
||
}
|
||
|
||
$('#tree').addEventListener('click', (e) => {
|
||
const li = e.target.closest('[role="treeitem"]');
|
||
if (!li) return;
|
||
const it = treeIndex.get(li.dataset.id);
|
||
if (e.target.closest('.twisty')) { if (li.hasAttribute('aria-expanded')) treeToggle(li, li.getAttribute('aria-expanded') !== 'true'); return; }
|
||
if (li.getAttribute('aria-expanded') === 'false') state.expanded.add(li.dataset.id);
|
||
it?.activate?.(e.ctrlKey || e.metaKey);
|
||
});
|
||
$('#tree').addEventListener('keydown', (e) => {
|
||
const li = e.target.closest('[role="treeitem"]');
|
||
if (!li) return;
|
||
const items = visibleTreeItems();
|
||
const i = items.indexOf(li);
|
||
const expanded = li.getAttribute('aria-expanded');
|
||
switch (e.key) {
|
||
case 'ArrowDown': if (items[i + 1]) focusTreeItem(items[i + 1]); break;
|
||
case 'ArrowUp': if (items[i - 1]) focusTreeItem(items[i - 1]); break;
|
||
case 'Home': focusTreeItem(items[0]); break;
|
||
case 'End': focusTreeItem(items[items.length - 1]); break;
|
||
case 'ArrowRight':
|
||
if (expanded === 'false') treeToggle(li, true);
|
||
else if (expanded === 'true') { const c = li.querySelector('[role="treeitem"]'); if (c) focusTreeItem(c); }
|
||
break;
|
||
case 'ArrowLeft':
|
||
if (expanded === 'true') treeToggle(li, false);
|
||
else { const p = li.parentElement.closest('[role="treeitem"]'); if (p) focusTreeItem(p); }
|
||
break;
|
||
case 'Enter': treeIndex.get(li.dataset.id)?.activate?.(e.ctrlKey || e.metaKey); break;
|
||
case ' ': e.preventDefault(); break;
|
||
default: return;
|
||
}
|
||
if (e.key !== ' ') e.preventDefault();
|
||
});
|
||
$('#tree').addEventListener('keyup', (e) => {
|
||
if (e.key !== ' ') return;
|
||
const li = e.target.closest('[role="treeitem"]');
|
||
if (li) treeIndex.get(li.dataset.id)?.activate?.(e.ctrlKey || e.metaKey);
|
||
});
|
||
let filterTimer;
|
||
$('#tree-filter').addEventListener('input', (e) => {
|
||
clearTimeout(filterTimer);
|
||
filterTimer = setTimeout(() => { state.filter = e.target.value; renderTree(); }, 120);
|
||
});
|
||
for (const [id, view] of [['#view-ns', 'ns'], ['#view-nodes', 'nodes']]) {
|
||
$(id).addEventListener('click', () => {
|
||
state.treeView = view;
|
||
$('#view-ns').setAttribute('aria-selected', String(view === 'ns'));
|
||
$('#view-nodes').setAttribute('aria-selected', String(view === 'nodes'));
|
||
if (state.selected) revealInTree(state.selected);
|
||
renderTree();
|
||
writeHash();
|
||
});
|
||
}
|
||
|
||
/* ---------- navigation ---------- */
|
||
function scopeCluster() {
|
||
state.scope = { mode: 'cluster' };
|
||
state.selected = null;
|
||
closeDetails();
|
||
renderMap();
|
||
}
|
||
function scopeNs(ns, add = false) {
|
||
if (add && state.scope.mode === 'ns') {
|
||
const set = new Set(state.scope.ns);
|
||
if (set.has(ns) && set.size > 1) set.delete(ns); else set.add(ns);
|
||
state.scope = { mode: 'ns', ns: [...set] };
|
||
} else {
|
||
state.scope = { mode: 'ns', ns: [ns] };
|
||
}
|
||
state.expanded.add('t:ns:' + ns);
|
||
if (state.selected && !scopeContains(state.selected)) { state.selected = null; closeDetails(); }
|
||
renderMap();
|
||
}
|
||
function scopeNode(host) {
|
||
state.scope = { mode: 'node', node: host };
|
||
state.expanded.add('t:node:' + host);
|
||
if (state.selected && !scopeContains(state.selected)) { state.selected = null; closeDetails(); }
|
||
renderMap();
|
||
}
|
||
function scopeContains(id) {
|
||
const n = G.byId.get(id);
|
||
if (!n) return false;
|
||
if (state.scope.mode === 'ns') return state.scope.ns.includes(n.namespace);
|
||
if (state.scope.mode === 'node') return G.placement.get(id)?.has(state.scope.node) ?? false;
|
||
return false;
|
||
}
|
||
function selectObject(id) {
|
||
const n = G.byId.get(id);
|
||
if (!n) return;
|
||
state.selected = id;
|
||
revealInTree(id);
|
||
if (!scopeContains(id)) {
|
||
state.scope = { mode: 'ns', ns: [n.namespace] };
|
||
renderMap().then(() => focusOnMap(id));
|
||
} else {
|
||
renderTree();
|
||
renderCrumbs();
|
||
focusOnMap(id);
|
||
}
|
||
openDetails(id);
|
||
writeHash();
|
||
}
|
||
|
||
/* ---------- map ---------- */
|
||
const cy = cytoscape({
|
||
container: $('#cy'),
|
||
minZoom: 0.15,
|
||
maxZoom: 2.2,
|
||
wheelSensitivity: 0.35,
|
||
boxSelectionEnabled: false,
|
||
selectionType: 'single',
|
||
});
|
||
|
||
function mapStyle() {
|
||
return [
|
||
{ selector: 'node', style: {
|
||
shape: 'round-rectangle', 'corner-radius': 8, width: 'data(w)', height: 'data(h)',
|
||
'background-opacity': 0, 'background-image': 'data(img)', 'background-width': 'data(w)', 'background-height': 'data(h)',
|
||
'background-clip': 'none', 'bounds-expansion': 2, 'border-width': 0, label: '',
|
||
} },
|
||
{ selector: ':parent', style: {
|
||
'background-image': 'none', 'background-color': T.panel2, 'background-opacity': 0.55,
|
||
'border-width': 1, 'border-color': T.line, 'corner-radius': 12, padding: '18px',
|
||
label: 'data(label)', 'text-valign': 'top', 'text-halign': 'center', 'text-margin-x': 'data(lmx)', 'text-margin-y': -6,
|
||
'font-size': 12, 'font-weight': 600, color: T.muted, 'font-family': FONT, 'min-zoomed-font-size': 5,
|
||
} },
|
||
{ selector: ':parent.ghost', style: { 'border-style': 'dashed', 'background-opacity': 0.2 } },
|
||
{ selector: ':parent.hostbox', style: { 'border-width': 1.5, 'border-color': KIND.node.color, 'background-opacity': 0.25, color: T.text } },
|
||
{ selector: ':parent.group', style: { 'background-opacity': 0, 'border-width': 0, 'font-size': 13, color: T.text } },
|
||
{ selector: 'node:childless:selected', style: { 'border-width': 2, 'border-color': T.accent, 'border-opacity': 1 } },
|
||
{ selector: 'edge', style: {
|
||
'curve-style': 'bezier', width: 1.3, 'line-color': T.muted, 'target-arrow-shape': 'triangle',
|
||
'target-arrow-color': T.muted, 'arrow-scale': 0.8, opacity: 0.55,
|
||
} },
|
||
{ selector: 'edge.traffic', style: {
|
||
'line-color': T.accent, 'target-arrow-color': T.accent, 'line-style': 'dashed', 'line-dash-pattern': [7, 5],
|
||
width: 'data(width)', opacity: 0.9,
|
||
} },
|
||
{ selector: 'edge.drop', style: { 'line-color': T.error, 'target-arrow-color': T.error } },
|
||
{ selector: 'edge.labelled, edge:selected', style: {
|
||
label: 'data(label)', 'font-size': 10, 'font-family': FONT, color: T.text, 'text-rotation': 'autorotate',
|
||
'text-background-color': T.panel, 'text-background-opacity': 0.92, 'text-background-padding': 2, 'text-background-shape': 'round-rectangle',
|
||
} },
|
||
{ selector: 'edge.traffic.quiet', style: { opacity: 0.18, width: 1.2 } },
|
||
{ selector: '.faded', style: { opacity: 0.12 } },
|
||
{ selector: 'edge.hl', style: { opacity: 1, 'z-index': 20 } },
|
||
{ selector: 'edge.traffic.quiet.hl', style: { opacity: 1, width: 'data(width)' } },
|
||
];
|
||
}
|
||
|
||
function cardNode(n, parent, ghost) {
|
||
const size = CARD;
|
||
return {
|
||
group: 'nodes', classes: ghost ? 'ghostcard' : '',
|
||
data: {
|
||
id: n.id, ref: n.id, parent, kind: n.kind, w: size.w, h: size.h,
|
||
img: cardImage({ kind: n.kind, title: n.label, sub: ghost ? n.namespace + ' · ' + KIND[n.kind].title : subline(n), health: ghost ? null : n.facts?.health, ghost, w: size.w, h: size.h }),
|
||
},
|
||
};
|
||
}
|
||
function externalNode(ep) {
|
||
const inNs = !!ep.namespace;
|
||
const kind = !inNs ? 'external' : KIND[ep.kind] ? ep.kind : 'pod';
|
||
const size = inNs ? CARD : PILL;
|
||
return {
|
||
group: 'nodes',
|
||
data: {
|
||
id: ep.id, ref: ep.id, kind, w: size.w, h: size.h, parent: inNs ? 'box:' + ep.namespace : undefined, external: ep,
|
||
img: cardImage({ kind, title: ep.label, sub: inNs ? `${ep.namespace} · ${ep.kind}` : null, ghost: inNs, w: size.w, h: size.h }),
|
||
},
|
||
};
|
||
}
|
||
const nsBox = (ns, ghost, parent) => ({ group: 'nodes', classes: ghost ? 'ghost' : '', data: { id: 'box:' + ns, label: ns, kind: 'nsbox', ns, w: 1, h: 1, img: 'none', lmx: 0, parent } });
|
||
|
||
function scopeNamespaces() {
|
||
if (state.scope.mode === 'ns') return state.scope.ns;
|
||
if (state.scope.mode === 'node') {
|
||
const set = new Set();
|
||
for (const id of G.onNode.get(state.scope.node) || []) { const n = G.byId.get(id); if (n) set.add(n.namespace); }
|
||
return [...set].sort();
|
||
}
|
||
return [];
|
||
}
|
||
|
||
function isInfraEdge(e) {
|
||
if (INFRA_PREFIXES.some((p) => e.source.startsWith(p) || e.target.startsWith(p))) return true;
|
||
return e.ports.every((p) => p === '53/UDP' || p === '53/TCP');
|
||
}
|
||
|
||
// Merge per-port flow edges into one edge per pair, for drawing.
|
||
function aggregateFlows(flows) {
|
||
const pairs = new Map();
|
||
for (const e of flows.edges) {
|
||
const key = e.source + '→' + e.target;
|
||
let p = pairs.get(key);
|
||
if (!p) { p = { source: e.source, target: e.target, count: 0, fresh: 0, dropped: 0, ports: [], last: '' }; pairs.set(key, p); }
|
||
p.count += e.connections;
|
||
p.fresh += e.new;
|
||
p.dropped += e.dropped;
|
||
if (!p.ports.includes(e.port)) p.ports.push(e.port);
|
||
if (e.last > p.last) p.last = e.last;
|
||
}
|
||
return [...pairs.values()];
|
||
}
|
||
|
||
function buildElements() {
|
||
const els = [];
|
||
const present = new Set();
|
||
const add = (x) => { if (!present.has(x.data.id)) { present.add(x.data.id); els.push(x); } };
|
||
|
||
if (state.scope.mode === 'cluster') return buildClusterElements();
|
||
|
||
let members;
|
||
if (state.scope.mode === 'ns') {
|
||
members = state.scope.ns.flatMap((ns) => G.byNs.get(ns) || []);
|
||
for (const ns of state.scope.ns) add(nsBox(ns, false));
|
||
} else {
|
||
const host = state.scope.node;
|
||
members = [...(G.onNode.get(host) || [])].map((id) => G.byId.get(id)).filter(Boolean);
|
||
add({ group: 'nodes', classes: 'hostbox', data: { id: 'host:' + host, label: 'нода ' + host, kind: 'hostbox', w: 1, h: 1, img: 'none', lmx: 0 } });
|
||
for (const ns of new Set(members.map((m) => m.namespace))) add(nsBox(ns, false, 'host:' + host));
|
||
}
|
||
const memberIds = new Set(members.map((m) => m.id));
|
||
for (const n of members) add(cardNode(n, 'box:' + n.namespace, false));
|
||
|
||
for (const e of G.cfgEdges) {
|
||
if (memberIds.has(e.source) && memberIds.has(e.target)) add({ group: 'edges', classes: 'cfg ' + e.kind, data: { ...e, label: e.kind === 'routes' ? 'route' : 'selector' } });
|
||
}
|
||
|
||
state.trafficEdges = [];
|
||
if (state.traffic && state.flows) {
|
||
for (const e of aggregateFlows(state.flows)) {
|
||
if (!state.infra && isInfraEdge(e)) continue;
|
||
const touches = memberIds.has(e.source) || memberIds.has(e.target);
|
||
if (!touches) continue;
|
||
for (const id of [e.source, e.target]) {
|
||
if (present.has(id)) continue;
|
||
const gn = G.byId.get(id);
|
||
if (gn) {
|
||
if (!present.has('box:' + gn.namespace)) add(nsBox(gn.namespace, true));
|
||
add(cardNode(gn, 'box:' + gn.namespace, true));
|
||
} else {
|
||
const ep = state.flows.endpoints.find((x) => x.id === id) || { id, label: id, kind: 'external' };
|
||
if (ep.namespace && !present.has('box:' + ep.namespace)) add(nsBox(ep.namespace, true));
|
||
add(externalNode(ep));
|
||
}
|
||
}
|
||
state.trafficEdges.push(e);
|
||
add(trafficEdgeElement(e));
|
||
}
|
||
}
|
||
return els;
|
||
}
|
||
|
||
function trafficEdgeElement(e) {
|
||
return {
|
||
group: 'edges', classes: 'traffic' + (e.dropped ? ' drop' : ''),
|
||
data: { id: 'tr:' + e.source + '→' + e.target, source: e.source, target: e.target, ...trafficEdgeData(e) },
|
||
};
|
||
}
|
||
function trafficEdgeData(e) {
|
||
return {
|
||
width: 1.6 + Math.min(4.5, Math.log10(e.count + 1) * 1.7),
|
||
label: `${e.ports.slice(0, 3).join(', ')}${e.ports.length > 3 ? '…' : ''} · ${e.count} соед.${e.dropped ? ` · drop ${e.dropped}` : ''}`,
|
||
flow: e,
|
||
};
|
||
}
|
||
|
||
// Refresh traffic on the drawn map without relayout: counts and widths are
|
||
// updated, edges between cards already on the map come and go. Peers that
|
||
// would need new cards are only counted, so the layout never jumps under
|
||
// the cursor; "Обновить" redraws with them.
|
||
let hiddenPeers = 0;
|
||
async function refreshTraffic() {
|
||
if (!state.traffic || state.scope.mode === 'cluster' || document.hidden) return;
|
||
const token = renderToken;
|
||
let flows;
|
||
try { flows = await fetchFlows(scopeNamespaces().slice(0, 100)); } catch { return; }
|
||
if (token !== renderToken) return;
|
||
state.flows = flows;
|
||
state.flowsError = null;
|
||
const members = new Set(cy.nodes(':childless').filter((n) => !n.hasClass('ghostcard') && !n.data('external')).map((n) => n.id()));
|
||
const next = new Map();
|
||
hiddenPeers = 0;
|
||
for (const e of aggregateFlows(flows)) {
|
||
if (!state.infra && isInfraEdge(e)) continue;
|
||
if (!members.has(e.source) && !members.has(e.target)) continue;
|
||
if (cy.getElementById(e.source).empty() || cy.getElementById(e.target).empty()) { hiddenPeers++; continue; }
|
||
next.set('tr:' + e.source + '→' + e.target, e);
|
||
}
|
||
cy.batch(() => {
|
||
cy.edges('.traffic').forEach((edge) => { if (!next.has(edge.id())) edge.remove(); });
|
||
for (const [id, e] of next) {
|
||
const edge = cy.getElementById(id);
|
||
if (edge.nonempty()) { edge.data(trafficEdgeData(e)); edge.toggleClass('drop', e.dropped > 0); }
|
||
else cy.add(trafficEdgeElement(e));
|
||
}
|
||
cy.edges('.traffic').toggleClass('quiet', next.size > QUIET_AT);
|
||
});
|
||
state.trafficEdges = [...next.values()];
|
||
if (detailsId) renderLinks(detailsId);
|
||
updateStatus(cy.elements().map((x) => ({ group: x.group(), data: x.data() })));
|
||
}
|
||
setInterval(refreshTraffic, 30000);
|
||
|
||
function buildClusterElements() {
|
||
const els = [];
|
||
const groups = [
|
||
['grp:user', 'Приложения', G.nsNodes.filter((n) => n.facts?.system !== 'true')],
|
||
['grp:sys', 'Системные', G.nsNodes.filter((n) => n.facts?.system === 'true')],
|
||
];
|
||
let y0 = 0;
|
||
const gapX = 18, gapY = 18;
|
||
const aspect = Math.max(0.6, cy.width() / Math.max(1, cy.height()));
|
||
for (const [gid, label, list] of groups) {
|
||
const cols = Math.max(2, Math.min(8, Math.round(Math.sqrt(list.length * aspect * (NSCARD.h + gapY) / (NSCARD.w + gapX)) * 1.4)));
|
||
els.push({ group: 'nodes', classes: 'group', data: { id: gid, label, kind: 'group', w: 1, h: 1, img: 'none', lmx: 0 } });
|
||
list.forEach((n, i) => {
|
||
const objs = G.byNs.get(n.label) || [];
|
||
const wl = objs.filter(hasPods).length;
|
||
const ing = objs.filter((o) => o.kind === 'ingress').length;
|
||
const svc = objs.filter((o) => o.kind === 'service').length;
|
||
const sub = `${wl} workload · ${svc} svc · ${ing} ingress`;
|
||
els.push({
|
||
group: 'nodes', position: { x: (i % cols) * (NSCARD.w + gapX), y: y0 + Math.floor(i / cols) * (NSCARD.h + gapY) },
|
||
data: { id: 'nscard:' + n.label, ns: n.label, parent: gid, kind: 'nscard', w: NSCARD.w, h: NSCARD.h,
|
||
img: cardImage({ kind: 'namespace', title: n.label, sub, health: nsHealth(n.label), ghost: false, w: NSCARD.w, h: NSCARD.h }) },
|
||
});
|
||
});
|
||
y0 += Math.ceil(list.length / cols) * (NSCARD.h + gapY) + 90;
|
||
}
|
||
return els;
|
||
}
|
||
|
||
/* Two-level layout: every compound (namespace / node box) is laid out on its
|
||
own and its unconnected groups packed in rows, then the boxes are placed
|
||
against each other using the edges lifted to box level. A single ELK pass
|
||
with INCLUDE_CHILDREN can't pack components inside a compound and stacks
|
||
a big namespace into one tall column. */
|
||
const elk = new ELK();
|
||
const PAD = 18; // cytoscape compound padding
|
||
const LABEL_H = 22; // room above a box for its label
|
||
async function runLayout() {
|
||
const aspect = Math.max(1, cy.width() / Math.max(1, cy.height()));
|
||
const edges = cy.edges();
|
||
const plan = await layoutLevel(null, edges, aspect);
|
||
cy.batch(() => place(plan, 0, 0));
|
||
}
|
||
async function layoutLevel(container, edges, aspect) {
|
||
const kids = container ? container.children() : cy.nodes().orphans();
|
||
const blocks = [];
|
||
for (const k of kids) {
|
||
if (k.isParent()) {
|
||
const inner = await layoutLevel(k, edges, 2.2);
|
||
blocks.push({ node: k, inner, w: inner.w + 2 * PAD, h: inner.h + 2 * PAD + LABEL_H });
|
||
} else {
|
||
blocks.push({ node: k, w: k.data('w'), h: k.data('h') });
|
||
}
|
||
}
|
||
const owner = new Map();
|
||
for (const b of blocks) {
|
||
owner.set(b.node.id(), b.node.id());
|
||
if (b.inner) b.node.descendants().forEach((d) => owner.set(d.id(), b.node.id()));
|
||
}
|
||
const lifted = new Map();
|
||
edges.forEach((e) => {
|
||
const s = owner.get(e.source().id()), t = owner.get(e.target().id());
|
||
if (s && t && s !== t) lifted.set(s + '>' + t, { id: 'l' + lifted.size, sources: [s], targets: [t] });
|
||
});
|
||
const graph = {
|
||
id: 'root',
|
||
layoutOptions: {
|
||
'elk.algorithm': 'layered',
|
||
'elk.direction': 'RIGHT',
|
||
'elk.separateConnectedComponents': 'true',
|
||
'elk.aspectRatio': String(aspect),
|
||
'elk.spacing.nodeNode': container ? '16' : '40',
|
||
'elk.spacing.componentComponent': container ? '22' : '48',
|
||
'elk.layered.spacing.nodeNodeBetweenLayers': container ? '64' : '90',
|
||
'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX',
|
||
'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
|
||
'elk.padding': '[top=0,left=0,bottom=0,right=0]',
|
||
},
|
||
children: blocks.map((b) => ({ id: b.node.id(), width: b.w, height: b.h })),
|
||
edges: [...lifted.values()],
|
||
};
|
||
const out = await elk.layout(graph);
|
||
const pos = new Map(out.children.map((c) => [c.id, c]));
|
||
for (const b of blocks) { const p = pos.get(b.node.id()); b.x = p.x; b.y = p.y; }
|
||
return { blocks, w: out.width, h: out.height };
|
||
}
|
||
function place(plan, ox, oy) {
|
||
for (const b of plan.blocks) {
|
||
const x = ox + b.x, y = oy + b.y;
|
||
if (b.inner) place(b.inner, x + PAD, y + LABEL_H + PAD);
|
||
else b.node.position({ x: x + b.w / 2, y: y + b.h / 2 });
|
||
}
|
||
}
|
||
|
||
// Compound bounds are only settled after cytoscape's next render, so the
|
||
// left-aligned group labels are placed a frame later (and after drags).
|
||
function placeCompoundLabels() {
|
||
requestAnimationFrame(() => {
|
||
measure.font = `600 12px ${FONT}`;
|
||
cy.batch(() => {
|
||
cy.nodes(':parent').forEach((p) => {
|
||
const lw = measure.measureText(p.data('label') || '').width;
|
||
p.data('lmx', -p.outerWidth() / 2 + lw / 2 + 6);
|
||
});
|
||
});
|
||
});
|
||
}
|
||
cy.on('dragfree', 'node', placeCompoundLabels);
|
||
|
||
function fitView() {
|
||
cy.resize();
|
||
cy.fit(undefined, 48);
|
||
if (cy.zoom() > 1.1) { cy.zoom(1.1); cy.center(); }
|
||
}
|
||
function focusOnMap(id) {
|
||
const n = cy.getElementById(id);
|
||
if (!n.nonempty()) return;
|
||
cy.$(':selected').unselect();
|
||
n.select();
|
||
const z = Math.max(cy.zoom(), 0.9);
|
||
cy.animate({ zoom: z, center: { eles: n } }, { duration: matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 250 });
|
||
}
|
||
|
||
let renderToken = 0;
|
||
async function renderMap() {
|
||
const token = ++renderToken;
|
||
renderTree();
|
||
renderCrumbs();
|
||
writeHash();
|
||
state.flows = null;
|
||
state.flowsError = null;
|
||
const namespaces = scopeNamespaces();
|
||
if (state.traffic && namespaces.length) {
|
||
setStatus('загрузка трафика…');
|
||
try {
|
||
state.flows = await fetchFlows(namespaces.slice(0, 100));
|
||
if (!state.flows.connected && !state.flows.edges?.length) state.flowsError = state.flows.error || 'нет связи с Hubble Relay';
|
||
} catch (err) {
|
||
state.flowsError = err.message;
|
||
}
|
||
if (token !== renderToken) return;
|
||
}
|
||
hiddenPeers = 0;
|
||
const els = buildElements();
|
||
cy.batch(() => { cy.elements().remove(); cy.add(els); });
|
||
const quiet = cy.edges('.traffic').length > QUIET_AT;
|
||
cy.edges('.traffic').toggleClass('quiet', quiet);
|
||
if (state.scope.mode !== 'cluster') await runLayout();
|
||
if (token !== renderToken) return;
|
||
placeCompoundLabels();
|
||
fitView();
|
||
if (state.selected && cy.getElementById(state.selected).nonempty()) cy.getElementById(state.selected).select();
|
||
renderLegend();
|
||
updateStatus(els);
|
||
}
|
||
|
||
function updateStatus(els) {
|
||
if (state.scope.mode === 'cluster') { setStatus(''); return; }
|
||
const cards = els.filter((x) => x.group === 'nodes' && x.data.kind !== 'nsbox' && x.data.kind !== 'hostbox').length;
|
||
if (!cards) { setStatus('здесь нет объектов'); return; }
|
||
if (!state.traffic) { setStatus(''); return; }
|
||
if (state.flowsError) { setStatus('трафик недоступен: ' + state.flowsError, true); return; }
|
||
if (state.flows) {
|
||
const total = state.trafficEdges.reduce((s, e) => s + e.count, 0);
|
||
const f = state.flows;
|
||
// The collector only knows what it has seen since the pod started.
|
||
const win = f.coveredSec < f.windowSec - 30
|
||
? `${fmtDuration(f.coveredSec)} (из ${fmtDuration(f.windowSec)}: сбор идёт с запуска)`
|
||
: fmtDuration(f.windowSec);
|
||
if (!f.connected) setStatus(`связь с Hubble потеряна (${f.error || 'нет ответа'}), данные могут устареть`, true);
|
||
const hint = state.trafficEdges.length > QUIET_AT ? ' — наведите на карточку, чтобы увидеть её трафик' : '';
|
||
if (!f.connected) return;
|
||
const more = hiddenPeers ? `; ещё ${plural(hiddenPeers, 'новое направление', 'новых направления', 'новых направлений')} — «Обновить»` : '';
|
||
setStatus(state.trafficEdges.length
|
||
? `трафик за ${win}: ${plural(state.trafficEdges.length, 'направление', 'направления', 'направлений')}, ${plural(total, 'соединение', 'соединения', 'соединений')}${hint}${more}`
|
||
: `трафика за ${win} не видно${more}`);
|
||
}
|
||
}
|
||
function fmtDuration(sec) {
|
||
if (sec < 90) return plural(Math.max(1, Math.round(sec)), 'секунду', 'секунды', 'секунд');
|
||
if (sec < 5400) return Math.round(sec / 60) + ' мин';
|
||
return plural(Math.round(sec / 3600), 'час', 'часа', 'часов');
|
||
}
|
||
function setStatus(text, isError = false) {
|
||
const s = $('#stage-status');
|
||
s.textContent = text;
|
||
s.classList.toggle('error', isError);
|
||
}
|
||
|
||
async function fetchFlows(namespaces) {
|
||
const p = new URLSearchParams({ namespaces: namespaces.join(','), window: state.trafficWindow });
|
||
const r = await fetch('/api/flows?' + p);
|
||
if (!r.ok) throw new Error((await r.text()).trim() || 'HTTP ' + r.status);
|
||
return r.json();
|
||
}
|
||
|
||
/* hover: highlight a card's neighbourhood, like NSX "logical path" */
|
||
cy.on('mouseover', 'node:childless', (e) => {
|
||
const n = e.target;
|
||
const hood = n.closedNeighborhood();
|
||
const keep = hood.union(hood.ancestors());
|
||
cy.batch(() => {
|
||
cy.elements().difference(keep).addClass('faded');
|
||
hood.edges().addClass('hl labelled');
|
||
});
|
||
});
|
||
cy.on('mouseout', 'node:childless', () => {
|
||
cy.batch(() => {
|
||
cy.elements().removeClass('faded hl labelled');
|
||
cy.$('node:selected').connectedEdges().addClass('hl');
|
||
});
|
||
});
|
||
cy.on('select', 'node', (e) => e.target.connectedEdges().addClass('hl'));
|
||
cy.on('unselect', 'node', (e) => e.target.connectedEdges().removeClass('hl'));
|
||
cy.on('mouseover', 'edge', (e) => e.target.addClass('labelled hl'));
|
||
cy.on('mouseout', 'edge', (e) => e.target.removeClass('labelled hl'));
|
||
|
||
cy.on('tap', 'node', (e) => {
|
||
const d = e.target.data();
|
||
if (d.kind === 'nscard') { scopeNs(d.ns); return; }
|
||
if (e.target.isParent()) {
|
||
if (d.kind === 'nsbox' && !(state.scope.mode === 'ns' && state.scope.ns.includes(d.ns))) scopeNs(d.ns);
|
||
return;
|
||
}
|
||
if (G.byId.has(d.ref)) {
|
||
if (!scopeContains(d.ref)) { selectObject(d.ref); return; }
|
||
state.selected = d.ref;
|
||
revealInTree(d.ref);
|
||
renderTree();
|
||
renderCrumbs();
|
||
writeHash();
|
||
openDetails(d.ref);
|
||
} else if (d.external) {
|
||
state.selected = null;
|
||
openExternalDetails(d.external);
|
||
}
|
||
});
|
||
cy.on('tap', (e) => {
|
||
if (e.target === cy) { cy.$(':selected').unselect(); }
|
||
});
|
||
|
||
$('#zoom-in').addEventListener('click', () => cy.zoom({ level: cy.zoom() * 1.25, renderedPosition: { x: cy.width() / 2, y: cy.height() / 2 } }));
|
||
$('#zoom-out').addEventListener('click', () => cy.zoom({ level: cy.zoom() / 1.25, renderedPosition: { x: cy.width() / 2, y: cy.height() / 2 } }));
|
||
$('#zoom-fit').addEventListener('click', fitView);
|
||
|
||
/* Animated dashes on traffic edges. Any edge style change makes cytoscape
|
||
redraw the whole element layer (~15 ms for a 200-element node view), so
|
||
the animation is rationed: 12 fps, only highlighted edges in dense views
|
||
(no highlight -> no redraw at all), and asleep after a minute without
|
||
input. */
|
||
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
|
||
let dash = 0;
|
||
let lastTick = 0;
|
||
let lastInput = performance.now();
|
||
for (const ev of ['pointermove', 'wheel', 'keydown', 'pointerdown']) addEventListener(ev, () => { lastInput = performance.now(); }, { passive: true });
|
||
function tick(t) {
|
||
requestAnimationFrame(tick);
|
||
if (document.hidden || reduceMotion.matches || t - lastTick < 80 || t - lastInput > 60000) return;
|
||
lastTick = t;
|
||
let edges = cy.edges('.traffic');
|
||
if (edges.length > QUIET_AT) edges = edges.filter('.hl');
|
||
if (!edges.length) return;
|
||
dash = (dash + 2) % 120;
|
||
edges.style('line-dash-offset', -dash);
|
||
}
|
||
requestAnimationFrame(tick);
|
||
|
||
/* ---------- crumbs & legend ---------- */
|
||
function renderCrumbs() {
|
||
const c = $('#crumbs');
|
||
const parts = [el('button', { type: 'button', onclick: scopeCluster }, 'Кластер')];
|
||
if (state.scope.mode === 'ns') {
|
||
parts.push(el('span', { class: 'sep', 'aria-hidden': 'true' }, '›'));
|
||
for (const ns of state.scope.ns) {
|
||
parts.push(el('span', { class: 'chip' }, ns,
|
||
state.scope.ns.length > 1 ? el('button', { type: 'button', 'aria-label': 'Убрать ' + ns, onclick: () => scopeNs(ns, true) }, '×') : null));
|
||
}
|
||
} else if (state.scope.mode === 'node') {
|
||
parts.push(el('span', { class: 'sep', 'aria-hidden': 'true' }, '›'), el('span', { class: 'chip' }, 'нода ' + state.scope.node));
|
||
}
|
||
const sel = state.selected && G.byId.get(state.selected);
|
||
if (sel) parts.push(el('span', { class: 'sep', 'aria-hidden': 'true' }, '›'), el('span', {}, `${KIND[sel.kind].title} ${sel.label}`));
|
||
c.replaceChildren(...parts);
|
||
}
|
||
function renderLegend() {
|
||
const l = $('#legend');
|
||
if (state.scope.mode === 'cluster') {
|
||
l.replaceChildren(
|
||
el('span', {}, 'Карточка — namespace, точка — худшее состояние его workload’ов:'),
|
||
...['ok', 'warn', 'error', 'idle'].map((h) => el('span', {}, el('span', { class: 'dot ' + h }), HEALTH_TEXT[h])),
|
||
);
|
||
return;
|
||
}
|
||
l.replaceChildren(
|
||
el('span', {}, el('span', { class: 'line config' }), 'по конфигурации (Ingress → Service → Pod)'),
|
||
el('span', {}, el('span', { class: 'line traffic' }), 'реальный трафик (Hubble)'),
|
||
el('span', {}, el('span', { class: 'line drop' }), 'есть drop'),
|
||
el('span', {}, 'пунктирная карточка — из другого namespace'),
|
||
);
|
||
}
|
||
|
||
/* ---------- details panel ---------- */
|
||
const yamlCache = new Map();
|
||
let detailsId = null;
|
||
function closeDetails() {
|
||
$('#details').hidden = true;
|
||
detailsId = null;
|
||
requestAnimationFrame(() => cy.resize());
|
||
}
|
||
$('#d-close').addEventListener('click', () => { state.selected = null; cy.$(':selected').unselect(); closeDetails(); renderTree(); renderCrumbs(); writeHash(); });
|
||
|
||
function setTab(name) {
|
||
for (const t of document.querySelectorAll('.tabs [role="tab"]')) t.setAttribute('aria-selected', String(t.dataset.tab === name));
|
||
for (const p of document.querySelectorAll('.tab-panel')) p.hidden = p.dataset.panel !== name;
|
||
const n = G.byId.get(detailsId);
|
||
if (name === 'yaml' && n) loadYaml(n);
|
||
if (name === 'logs' && n) loadPods(n);
|
||
}
|
||
for (const t of document.querySelectorAll('.tabs [role="tab"]')) t.addEventListener('click', () => setTab(t.dataset.tab));
|
||
|
||
function showPanelHead(kind, name, sub) {
|
||
const chip = $('#d-kind');
|
||
chip.textContent = KIND[kind]?.title || kind;
|
||
chip.style.background = (KIND[kind] || KIND.external).color;
|
||
$('#d-name').textContent = name;
|
||
$('#d-sub').textContent = sub;
|
||
const wasHidden = $('#details').hidden;
|
||
$('#details').hidden = false;
|
||
if (wasHidden) requestAnimationFrame(() => { cy.resize(); keepVisible(state.selected); });
|
||
}
|
||
function keepVisible(id) {
|
||
const n = id && cy.getElementById(id);
|
||
if (!n || !n.nonempty()) return;
|
||
const bb = n.renderedBoundingBox();
|
||
if (bb.x1 < 0 || bb.y1 < 0 || bb.x2 > cy.width() || bb.y2 > cy.height()) {
|
||
cy.animate({ center: { eles: n } }, { duration: matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 200 });
|
||
}
|
||
}
|
||
function tabVisible(name, visible) {
|
||
const t = document.querySelector(`.tabs [data-tab="${name}"]`);
|
||
t.hidden = !visible;
|
||
if (!visible && t.getAttribute('aria-selected') === 'true') setTab('overview');
|
||
}
|
||
|
||
const FACT_LABELS = {
|
||
replicas: 'Реплик', readyReplicas: 'Готово', desired: 'Нужно', ready: 'Готово', image: 'Образ', schedule: 'Расписание',
|
||
suspended: 'Пауза', active: 'Активных запусков', lastSuccess: 'Последний успех (UTC)', type: 'Тип', ports: 'Порты',
|
||
hosts: 'Хосты', class: 'IngressClass', os: 'ОС', kubelet: 'kubelet', controller: 'Контроллер', pods: 'Подов',
|
||
};
|
||
function openDetails(id) {
|
||
const n = G.byId.get(id);
|
||
if (!n) return;
|
||
detailsId = id;
|
||
showPanelHead(n.kind, n.label, n.namespace ? `namespace ${n.namespace}` : '');
|
||
const foreign = n.facts?.foreign === 'true';
|
||
tabVisible('yaml', !foreign);
|
||
tabVisible('logs', hasPods(n));
|
||
|
||
const panel = document.querySelector('[data-panel="overview"]');
|
||
const dl = el('dl', { class: 'facts' });
|
||
const h = n.facts?.health;
|
||
if (h) dl.append(el('dt', {}, 'Состояние'), el('dd', {}, el('span', { class: 'status' }, el('span', { class: 'dot ' + h }), HEALTH_TEXT[h])));
|
||
for (const [k, v] of Object.entries(n.facts || {})) {
|
||
if (k === 'health' || k === 'system' || k === 'foreign' || v === '') continue;
|
||
dl.append(el('dt', {}, FACT_LABELS[k] || k), el('dd', {}, v));
|
||
}
|
||
const parts = [dl];
|
||
const hosts = [...(G.placement.get(id) || [])].sort();
|
||
if (hosts.length) {
|
||
parts.push(el('div', { class: 'section-title' }, 'Работает на нодах'),
|
||
el('ul', { class: 'link-list' }, hosts.map((host) => el('li', {}, el('button', { type: 'button', onclick: () => scopeNode(host) },
|
||
el('span', { html: iconSvg('node') }).firstChild, host)))));
|
||
}
|
||
panel.replaceChildren(...parts);
|
||
renderLinks(id);
|
||
$('#d-yaml').textContent = '';
|
||
$('#d-logs').textContent = '';
|
||
const active = document.querySelector('.tabs [aria-selected="true"]')?.dataset.tab || 'overview';
|
||
setTab(document.querySelector(`.tabs [data-tab="${active}"]`).hidden ? 'overview' : active);
|
||
}
|
||
|
||
function openExternalDetails(ep) {
|
||
detailsId = ep.id;
|
||
showPanelHead(ep.namespace ? (KIND[ep.kind] ? ep.kind : 'pod') : 'external', ep.label, ep.namespace ? `namespace ${ep.namespace}` : 'за пределами кластера или служебный адрес');
|
||
tabVisible('yaml', false);
|
||
tabVisible('logs', false);
|
||
document.querySelector('[data-panel="overview"]').replaceChildren(
|
||
el('p', { class: 'muted' }, ep.namespace
|
||
? 'Этот workload есть в трафике, но его нет в графе: под без контроллера или уже удалён.'
|
||
: 'Адрес, с которым общались поды из текущего вида. Имя — из DNS, если Hubble его видел.'));
|
||
renderLinks(ep.id);
|
||
setTab('overview');
|
||
}
|
||
|
||
function linkButton(id, meta, dropped) {
|
||
const n = G.byId.get(id);
|
||
const ep = state.flows?.endpoints.find((x) => x.id === id);
|
||
const kind = n?.kind || (ep?.namespace ? (KIND[ep.kind] ? ep.kind : 'pod') : 'external');
|
||
const label = n ? `${n.label}` : ep?.label || id;
|
||
const ns = n?.namespace || ep?.namespace;
|
||
return el('li', {}, el('button', { type: 'button', onclick: () => (n ? selectObject(id) : null) },
|
||
el('span', { html: iconSvg(kind) }).firstChild,
|
||
el('span', {}, label, ns ? el('span', { class: 'muted' }, ' · ' + ns) : null),
|
||
el('span', { class: 'meta' + (dropped ? ' drop' : '') }, meta)));
|
||
}
|
||
function renderLinks(id) {
|
||
const panel = document.querySelector('[data-panel="links"]');
|
||
const incoming = [], outgoing = [];
|
||
for (const e of G.cfgEdges) {
|
||
const what = e.kind === 'routes' ? 'маршрут' : 'селектор';
|
||
if (e.target === id) incoming.push(linkButton(e.source, what));
|
||
if (e.source === id) outgoing.push(linkButton(e.target, what));
|
||
}
|
||
const tIn = [], tOut = [];
|
||
for (const e of state.trafficEdges || []) {
|
||
const meta = `${e.ports.join(', ')} · ${e.count} соед.${e.fresh ? `, новых ${e.fresh}` : ''}${e.dropped ? ` · drop ${e.dropped}` : ''}`;
|
||
if (e.target === id) tIn.push(linkButton(e.source, meta, e.dropped));
|
||
if (e.source === id) tOut.push(linkButton(e.target, meta, e.dropped));
|
||
}
|
||
const section = (title, items, empty) => [el('div', { class: 'section-title' }, title),
|
||
items.length ? el('ul', { class: 'link-list' }, items) : el('p', { class: 'muted small' }, empty)];
|
||
const trafficNote = !state.traffic ? 'трафик выключен' : state.flowsError ? 'трафик недоступен' : 'нет за выбранное окно';
|
||
panel.replaceChildren(
|
||
...section('Конфигурация: кто ссылается сюда', incoming, 'нет'),
|
||
...section('Конфигурация: куда ссылается', outgoing, 'нет'),
|
||
...section('Трафик: входящие соединения', tIn, trafficNote),
|
||
...section('Трафик: исходящие соединения', tOut, trafficNote),
|
||
);
|
||
}
|
||
|
||
async function loadYaml(n) {
|
||
const pre = $('#d-yaml');
|
||
if (yamlCache.has(n.id)) { pre.textContent = yamlCache.get(n.id); return; }
|
||
pre.textContent = 'загрузка…';
|
||
const p = new URLSearchParams({ kind: n.kind, namespace: n.namespace || '', name: n.label });
|
||
const r = await fetch('/api/resource?' + p);
|
||
const text = r.ok ? await r.text() : 'не удалось получить манифест: HTTP ' + r.status;
|
||
if (r.ok) yamlCache.set(n.id, text);
|
||
if (detailsId === n.id) pre.textContent = text;
|
||
}
|
||
|
||
let podsFor = null;
|
||
async function loadPods(n) {
|
||
if (podsFor === n.id) return;
|
||
podsFor = n.id;
|
||
const podSel = $('#pod-select'), cSel = $('#container-select'), out = $('#d-logs');
|
||
podSel.replaceChildren(el('option', {}, 'загрузка…'));
|
||
cSel.replaceChildren();
|
||
out.textContent = '';
|
||
const p = new URLSearchParams({ id: n.id, namespace: n.namespace });
|
||
const r = await fetch('/api/pods?' + p);
|
||
const pods = r.ok ? await r.json() : [];
|
||
if (detailsId !== n.id) return;
|
||
if (!pods.length) {
|
||
podSel.replaceChildren(el('option', { value: '' }, 'нет живых подов'));
|
||
out.textContent = 'У этого workload сейчас нет подов.';
|
||
return;
|
||
}
|
||
podSel.replaceChildren(...pods.map((pod) => el('option', { value: pod.name }, `${pod.name} · ${pod.phase} · ${pod.nodeName}`)));
|
||
const fill = () => {
|
||
const pod = pods.find((x) => x.name === podSel.value);
|
||
cSel.replaceChildren(...(pod?.containers || []).map((c) => el('option', { value: c }, c)));
|
||
};
|
||
podSel.onchange = () => { fill(); loadLogs(); };
|
||
cSel.onchange = loadLogs;
|
||
fill();
|
||
loadLogs();
|
||
}
|
||
async function loadLogs() {
|
||
const n = G.byId.get(detailsId);
|
||
const pod = $('#pod-select').value;
|
||
if (!n || !pod) return;
|
||
const out = $('#d-logs');
|
||
out.textContent = 'загрузка логов…';
|
||
const p = new URLSearchParams({ namespace: n.namespace, pod, container: $('#container-select').value || '' });
|
||
const r = await fetch('/api/logs?' + p);
|
||
const text = r.ok ? (await r.text()) || '(лог пуст)' : 'не удалось получить логи: HTTP ' + r.status;
|
||
if (detailsId === n.id) { out.textContent = text; out.scrollTop = out.scrollHeight; }
|
||
}
|
||
$('#logs-reload').addEventListener('click', loadLogs);
|
||
|
||
/* ---------- top bar ---------- */
|
||
$('#traffic-on').addEventListener('change', (e) => { state.traffic = e.target.checked; renderMap(); });
|
||
$('#traffic-window').addEventListener('change', (e) => { state.trafficWindow = Number(e.target.value); if (state.traffic) renderMap(); });
|
||
$('#infra-traffic').addEventListener('change', (e) => { state.infra = e.target.checked; renderMap(); });
|
||
$('#reload').addEventListener('click', () => load());
|
||
|
||
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||
readTheme();
|
||
imgCache.clear();
|
||
cy.style(mapStyle());
|
||
renderMap();
|
||
});
|
||
|
||
async function load() {
|
||
setStatus('загрузка графа…');
|
||
const r = await fetch('/api/graph');
|
||
if (!r.ok) { setStatus('не удалось загрузить граф: HTTP ' + r.status, true); return; }
|
||
indexGraph(await r.json());
|
||
podsFor = null;
|
||
yamlCache.clear();
|
||
if (state.scope.mode === 'ns') state.scope.ns = state.scope.ns.filter((ns) => G.byNs.has(ns));
|
||
if (state.scope.mode === 'ns' && !state.scope.ns.length) state.scope = { mode: 'cluster' };
|
||
if (state.selected && !G.byId.has(state.selected)) state.selected = null;
|
||
$('#updated').textContent = 'обновлено ' + new Date().toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
|
||
if (state.selected) revealInTree(state.selected);
|
||
await renderMap();
|
||
if (state.selected) { openDetails(state.selected); focusOnMap(state.selected); }
|
||
}
|
||
|
||
window.addEventListener('hashchange', () => {
|
||
if (location.hash === lastHash) return;
|
||
lastHash = location.hash;
|
||
state.scope = { mode: 'cluster' };
|
||
readHash();
|
||
if (state.selected && G.byId.has(state.selected)) { revealInTree(state.selected); openDetails(state.selected); } else closeDetails();
|
||
renderMap().then(() => state.selected && focusOnMap(state.selected));
|
||
});
|
||
|
||
readTheme();
|
||
cy.style(mapStyle());
|
||
readHash();
|
||
$('#view-ns').setAttribute('aria-selected', String(state.treeView === 'ns'));
|
||
$('#view-nodes').setAttribute('aria-selected', String(state.treeView === 'nodes'));
|
||
load();
|