refator_comm1

This commit is contained in:
Mateusz Gruszczyński
2025-10-18 21:41:24 +02:00
parent e3b3ff235b
commit 39c783c403

View File

@@ -4,7 +4,7 @@ import { api } from './api.js';
export async function renderVMAdmin() { export async function renderVMAdmin() {
const data = await api.listAllVmct(); const data = await api.listAllVmct();
const arr = Array.isArray(data.all) ? data.all : []; const arr = Array.isArray(data.all) ? data.all : [];
const nodes = Array.isArray(data.nodes) ? data.nodes : []; const availableNodes = Array.isArray(data.nodes) ? data.nodes : [];
const tbody = document.querySelector('#vm-admin tbody'); const tbody = document.querySelector('#vm-admin tbody');
if (!arr.length) { setRows(tbody, [rowHTML(['Brak VM/CT'])]); return; } if (!arr.length) { setRows(tbody, [rowHTML(['Brak VM/CT'])]); return; }
@@ -18,8 +18,8 @@ export async function renderVMAdmin() {
<button class="btn btn-outline-warning act-shutdown">Shutdown</button> <button class="btn btn-outline-warning act-shutdown">Shutdown</button>
<button class="btn btn-outline-danger act-stop">Stop</button> <button class="btn btn-outline-danger act-stop">Stop</button>
</div>`; </div>`;
const sel = `<select class="form-select form-select-sm target-node" style="min-width:140px"> const sel = `<select class="form-select form-select-sm target-node" style="min-width:160px">
${nodes.map(n => `<option value="${n}" ${n === x.node ? 'disabled' : ''}>${n}${n === x.node ? ' (src)' : ''}</option>`).join('')} ${availableNodes.map(n => `<option value="${n}" ${n === x.node ? 'disabled' : ''}>${n}${n === x.node ? ' (src)' : ''}</option>`).join('')}
</select>`; </select>`;
const tools = `<div class="d-flex align-items-center gap-2"> const tools = `<div class="d-flex align-items-center gap-2">
<button class="btn btn-outline-primary btn-sm act-migrate">Migrate (offline)</button> <button class="btn btn-outline-primary btn-sm act-migrate">Migrate (offline)</button>
@@ -34,8 +34,10 @@ export async function renderVMAdmin() {
Array.from(tbody.querySelectorAll('tr[data-sid]')).forEach(tr => { Array.from(tbody.querySelectorAll('tr[data-sid]')).forEach(tr => {
const sid = tr.getAttribute('data-sid'); const sid = tr.getAttribute('data-sid');
const colSpan = tr.children.length; const colSpan = tr.children.length;
const nodeCell = tr.children[3]; // Node const nodeCell = tr.children[3]; // kolumna Node
const badgeCell = tr.children[4]; // Status const badgeCell = tr.children[4]; // kolumna Status
const targetSel = tr.querySelector('.target-node');
const watchBtn = tr.querySelector('.act-watch');
// subpanel (log) // subpanel (log)
let sub = tr.nextElementSibling; let sub = tr.nextElementSibling;
@@ -49,7 +51,7 @@ export async function renderVMAdmin() {
const toggleSub = (show) => sub.classList.toggle('d-none', !show); const toggleSub = (show) => sub.classList.toggle('d-none', !show);
let wsObs = null; // observe websocket let wsObs = null; // observe websocket
let wsTask = null; // tail websocket (auto z observe) let wsTask = null; // tail websocket
const closeWS = () => { const closeWS = () => {
try { wsObs && wsObs.close(); } catch {} try { wsObs && wsObs.close(); } catch {}
@@ -69,12 +71,26 @@ export async function renderVMAdmin() {
if (!busy && spin) spin.remove(); if (!busy && spin) spin.remove();
}; };
const getTarget = () => tr.querySelector('.target-node')?.value || ''; const rebuildTargetSelect = (currentNode) => {
if (!targetSel) return;
const current = currentNode || (nodeCell?.textContent || '').trim();
const html = availableNodes.map(n =>
`<option value="${n}" ${n === current ? 'disabled selected' : ''}>${n}${n === current ? ' (src)' : ''}</option>`).join('');
targetSel.innerHTML = html;
// jeśli selected jest disabled, ustaw zaznaczenie na pierwszy dozwolony
if (targetSel.options.length) {
const idx = Array.from(targetSel.options).findIndex(o => !o.disabled);
if (idx >= 0) targetSel.selectedIndex = idx;
}
};
const getTarget = () => targetSel?.value || '';
const openTaskWS = (upid, node) => { const openTaskWS = (upid, node) => {
if (!upid) return; if (!upid) return;
toggleSub(true); toggleSub(true);
logPre.textContent = `UPID: ${upid} @ ${node}\n`; logPre.textContent = `UPID: ${upid} @ ${node}\n`;
try { wsTask && wsTask.close(); } catch {}
wsTask = new WebSocket(api.wsTaskURL(upid, node)); wsTask = new WebSocket(api.wsTaskURL(upid, node));
wsTask.onmessage = (ev) => { wsTask.onmessage = (ev) => {
try { try {
@@ -84,13 +100,15 @@ export async function renderVMAdmin() {
logPre.scrollTop = logPre.scrollHeight; logPre.scrollTop = logPre.scrollHeight;
} else if (msg.type === 'status' && msg.status) { } else if (msg.type === 'status' && msg.status) {
const ok = String(msg.status.exitstatus||'').toUpperCase() === 'OK'; const ok = String(msg.status.exitstatus||'').toUpperCase() === 'OK';
const stopped = String(msg.status.status||'').toLowerCase() === 'stopped'; const s = String(msg.status.status||'').toLowerCase();
if (badgeCell) badgeCell.innerHTML = ok ? badge('running','ok') : (stopped ? badge('stopped','dark') : badge('working','info')); if (badgeCell) badgeCell.innerHTML = ok ? badge('running','ok') :
(s === 'stopped' ? badge('stopped','dark') : badge('working','info'));
} else if (msg.type === 'done') { } else if (msg.type === 'done') {
const ok = !!msg.ok; const ok = !!msg.ok;
if (badgeCell) badgeCell.innerHTML = ok ? badge('running','ok') : badge('error','err'); if (badgeCell) badgeCell.innerHTML = ok ? badge('running','ok') : badge('error','err');
setRowBusy(false); setRowBusy(false);
setTimeout(() => toggleSub(false), 1200); // nie chowam subpanelu natychmiast, żeby dać doczytać log
setTimeout(() => toggleSub(false), 1500);
try { document.getElementById('btnRefresh').click(); } catch {} try { document.getElementById('btnRefresh').click(); } catch {}
} }
} catch {} } catch {}
@@ -98,10 +116,15 @@ export async function renderVMAdmin() {
wsTask.onerror = () => {}; wsTask.onerror = () => {};
}; };
const openObserveWS = () => { const ensureWatchOn = () => {
if (wsObs) return; if (wsObs) return;
const url = api.wsObserveURL(sid); const url = api.wsObserveURL(sid);
wsObs = new WebSocket(url); wsObs = new WebSocket(url);
if (watchBtn) {
watchBtn.classList.remove('btn-outline-info');
watchBtn.classList.add('btn-info');
watchBtn.textContent = 'Watching 🔔';
}
wsObs.onmessage = (ev) => { wsObs.onmessage = (ev) => {
try { try {
const msg = JSON.parse(ev.data); const msg = JSON.parse(ev.data);
@@ -131,18 +154,17 @@ export async function renderVMAdmin() {
else if (msg.type === 'moved' && msg.new_node) { else if (msg.type === 'moved' && msg.new_node) {
if (nodeCell) nodeCell.textContent = msg.new_node; if (nodeCell) nodeCell.textContent = msg.new_node;
rebuildTargetSelect(msg.new_node);
try { document.getElementById('btnRefresh').click(); } catch {} try { document.getElementById('btnRefresh').click(); } catch {}
} }
else if (msg.type === 'done' && msg.upid) { else if (msg.type === 'done' && typeof msg.ok === 'boolean') {
if (typeof msg.ok === 'boolean') {
if (badgeCell) badgeCell.innerHTML = msg.ok ? badge('running','ok') : badge('error','err'); if (badgeCell) badgeCell.innerHTML = msg.ok ? badge('running','ok') : badge('error','err');
} }
}
} catch {} } catch {}
}; };
wsObs.onclose = () => { wsObs = null; }; wsObs.onclose = () => { wsObs = null; if (watchBtn) { watchBtn.classList.remove('btn-info'); watchBtn.classList.add('btn-outline-info'); watchBtn.textContent='Watch 🔔'; } };
wsObs.onerror = () => {}; wsObs.onerror = () => {};
}; };
@@ -150,32 +172,38 @@ export async function renderVMAdmin() {
setRowBusy(true); setRowBusy(true);
try { try {
const target = withTarget ? getTarget() : undefined; const target = withTarget ? getTarget() : undefined;
ensureWatchOn();
if (action !== 'unlock') toggleSub(true);
const resp = await api.vmAction(sid, action, target); const resp = await api.vmAction(sid, action, target);
if (!resp.ok) throw new Error(resp.error || 'unknown'); if (!resp.ok) throw new Error(resp.error || 'unknown');
// unlock brak UPID
if (!resp.upid) { if (!resp.upid) {
showToast('Success', `${action} executed for ${sid}`, 'success');
setRowBusy(false); toggleSub(false); logPre.textContent = `Waiting for task… (${action})\n`;
try { document.getElementById('btnRefresh').click(); } catch {} showToast('Info', `${action} zainicjowane`, 'info');
setRowBusy(false);
return; return;
} }
// UPID → WS tail
openTaskWS(resp.upid, resp.source_node); openTaskWS(resp.upid, resp.source_node);
} catch (e) { } catch (e) {
showToast('Error', 'ERROR: ' + (e.message || e), 'danger'); showToast('Error', 'ERROR: ' + (e.message || e), 'danger');
setRowBusy(false); setRowBusy(false);
toggleSub(false);
} }
}; };
tr.querySelector('.act-unlock')?.addEventListener('click', () => doAction('unlock')); tr.querySelector('.act-unlock')?.addEventListener('click', () => doAction('unlock'));
tr.querySelector('.act-start')?.addEventListener('click', () => { toggleSub(true); doAction('start'); }); tr.querySelector('.act-start')?.addEventListener('click', () => doAction('start'));
tr.querySelector('.act-stop')?.addEventListener('click', () => { toggleSub(true); doAction('stop'); }); tr.querySelector('.act-stop')?.addEventListener('click', () => doAction('stop'));
tr.querySelector('.act-shutdown')?.addEventListener('click', () => { toggleSub(true); doAction('shutdown'); }); tr.querySelector('.act-shutdown')?.addEventListener('click',() => doAction('shutdown'));
tr.querySelector('.act-migrate')?.addEventListener('click', () => { toggleSub(true); doAction('migrate', true); }); tr.querySelector('.act-migrate')?.addEventListener('click', () => doAction('migrate', true));
tr.querySelector('.act-status')?.addEventListener('click', () => toggleSub(sub.classList.contains('d-none'))); tr.querySelector('.act-status')?.addEventListener('click', () => toggleSub(sub.classList.contains('d-none')));
const watchBtn = tr.querySelector('.act-watch');
if (watchBtn) { if (watchBtn) {
watchBtn.addEventListener('click', () => { watchBtn.addEventListener('click', () => {
if (wsObs) { if (wsObs) {
@@ -183,11 +211,11 @@ export async function renderVMAdmin() {
watchBtn.classList.remove('btn-info'); watchBtn.classList.add('btn-outline-info'); watchBtn.classList.remove('btn-info'); watchBtn.classList.add('btn-outline-info');
watchBtn.textContent = 'Watch 🔔'; watchBtn.textContent = 'Watch 🔔';
} else { } else {
openObserveWS(); ensureWatchOn();
watchBtn.classList.remove('btn-outline-info'); watchBtn.classList.add('btn-info');
watchBtn.textContent = 'Watching 🔔';
} }
}); });
} }
rebuildTargetSelect(nodeCell?.textContent?.trim());
}); });
} }