import { badge, rowHTML, setRows, safe, showToast } from './helpers.js'; import { api } from './api.js'; const liveSockets = new Map(); let slowTimer = null; let fastTimer = null; const activeSids = new Set(); function closeForSid(sid) { const entry = liveSockets.get(sid); if (!entry) return; try { entry.obs && entry.obs.close(); } catch {} try { entry.task && entry.task.close(); } catch {} liveSockets.delete(sid); } export function stopAllAdminWatches() { if (slowTimer) { clearInterval(slowTimer); slowTimer = null; } if (fastTimer) { clearInterval(fastTimer); fastTimer = null; } activeSids.clear(); for (const sid of Array.from(liveSockets.keys())) closeForSid(sid); } function setBadge(cell, val) { if (!cell) return; cell.innerHTML = val; } function setMigrateDisabled(tr, disabled) { const btn = tr.querySelector('.act-migrate'); if (btn) btn.disabled = !!disabled; } function rebuildTargetSelect(selectEl, currentNode, nodes) { if (!selectEl) return; const html = nodes.map(n => `` ).join(''); selectEl.innerHTML = html; const idx = Array.from(selectEl.options).findIndex(o => !o.disabled); if (idx >= 0) selectEl.selectedIndex = idx; } export async function renderVMAdmin() { stopAllAdminWatches(); const data = await api.listAllVmct(); const arr = Array.isArray(data.all) ? data.all : []; const availableNodes = Array.isArray(data.nodes) ? data.nodes : []; const tbody = document.querySelector('#vm-admin tbody'); if (!arr.length) { setRows(tbody, [rowHTML(['Brak VM/CT'])]); return; } const rows = arr.map(x => { const sid = safe(x.sid), type = safe(x.type), name = safe(x.name), node = safe(x.node); const st = /running/i.test(x.status || '') ? badge('running','ok') : badge(x.status || '—','dark'); const actions = `
`; const sel = ``; const tools = `
`; return rowHTML([sid, type.toUpperCase(), name, node, st, actions, sel, tools], `data-sid="${sid}"`); }); setRows(tbody, rows); Array.from(tbody.querySelectorAll('tr[data-sid]')).forEach(tr => { const sid = tr.getAttribute('data-sid'); const colSpan = tr.children.length; const nodeCell = tr.children[3]; const badgeCell = tr.children[4]; const targetSel = tr.querySelector('.target-node'); let sub = tr.nextElementSibling; if (!sub || !sub.classList.contains('mig-row')) { sub = document.createElement('tr'); sub.className = 'mig-row d-none'; const td = document.createElement('td'); td.colSpan = colSpan; td.innerHTML = '
Task status
'; sub.appendChild(td); tr.parentNode.insertBefore(sub, tr.nextSibling); } const logPre = sub.querySelector('.mig-log'); const toggleSub = (show) => sub.classList.toggle('d-none', !show); const setRowBusy = (busy) => { const nameCell = tr.children[2]; let spin = nameCell.querySelector('.op-spin'); if (busy && !spin) { const span = document.createElement('span'); span.className = 'op-spin spinner-border spinner-border-sm align-middle ms-2'; span.setAttribute('role','status'); span.setAttribute('aria-hidden','true'); nameCell.appendChild(span); } if (!busy && spin) spin.remove(); }; const getTarget = () => targetSel?.value || ''; const openTaskWS = (upid, node) => { if (!upid) return; toggleSub(true); logPre.textContent = `UPID: ${upid} @ ${node}\n`; const entry = liveSockets.get(sid) || {}; try { entry.task && entry.task.close(); } catch {} const wsTask = new WebSocket(api.wsTaskURL(upid, node)); entry.task = wsTask; liveSockets.set(sid, entry); activeSids.add(sid); wsTask.onmessage = (ev) => { try { const msg = JSON.parse(ev.data); if (msg.type === 'log' && msg.line) { logPre.textContent += msg.line + '\n'; logPre.scrollTop = logPre.scrollHeight; } else if (msg.type === 'status' && msg.status) { const ok = String(msg.status.exitstatus||'').toUpperCase() === 'OK'; const s = String(msg.status.status||'').toLowerCase(); setBadge(badgeCell, ok ? badge('running','ok') : (s === 'stopped' ? badge('stopped','dark') : badge('working','info'))); } else if (msg.type === 'done') { const ok = !!msg.ok; setBadge(badgeCell, ok ? badge('running','ok') : badge('error','err')); setRowBusy(false); setTimeout(() => toggleSub(false), 1000); setTimeout(() => activeSids.delete(sid), 5000); } } catch {} }; }; const ensureWatchOn = () => { const existing = liveSockets.get(sid); if (existing && existing.obs && existing.obs.readyState <= 1) return; closeForSid(sid); const wsObs = new WebSocket(api.wsObserveURL(sid)); liveSockets.set(sid, { obs: wsObs, task: null }); wsObs.onmessage = (ev) => { try { const msg = JSON.parse(ev.data); if (msg.type === 'vm' && msg.current) { const st = String(msg.current.status || msg.current.qmpstatus || '').toLowerCase(); const isRunning = /running|online|started/.test(st); setBadge(badgeCell, isRunning ? badge('running','ok') : (/stopp|shutdown|offline/.test(st) ? badge('stopped','dark') : badge(st||'—','info'))); setMigrateDisabled(tr, isRunning); if (!isRunning && st) activeSids.add(sid); } else if (msg.type === 'task-start' && msg.upid && msg.node) { openTaskWS(msg.upid, msg.node); activeSids.add(sid); } else if (msg.type === 'task' && msg.upid && msg.status) { const stopped = String(msg.status||'').toLowerCase() === 'stopped'; if (stopped && typeof msg.exitstatus !== 'undefined') { const ok = String(msg.exitstatus||'').toUpperCase() === 'OK'; setBadge(badgeCell, ok ? badge('running','ok') : badge('error','err')); setTimeout(() => activeSids.delete(sid), 5000); } else { setBadge(badgeCell, badge('working','info')); activeSids.add(sid); } } else if (msg.type === 'moved' && msg.new_node) { if (nodeCell) nodeCell.textContent = msg.new_node; rebuildTargetSelect(targetSel, msg.new_node, Array.from(new Set([...(window.__nodesCache||[]), msg.new_node]))); activeSids.add(sid); } else if (msg.type === 'done' && typeof msg.ok === 'boolean') { setBadge(badgeCell, msg.ok ? badge('running','ok') : badge('error','err')); setTimeout(() => activeSids.delete(sid), 5000); } } catch {} }; wsObs.onclose = () => { const e = liveSockets.get(sid); if (e && e.obs === wsObs) { liveSockets.set(sid, { obs: null, task: e.task || null }); } }; }; const doAction = async (action, withTarget=false) => { setRowBusy(true); try { const target = withTarget ? getTarget() : undefined; ensureWatchOn(); if (action !== 'unlock') { setBadge(badgeCell, badge('working','info')); toggleSub(true); activeSids.add(sid); } const resp = await api.vmAction(sid, action, target); if (!resp.ok) throw new Error(resp.error || 'unknown'); if (!resp.upid) { logPre.textContent = `Waiting for task… (${action})\n`; setRowBusy(false); activeSids.add(sid); return; } openTaskWS(resp.upid, resp.source_node); } catch (e) { showToast('Error', 'ERROR: ' + (e.message || e), 'danger'); setRowBusy(false); toggleSub(false); activeSids.delete(sid); } }; tr.querySelector('.act-unlock')?.addEventListener('click', () => doAction('unlock')); tr.querySelector('.act-start')?.addEventListener('click', () => doAction('start')); tr.querySelector('.act-stop')?.addEventListener('click', () => doAction('stop')); tr.querySelector('.act-shutdown')?.addEventListener('click',() => doAction('shutdown')); tr.querySelector('.act-migrate')?.addEventListener('click', () => doAction('migrate', true)); tr.querySelector('.act-status')?.addEventListener('click', () => toggleSub(sub.classList.contains('d-none'))); ensureWatchOn(); const initialRunning = /running/i.test(tr.querySelector('td:nth-child(5)')?.innerText || ''); setMigrateDisabled(tr, initialRunning); }); window.__nodesCache = availableNodes.slice(); slowTimer = setInterval(async () => { try { const latest = await api.listAllVmct(); const all = Array.isArray(latest.all) ? latest.all : []; const bySid = new Map(all.map(x => [String(x.sid), x])); const nodesNow = Array.isArray(latest.nodes) ? latest.nodes : window.__nodesCache || []; window.__nodesCache = nodesNow; Array.from(tbody.querySelectorAll('tr[data-sid]')).forEach(tr => { const sid = tr.getAttribute('data-sid'); const rowData = bySid.get(sid); if (!rowData) return; const nodeCell = tr.children[3]; const badgeCell = tr.children[4]; const targetSel = tr.querySelector('.target-node'); const newNode = String(rowData.node || '').trim(); if (nodeCell && newNode && nodeCell.textContent.trim() !== newNode) { nodeCell.textContent = newNode; rebuildTargetSelect(targetSel, newNode, nodesNow); } const isRunning = /running/i.test(rowData.status || ''); setBadge(badgeCell, isRunning ? badge('running','ok') : badge(rowData.status || '—','dark')); setMigrateDisabled(tr, isRunning); }); } catch {} }, 30000); fastTimer = setInterval(async () => { try { const sids = Array.from(activeSids); if (!sids.length) return; for (const sid of sids) { const detail = await api.vmDetail(sid); if (!detail || !detail.meta) continue; const tr = tbody.querySelector(`tr[data-sid="${sid}"]`); if (!tr) continue; const nodeCell = tr.children[3]; const badgeCell = tr.children[4]; const targetSel = tr.querySelector('.target-node'); const stRaw = String((detail.current && (detail.current.status || detail.current.qmpstatus)) || '').toLowerCase(); const isRunning = /running|online|started/.test(stRaw); setBadge(badgeCell, isRunning ? badge('running','ok') : (/stopp|shutdown|offline/.test(stRaw) ? badge('stopped','dark') : badge(stRaw||'—','info'))); setMigrateDisabled(tr, isRunning); const newNode = String(detail.node || (detail.meta && detail.meta.node) || '').trim(); if (newNode) { if (nodeCell && nodeCell.textContent.trim() !== newNode) { nodeCell.textContent = newNode; } rebuildTargetSelect(targetSel, newNode, window.__nodesCache || []); } if (stRaw && /running|stopped|shutdown/.test(stRaw)) { setTimeout(() => activeSids.delete(sid), 5000); } } } catch {} }, 10000); window.addEventListener('beforeunload', stopAllAdminWatches, { once: true }); }