OrbiSubs panel: Engines tab (Whisper, LLM, gpu02 GPU, this host) with alerts
Tarea 080 y su agregado. El backend sondea gpu02 cada 15-30 s (solo GET /health, /slots, /props, /v1/models y el nvidia_gpu_exporter :9835), una vez para todas las pestañas. Los tiempos y fallas salen de los pedidos reales de cada canal: orbisubs.py y orbisubs_tr.py ahora escriben t, audio_s y error en sus .jsonl, y el panel los guarda 7 días en engine_reqs. Avisos en Eventos y punto en el menú: motor sin respuesta dos sondeos seguidos, p95 de 15 min sobre el umbral (3 s) y VRAM libre de la 3060 bajo 512 MiB.
This commit is contained in:
+39
-1
@@ -46,6 +46,37 @@ CREATE TABLE IF NOT EXISTS events (
|
||||
message TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts);
|
||||
-- Pestaña Motores (tarea 080): configuración, pedidos a los motores sacados de las
|
||||
-- métricas de cada canal y sondeos de /health y /slots. 7 días como máximo.
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL -- JSON
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS engine_reqs (
|
||||
ts REAL NOT NULL, -- epoch s (hora en que terminó el pedido)
|
||||
kind TEXT NOT NULL, -- asr | llm
|
||||
url TEXT NOT NULL,
|
||||
channel TEXT NOT NULL,
|
||||
dur_s REAL, -- tiempo del pedido HTTP
|
||||
audio_s REAL, -- segundos de audio enviados (solo asr)
|
||||
ok INTEGER NOT NULL,
|
||||
error TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_engine_reqs ON engine_reqs(kind, url, ts);
|
||||
CREATE TABLE IF NOT EXISTS engine_polls (
|
||||
ts REAL NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
up INTEGER NOT NULL,
|
||||
busy INTEGER -- llm: algún slot procesando (de cualquiera)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_engine_polls ON engine_polls(kind, url, ts);
|
||||
CREATE TABLE IF NOT EXISTS gpu_samples ( -- exporter de gpu02 (080-agregado)
|
||||
ts REAL NOT NULL,
|
||||
idx INTEGER NOT NULL, -- índice de nvidia-smi (0 = 3080, 1 = 3060)
|
||||
util REAL, mem_used REAL, mem_total REAL, temp REAL, power REAL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_gpu_samples ON gpu_samples(ts);
|
||||
`);
|
||||
|
||||
function event(level, message, { channel = null, username = null } = {}) {
|
||||
@@ -54,4 +85,11 @@ function event(level, message, { channel = null, username = null } = {}) {
|
||||
db.prepare('DELETE FROM events WHERE id <= (SELECT MAX(id) - 2000 FROM events)').run();
|
||||
}
|
||||
|
||||
module.exports = { db, DATA_DIR, event };
|
||||
const getSetting = (key, def) => {
|
||||
const r = db.prepare('SELECT value FROM settings WHERE key = ?').get(key);
|
||||
if (!r) return def;
|
||||
try { return JSON.parse(r.value); } catch { return def; }
|
||||
};
|
||||
const setSetting = (key, value) => db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, JSON.stringify(value));
|
||||
|
||||
module.exports = { db, DATA_DIR, event, getSetting, setSetting };
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
'use strict';
|
||||
// motores.js — estado de los motores de gpu02 (whisper.cpp y el LLM) para la pestaña
|
||||
// Motores (tarea 080: "no veo nada de info de estado del llm, q usamos (whisper)").
|
||||
//
|
||||
// Dos fuentes:
|
||||
// - Lo que medimos nosotros: cada pedido que hacen orbisubs.py y orbisubs_tr.py queda
|
||||
// en /var/log/orbisubs/<canal>.jsonl y <canal>-en.jsonl. Se leen solo las líneas
|
||||
// nuevas y se guardan en engine_reqs (7 días como máximo).
|
||||
// - Un sondeo desde este backend cada 15–30 s: GET /health (los dos), /slots y, de vez
|
||||
// en cuando, /props y /v1/models (el LLM). Es una sola consulta aunque haya varias
|
||||
// pestañas abiertas: los browsers leen lo guardado acá, nunca le pegan a gpu02.
|
||||
// gpu02 es compartido: solo esos GET, nunca /load ni nada que le cambie el estado.
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { execFile } = require('child_process');
|
||||
const { db, event, getSetting, setSetting } = require('../db');
|
||||
const { LOG_DIR, HLS_DIR } = require('./status');
|
||||
|
||||
const KEEP_S = 7 * 86400;
|
||||
const DEFAULTS = {
|
||||
poll_s: 20,
|
||||
// whisper.cpp no informa el modelo ni la versión: esto lo declara quien lo instaló.
|
||||
asr: { model: 'large-v3-turbo', hw: 'RTX 3060 en gpu02', p95_warn_s: 3 },
|
||||
llm: { p95_warn_s: 3 },
|
||||
// GPU de gpu02 (080-agregado): nvidia_gpu_exporter que instaló Jorge. Qué corre en cada
|
||||
// placa es un dato declarado (el exporter no lo sabe).
|
||||
gpu: {
|
||||
url: 'http://192.168.2.10:9835/metrics',
|
||||
main_index: 1, // la 3060: Whisper y Qwen-VL
|
||||
vram_warn_mib: 512,
|
||||
roles: {
|
||||
0: 'Qwen3.5-9B (texto, :8001) · Real-ESRGAN de ESPER (:8010)',
|
||||
1: 'Qwen3-VL-8B (:8002) · Whisper large-v3-turbo (:8004)',
|
||||
},
|
||||
},
|
||||
};
|
||||
const DEFAULT_URL = { asr: 'http://192.168.2.10:8004', llm: 'http://192.168.2.10:8001' };
|
||||
const NAME = { asr: 'Whisper', llm: 'LLM' };
|
||||
const SLOW_WINDOW_S = 900; // el p95 del aviso se mira en los últimos 15 min
|
||||
const SLOW_MIN_N = 8; // con menos pedidos que esto no se avisa (un pico no es tendencia)
|
||||
|
||||
function config() {
|
||||
const c = getSetting('engines', {});
|
||||
return {
|
||||
poll_s: c.poll_s ?? DEFAULTS.poll_s,
|
||||
asr: { ...DEFAULTS.asr, ...(c.asr || {}) },
|
||||
llm: { ...DEFAULTS.llm, ...(c.llm || {}) },
|
||||
gpu: { ...DEFAULTS.gpu, ...(c.gpu || {}), roles: { ...DEFAULTS.gpu.roles, ...((c.gpu || {}).roles || {}) } },
|
||||
};
|
||||
}
|
||||
|
||||
function setConfig(b) {
|
||||
const c = config();
|
||||
const num = (v, lo, hi, what) => {
|
||||
const n = Number(v);
|
||||
if (!Number.isFinite(n) || n < lo || n > hi) { const e = new Error(`${what}: entre ${lo} y ${hi}`); e.status = 400; throw e; }
|
||||
return n;
|
||||
};
|
||||
const str = (v, max) => String(v ?? '').trim().slice(0, max);
|
||||
if (b.poll_s != null) c.poll_s = Math.round(num(b.poll_s, 15, 30, 'Sondeo (s)'));
|
||||
if (b.asr) {
|
||||
if (b.asr.model != null) c.asr.model = str(b.asr.model, 80);
|
||||
if (b.asr.hw != null) c.asr.hw = str(b.asr.hw, 80);
|
||||
if (b.asr.p95_warn_s != null) c.asr.p95_warn_s = num(b.asr.p95_warn_s, 0.5, 60, 'Umbral de p95 de Whisper (s)');
|
||||
}
|
||||
if (b.llm && b.llm.p95_warn_s != null) c.llm.p95_warn_s = num(b.llm.p95_warn_s, 0.5, 60, 'Umbral de p95 del LLM (s)');
|
||||
if (b.gpu && b.gpu.vram_warn_mib != null) c.gpu.vram_warn_mib = Math.round(num(b.gpu.vram_warn_mib, 64, 16384, 'Aviso de VRAM libre (MiB)'));
|
||||
setSetting('engines', c);
|
||||
return c;
|
||||
}
|
||||
|
||||
const normUrl = u => String(u || '').trim().replace(/\/+$/, '');
|
||||
|
||||
// Los motores son las URL que usan los canales: si un canal apunta a otra URL (la
|
||||
// prueba de caída de la 080 la pone en :8999), aparece su tarjeta.
|
||||
function engineList(channels) {
|
||||
const out = [];
|
||||
for (const kind of ['asr', 'llm']) {
|
||||
const urls = new Map();
|
||||
for (const ch of channels) {
|
||||
if (kind === 'llm' && !(ch.cfg.tr && ch.cfg.tr.langs && ch.cfg.tr.langs.length)) continue;
|
||||
const u = normUrl(kind === 'asr' ? ch.cfg.asr.url : ch.cfg.tr.url);
|
||||
if (!u) continue;
|
||||
if (!urls.has(u)) urls.set(u, []);
|
||||
urls.get(u).push(ch.slug);
|
||||
}
|
||||
if (!urls.size) urls.set(DEFAULT_URL[kind], []);
|
||||
for (const [url, chans] of urls) out.push({ key: `${kind}|${url}`, kind, url, channels: chans });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ---------- números ---------- */
|
||||
function quantile(arr, q) {
|
||||
if (!arr.length) return null;
|
||||
const s = [...arr].sort((a, b) => a - b);
|
||||
const pos = (s.length - 1) * q, lo = Math.floor(pos), hi = Math.ceil(pos);
|
||||
return s[lo] + (s[hi] - s[lo]) * (pos - lo);
|
||||
}
|
||||
const r3 = v => (v == null ? null : Math.round(v * 1000) / 1000);
|
||||
|
||||
function statsOf(rows) {
|
||||
const ok = rows.filter(r => r.ok && r.dur_s != null);
|
||||
const d = ok.map(r => r.dur_s);
|
||||
const rtf = ok.filter(r => r.audio_s > 0).map(r => r.dur_s / r.audio_s);
|
||||
return {
|
||||
n: rows.length,
|
||||
fails: rows.length - ok.length,
|
||||
median_s: r3(quantile(d, 0.5)),
|
||||
p95_s: r3(quantile(d, 0.95)),
|
||||
rtf: r3(quantile(rtf, 0.5)),
|
||||
};
|
||||
}
|
||||
|
||||
// Sparkline: mediana y máximo por minuto de la última hora (60 puntos como mucho).
|
||||
function buckets(rows, now, span = 3600, step = 60) {
|
||||
const n = Math.ceil(span / step), out = [];
|
||||
const by = Array.from({ length: n }, () => ({ d: [], fails: 0 }));
|
||||
for (const r of rows) {
|
||||
const i = Math.floor((r.ts - (now - span)) / step);
|
||||
if (i < 0 || i >= n) continue;
|
||||
if (r.ok && r.dur_s != null) by[i].d.push(r.dur_s); else by[i].fails++;
|
||||
}
|
||||
by.forEach((b, i) => out.push({ t: Math.round(now - span + i * step), med: r3(quantile(b.d, 0.5)), max: r3(b.d.length ? Math.max(...b.d) : null), n: b.d.length, fails: b.fails }));
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ---------- lectura de las métricas de los canales ---------- */
|
||||
// Una línea del .jsonl del ASR o del traductor → un pedido, o null si no hubo pedido.
|
||||
function parseLine(kind, r) {
|
||||
if (!r || typeof r.t !== 'number') return null; // líneas de antes de la 080: sin hora
|
||||
if (kind === 'asr') {
|
||||
if (typeof r.http_s !== 'number') return null; // ese segmento no pidió nada (menos de 1 s pendiente)
|
||||
return { ts: r.t, dur_s: r.http_s, audio_s: r.audio_s ?? null, ok: r.error ? 0 : 1, error: r.error || null };
|
||||
}
|
||||
if (!('es' in r) || typeof r.qwen_s !== 'number') return null;
|
||||
const fail = !!r.error || r.en == null;
|
||||
return { ts: r.t, dur_s: r.qwen_s, audio_s: null, ok: fail ? 0 : 1, error: fail ? (r.error || 'sin traducción') : null };
|
||||
}
|
||||
|
||||
const insReq = db.prepare('INSERT INTO engine_reqs (ts, kind, url, channel, dur_s, audio_s, ok, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
|
||||
// Lee lo nuevo de un archivo desde el último offset guardado (sobrevive un reinicio).
|
||||
function ingestFile(file, kind, url, channel) {
|
||||
const key = `off:${file}`;
|
||||
let st;
|
||||
try { st = fs.statSync(file); } catch { return 0; }
|
||||
let { ino, off } = getSetting(key, { ino: null, off: 0 });
|
||||
if (ino !== st.ino || st.size < off) off = 0; // rotado o truncado
|
||||
if (st.size === off) return 0;
|
||||
const len = Math.min(st.size - off, 8 << 20);
|
||||
const buf = Buffer.alloc(len);
|
||||
const fd = fs.openSync(file, 'r');
|
||||
try { fs.readSync(fd, buf, 0, len, off); } finally { fs.closeSync(fd); }
|
||||
const lastNl = buf.lastIndexOf(10);
|
||||
if (lastNl < 0) return 0; // línea a medias: se lee la próxima vez
|
||||
const cutoff = Date.now() / 1000 - KEEP_S;
|
||||
let n = 0;
|
||||
const tx = db.transaction(lines => {
|
||||
for (const l of lines) {
|
||||
if (!l.trim()) continue;
|
||||
let r; try { r = JSON.parse(l); } catch { continue; }
|
||||
const q = parseLine(kind, r);
|
||||
if (!q || q.ts < cutoff) continue;
|
||||
insReq.run(q.ts, kind, url, channel, q.dur_s, q.audio_s, q.ok, q.error); n++;
|
||||
}
|
||||
});
|
||||
tx(buf.subarray(0, lastNl).toString('utf8').split('\n'));
|
||||
setSetting(key, { ino: st.ino, off: off + lastNl + 1 });
|
||||
return n;
|
||||
}
|
||||
|
||||
function ingest(channels) {
|
||||
for (const ch of channels) {
|
||||
ingestFile(path.join(LOG_DIR, `${ch.slug}.jsonl`), 'asr', normUrl(ch.cfg.asr.url), ch.slug);
|
||||
ingestFile(path.join(LOG_DIR, `${ch.slug}-en.jsonl`), 'llm', normUrl(ch.cfg.tr.url), ch.slug);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- sondeo ---------- */
|
||||
async function get(url, timeoutMs = 4000) {
|
||||
const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { 'User-Agent': 'OrbiSubs-panel' } });
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
const errText = e => (e && e.cause && e.cause.code) || (e && e.name === 'TimeoutError' ? 'sin respuesta en 4 s' : (e && e.message) || String(e));
|
||||
|
||||
const state = new Map(); // key → estado del motor (también en settings, para sobrevivir un reinicio)
|
||||
let pollN = 0, polledAt = null;
|
||||
const insPoll = db.prepare('INSERT INTO engine_polls (ts, kind, url, up, busy) VALUES (?, ?, ?, ?, ?)');
|
||||
|
||||
function stOf(key) {
|
||||
if (!state.has(key)) state.set(key, getSetting(`st:${key}`, { fails: 0, last_ok: null, down_since: null, last_err: null, alerted_down: false, slow: false, info: null }));
|
||||
return state.get(key);
|
||||
}
|
||||
const fmtDur = s => (s < 90 ? `${Math.round(s)} s` : s < 5400 ? `${Math.round(s / 60)} min` : `${(s / 3600).toFixed(1)} h`);
|
||||
|
||||
async function probe(e) {
|
||||
const s = stOf(e.key);
|
||||
const now = Date.now();
|
||||
let busy = null;
|
||||
try {
|
||||
const h = await get(`${e.url}/health`);
|
||||
if (h && h.status && h.status !== 'ok') throw new Error(`health: ${h.status}`);
|
||||
if (e.kind === 'llm') {
|
||||
const slots = await get(`${e.url}/slots`);
|
||||
if (Array.isArray(slots)) {
|
||||
busy = slots.some(x => x.is_processing) ? 1 : 0;
|
||||
s.slots = { total: slots.length, busy: slots.filter(x => x.is_processing).length };
|
||||
}
|
||||
// /props y /v1/models casi no cambian: cada ~10 sondeos o si falta el dato.
|
||||
if (!s.info || pollN % 10 === 0) {
|
||||
const p = await get(`${e.url}/props`).catch(() => null);
|
||||
const m = await get(`${e.url}/v1/models`).catch(() => null);
|
||||
if (p || m) {
|
||||
s.info = {
|
||||
model_path: p && p.model_path || null,
|
||||
model_ftype: p && p.model_ftype || null,
|
||||
n_ctx: p && ((p.default_generation_settings && p.default_generation_settings.n_ctx) ?? p.n_ctx) || null,
|
||||
total_slots: p && p.total_slots || null,
|
||||
build: p && p.build_info || null,
|
||||
published: (m && m.data && m.data[0] && m.data[0].id) || (p && p.model_alias) || null,
|
||||
read_at: now,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.alerted_down) {
|
||||
event('info', `${NAME[e.kind]} volvió a responder (${e.url}) después de ${fmtDur((now - s.down_since) / 1000)} caído`);
|
||||
}
|
||||
Object.assign(s, { fails: 0, last_ok: now, down_since: null, alerted_down: false, last_err: null });
|
||||
insPoll.run(now / 1000, e.kind, e.url, 1, busy);
|
||||
} catch (err) {
|
||||
s.fails++;
|
||||
s.last_err = errText(err);
|
||||
if (!s.down_since) s.down_since = now;
|
||||
if (s.fails >= 2 && !s.alerted_down) {
|
||||
s.alerted_down = true;
|
||||
event('error', `${NAME[e.kind]} no responde (${e.url}): ${s.last_err}. Dos sondeos seguidos sin respuesta`);
|
||||
}
|
||||
insPoll.run(now / 1000, e.kind, e.url, 0, null);
|
||||
}
|
||||
s.last_check = now;
|
||||
}
|
||||
|
||||
// Aviso de lentitud: p95 de los últimos 15 min contra el umbral de la configuración.
|
||||
function checkSlow(e, cfg) {
|
||||
const s = stOf(e.key);
|
||||
const since = Date.now() / 1000 - SLOW_WINDOW_S;
|
||||
const rows = db.prepare('SELECT dur_s FROM engine_reqs WHERE kind = ? AND url = ? AND ts >= ? AND ok = 1').all(e.kind, e.url, since).map(r => r.dur_s);
|
||||
const p95 = rows.length >= SLOW_MIN_N ? quantile(rows, 0.95) : null;
|
||||
const thr = cfg[e.kind].p95_warn_s;
|
||||
s.p95_15m = r3(p95);
|
||||
if (p95 != null && p95 > thr && !s.slow) {
|
||||
s.slow = true;
|
||||
event('warn', `${NAME[e.kind]} lento (${e.url}): p95 de ${p95.toFixed(2)} s en 15 min, umbral ${thr} s`);
|
||||
} else if (s.slow && (p95 == null || p95 <= thr * 0.9)) {
|
||||
s.slow = false;
|
||||
event('info', `${NAME[e.kind]} (${e.url}) volvió a tiempos normales${p95 != null ? `: p95 de ${p95.toFixed(2)} s` : ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- GPU de gpu02 (exporter Prometheus, 080-agregado) ---------- */
|
||||
// Texto Prometheus → { uuid: { métrica: valor, ...labels de gpu_info } }.
|
||||
function parseProm(text) {
|
||||
const by = {};
|
||||
for (const line of String(text).split('\n')) {
|
||||
const m = /^nvidia_smi_(\w+)\{([^}]*)\}\s+(\S+)/.exec(line);
|
||||
if (!m) continue;
|
||||
const labels = {};
|
||||
for (const l of m[2].matchAll(/(\w+)="([^"]*)"/g)) labels[l[1]] = l[2];
|
||||
if (!labels.uuid) continue;
|
||||
const g = by[labels.uuid] || (by[labels.uuid] = {});
|
||||
if (m[1] === 'gpu_info') Object.assign(g, { name: labels.name, driver: labels.driver_version, cuda: labels.cuda_version, index: Number(labels.index) });
|
||||
// nvidia_smi_name e index también vienen como métrica numérica ("3060"): mandan los labels de gpu_info.
|
||||
else if (m[1] === 'name') continue;
|
||||
else if (m[1] === 'index') { if (g.index == null) g.index = Number(m[3]); }
|
||||
else g[m[1]] = Number(m[3]);
|
||||
}
|
||||
return Object.values(by).filter(g => Number.isFinite(g.index)).map(g => ({
|
||||
index: g.index, name: g.name || null, driver: g.driver || null, cuda: g.cuda || null,
|
||||
util: g.utilization_gpu_ratio ?? null, mem_used: g.memory_used_bytes ?? null, mem_total: g.memory_total_bytes ?? null,
|
||||
mem_free: g.memory_free_bytes ?? null, temp: g.temperature_gpu ?? null, power: g.power_draw_watts ?? null,
|
||||
})).sort((a, b) => a.index - b.index);
|
||||
}
|
||||
|
||||
const gpu = { fails: 0, last_ok: null, down_since: null, err: null, gpus: [], alerted_down: false, vram_low: false };
|
||||
const insGpu = db.prepare('INSERT INTO gpu_samples (ts, idx, util, mem_used, mem_total, temp, power) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
||||
async function probeGpu(cfg) {
|
||||
const now = Date.now();
|
||||
try {
|
||||
const r = await fetch(cfg.gpu.url, { signal: AbortSignal.timeout(4000), headers: { 'User-Agent': 'OrbiSubs-panel' } });
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
const gs = parseProm(await r.text());
|
||||
if (!gs.length) throw new Error('el exporter no trae placas');
|
||||
db.transaction(() => { for (const g of gs) insGpu.run(now / 1000, g.index, g.util, g.mem_used, g.mem_total, g.temp, g.power); })();
|
||||
if (gpu.alerted_down) event('info', `Exporter de GPU de gpu02 volvió a responder (${cfg.gpu.url})`);
|
||||
Object.assign(gpu, { fails: 0, last_ok: now, down_since: null, err: null, gpus: gs, alerted_down: false });
|
||||
// Aviso: VRAM libre de la placa principal (la 3060) por debajo del umbral.
|
||||
const main = gs.find(g => g.index === cfg.gpu.main_index);
|
||||
if (main && main.mem_free != null) {
|
||||
const freeMiB = main.mem_free / 1048576, thr = cfg.gpu.vram_warn_mib;
|
||||
if (freeMiB < thr && !gpu.vram_low) {
|
||||
gpu.vram_low = true;
|
||||
event('warn', `VRAM libre de la ${main.name || `GPU ${main.index}`} en gpu02: ${Math.round(freeMiB)} MiB, menos de ${thr} MiB`);
|
||||
} else if (gpu.vram_low && freeMiB > thr * 1.25) {
|
||||
gpu.vram_low = false;
|
||||
event('info', `VRAM libre de la ${main.name || `GPU ${main.index}`} en gpu02 de vuelta en ${Math.round(freeMiB)} MiB`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
gpu.fails++; gpu.err = errText(err);
|
||||
if (!gpu.down_since) gpu.down_since = now;
|
||||
if (gpu.fails >= 2 && !gpu.alerted_down) {
|
||||
gpu.alerted_down = true;
|
||||
event('warn', `Exporter de GPU de gpu02 no responde (${cfg.gpu.url}): ${gpu.err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function gpuView(cfg, nowS) {
|
||||
const rows = db.prepare('SELECT ts, idx, util FROM gpu_samples WHERE ts >= ? ORDER BY ts').all(nowS - 3600);
|
||||
return {
|
||||
url: cfg.gpu.url, main_index: cfg.gpu.main_index, vram_warn_mib: cfg.gpu.vram_warn_mib, roles: cfg.gpu.roles,
|
||||
state: gpu.fails >= 2 ? 'down' : gpu.fails === 1 ? 'doubt' : (gpu.last_ok ? 'up' : 'unknown'),
|
||||
last_ok: gpu.last_ok, down_since: gpu.down_since, err: gpu.err, vram_low: gpu.vram_low,
|
||||
gpus: gpu.gpus.map(g => {
|
||||
const mine = rows.filter(r => r.idx === g.index).map(r => ({ ts: r.ts, ok: 1, dur_s: r.util }));
|
||||
// buckets() saca mediana y máximo por minuto; acá el "tiempo" es el uso (0–1).
|
||||
return { ...g, spark: buckets(mine, nowS) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
let lastPrune = 0;
|
||||
async function tick(getChannels) {
|
||||
const channels = getChannels();
|
||||
const cfg = config();
|
||||
try { ingest(channels); } catch (err) { console.error('[motores] ingest', err); }
|
||||
const engines = engineList(channels);
|
||||
for (const e of engines) { // de a uno: gpu02 compartido, nada en paralelo
|
||||
await probe(e);
|
||||
try { checkSlow(e, cfg); } catch (err) { console.error('[motores] slow', err); }
|
||||
setSetting(`st:${e.key}`, stOf(e.key));
|
||||
}
|
||||
await probeGpu(cfg);
|
||||
pollN++; polledAt = Date.now();
|
||||
sampleCpu();
|
||||
if (Date.now() - lastPrune > 3600e3) {
|
||||
const cut = Date.now() / 1000 - KEEP_S;
|
||||
db.prepare('DELETE FROM engine_reqs WHERE ts < ?').run(cut);
|
||||
db.prepare('DELETE FROM engine_polls WHERE ts < ?').run(cut);
|
||||
db.prepare('DELETE FROM gpu_samples WHERE ts < ?').run(cut);
|
||||
lastPrune = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
let timer = null;
|
||||
function start(getChannels) {
|
||||
const loop = async () => {
|
||||
try { await tick(getChannels); } catch (err) { console.error('[motores]', err); }
|
||||
timer = setTimeout(loop, config().poll_s * 1000);
|
||||
};
|
||||
timer = setTimeout(loop, 2000);
|
||||
}
|
||||
|
||||
/* ---------- lo que ve el panel ---------- */
|
||||
function engineView(e, cfg, now) {
|
||||
const s = stOf(e.key);
|
||||
const nowS = now / 1000;
|
||||
const rows24 = db.prepare('SELECT ts, channel, dur_s, audio_s, ok, error FROM engine_reqs WHERE kind = ? AND url = ? AND ts >= ? ORDER BY ts').all(e.kind, e.url, nowS - 86400);
|
||||
const rows1 = rows24.filter(r => r.ts >= nowS - 3600);
|
||||
const lastErr = db.prepare('SELECT ts, channel, error FROM engine_reqs WHERE kind = ? AND url = ? AND ok = 0 ORDER BY ts DESC LIMIT 1').get(e.kind, e.url);
|
||||
const polls = db.prepare('SELECT up, busy FROM engine_polls WHERE kind = ? AND url = ? AND ts >= ?').all(e.kind, e.url, nowS - 3600);
|
||||
const chans = [...new Set(rows1.map(r => r.channel).concat(e.channels))];
|
||||
const v = {
|
||||
key: e.key, kind: e.kind, url: e.url, name: NAME[e.kind], channels: e.channels,
|
||||
state: s.fails >= 2 ? 'down' : s.fails === 1 ? 'doubt' : (s.last_ok ? 'up' : 'unknown'),
|
||||
last_ok: s.last_ok, down_since: s.down_since, last_check: s.last_check || null, last_err: s.last_err,
|
||||
slow: !!s.slow, p95_15m: s.p95_15m ?? null, p95_warn_s: cfg[e.kind].p95_warn_s,
|
||||
h1: statsOf(rows1), h24: statsOf(rows24),
|
||||
last_error: lastErr ? { ts: lastErr.ts, channel: lastErr.channel, error: lastErr.error } : null,
|
||||
spark: buckets(rows1, nowS),
|
||||
by_channel: chans.map(c => ({ channel: c, ...statsOf(rows1.filter(r => r.channel === c)) })),
|
||||
uptime_1h: polls.length ? r3(polls.filter(p => p.up).length / polls.length) : null,
|
||||
};
|
||||
if (e.kind === 'asr') v.declared = { model: cfg.asr.model, hw: cfg.asr.hw };
|
||||
if (e.kind === 'llm') {
|
||||
v.info = s.info || null;
|
||||
v.slots = s.fails ? null : (s.slots || null);
|
||||
const b = polls.filter(p => p.busy != null);
|
||||
v.busy_pct_1h = b.length ? r3(b.filter(p => p.busy).length / b.length) : null;
|
||||
v.busy_polls_1h = b.length;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function alertLevel(engines) {
|
||||
if (engines.some(e => e.state === 'down')) return 'red';
|
||||
if (engines.some(e => e.slow || e.state === 'doubt') || gpu.vram_low || gpu.fails >= 2) return 'amber';
|
||||
return null;
|
||||
}
|
||||
|
||||
function view(channels) {
|
||||
const cfg = config(), now = Date.now();
|
||||
const engines = engineList(channels).map(e => engineView(e, cfg, now));
|
||||
return { config: cfg, polled_at: polledAt, engines, gpu: gpuView(cfg, now / 1000), alert: alertLevel(engines), host: hostInfo() };
|
||||
}
|
||||
|
||||
function alert(channels) {
|
||||
const engines = engineList(channels).map(e => {
|
||||
const s = stOf(e.key);
|
||||
return { state: s.fails >= 2 ? 'down' : s.fails === 1 ? 'doubt' : 'up', slow: !!s.slow };
|
||||
});
|
||||
return alertLevel(engines);
|
||||
}
|
||||
|
||||
/* ---------- este equipo (CT 176) ---------- */
|
||||
// CPU del CT por su cgroup (v2): /proc/stat en un LXC puede mostrar el host.
|
||||
let cpuPrev = null, cpuPct = null;
|
||||
function readCg(f) { try { return fs.readFileSync(`/sys/fs/cgroup/${f}`, 'utf8'); } catch { return null; } }
|
||||
function sampleCpu() {
|
||||
const t = readCg('cpu.stat');
|
||||
const m = t && /usage_usec (\d+)/.exec(t);
|
||||
if (!m) return;
|
||||
const cur = { u: Number(m[1]), w: process.hrtime.bigint() };
|
||||
if (cpuPrev) {
|
||||
const du = cur.u - cpuPrev.u, dw = Number(cur.w - cpuPrev.w) / 1000;
|
||||
if (dw > 0) cpuPct = r3(du / dw / os.cpus().length);
|
||||
}
|
||||
cpuPrev = cur;
|
||||
}
|
||||
|
||||
const versions = { node: process.version };
|
||||
function sh(cmd, args) {
|
||||
return new Promise(res => execFile(cmd, args, { timeout: 5000 }, (err, out, errOut) => res(String(out || '') + String(errOut || ''))));
|
||||
}
|
||||
async function loadVersions() {
|
||||
versions.ffmpeg = ((await sh('ffmpeg', ['-hide_banner', '-version'])).match(/ffmpeg version (\S+)/) || [])[1] || null;
|
||||
versions.srt = ((await sh('srt-live-transmit', ['-version'])).match(/SRT Library version: ([\d.]+)/) || [])[1] || null;
|
||||
// La versión de OrbiSubs es el commit que se instaló (lo escribe el deploy en VERSION).
|
||||
for (const f of [process.env.ORBISUBS_VERSION_FILE, '/opt/orbisubs/VERSION', path.join(__dirname, '..', '..', 'VERSION')]) {
|
||||
if (!f) continue;
|
||||
try { versions.orbisubs = fs.readFileSync(f, 'utf8').trim(); break; } catch { /* sigue */ }
|
||||
}
|
||||
}
|
||||
|
||||
let hlsSize = { at: 0, bytes: null };
|
||||
function dirBytes(dir, depth = 0) {
|
||||
let n = 0;
|
||||
if (depth > 4) return 0;
|
||||
let ents; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return 0; }
|
||||
for (const d of ents) {
|
||||
const p = path.join(dir, d.name);
|
||||
if (d.isDirectory()) n += dirBytes(p, depth + 1);
|
||||
else if (d.isFile()) { try { n += fs.statSync(p).size; } catch { /* se borró recién */ } }
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function hostInfo() {
|
||||
const memCur = Number(readCg('memory.current')), memMaxRaw = (readCg('memory.max') || '').trim();
|
||||
const total = memMaxRaw && memMaxRaw !== 'max' ? Number(memMaxRaw) : os.totalmem();
|
||||
const used = Number.isFinite(memCur) && memCur > 0 ? memCur : os.totalmem() - os.freemem();
|
||||
let disk = null;
|
||||
try {
|
||||
const st = fs.statfsSync(HLS_DIR);
|
||||
disk = { total: st.blocks * st.bsize, free: st.bavail * st.bsize };
|
||||
} catch { /* sin /var/www/hls */ }
|
||||
if (Date.now() - hlsSize.at > 300e3) hlsSize = { at: Date.now(), bytes: dirBytes(HLS_DIR) };
|
||||
return {
|
||||
// Sin loadavg: en el LXC /proc/loadavg es el del host (pve7), no el del CT.
|
||||
hostname: os.hostname(), cores: os.cpus().length, cpu: cpuPct,
|
||||
mem: { used, total }, disk, hls_bytes: hlsSize.bytes, uptime_s: Math.round(os.uptime()), versions,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
start, view, alert, config, setConfig, loadVersions, tick,
|
||||
// para los tests
|
||||
engineList, parseLine, statsOf, buckets, quantile, ingestFile, normUrl, parseProm,
|
||||
};
|
||||
@@ -104,7 +104,9 @@ function route() {
|
||||
$$('.nav a').forEach(a => a.classList.toggle('active', a.dataset.route === r));
|
||||
clearInterval(pollTimer);
|
||||
if (r === 'events') { loadEvents(); pollTimer = setInterval(loadEvents, 10000); }
|
||||
else if (r === 'engines') { loadEngines(); pollTimer = setInterval(loadEngines, 10000); }
|
||||
else { loadChannels(); pollTimer = setInterval(loadChannels, 5000); }
|
||||
loadEngineAlert();
|
||||
}
|
||||
window.addEventListener('hashchange', route);
|
||||
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/* engines.js — pestaña Motores (tarea 080): Whisper, LLM, GPU de gpu02 y este equipo.
|
||||
* Todo sale de /api/engines: el backend sondea gpu02 y guarda los pedidos de los canales. */
|
||||
'use strict';
|
||||
|
||||
let enginesData = null;
|
||||
const fmtS = v => (v == null ? '—' : `${Number(v).toFixed(2)} s`);
|
||||
const fmtPct = v => (v == null ? '—' : `${Math.round(v * 100)} %`);
|
||||
const fmtBytes = b => {
|
||||
if (b == null) return '—';
|
||||
const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0;
|
||||
while (b >= 1024 && i < u.length - 1) { b /= 1024; i++; }
|
||||
return `${b.toFixed(b < 10 && i ? 1 : 0)} ${u[i]}`;
|
||||
};
|
||||
const fmtAgo = ms => {
|
||||
if (!ms) return '—';
|
||||
const s = Math.max(0, (Date.now() - ms) / 1000);
|
||||
if (s < 90) return t('hace {n} s', { n: Math.round(s) });
|
||||
if (s < 5400) return t('hace {n} min', { n: Math.round(s / 60) });
|
||||
if (s < 172800) return t('hace {n} h', { n: (s / 3600).toFixed(1) });
|
||||
return t('hace {n} días', { n: Math.round(s / 86400) });
|
||||
};
|
||||
const fmtTime = ms => (ms ? new Date(ms).toLocaleTimeString(OrbiLang.locale(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '—');
|
||||
const fmtUptime = s => {
|
||||
const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);
|
||||
return d ? `${d} d ${h} h` : h ? `${h} h ${m} min` : `${m} min`;
|
||||
};
|
||||
const chName = slug => { const c = (typeof channels !== 'undefined' ? channels : []).find(x => x.slug === slug); return c ? c.name : slug; };
|
||||
|
||||
async function loadEngineAlert() {
|
||||
try { const r = await api('GET', '/api/engines/alert'); setEngineDot(r.alert); } catch { /* banner o login */ }
|
||||
}
|
||||
function setEngineDot(level) {
|
||||
const d = $('#nav-engines-dot');
|
||||
d.classList.toggle('hidden', !level);
|
||||
d.classList.toggle('red', level === 'red');
|
||||
d.classList.toggle('amber', level === 'amber');
|
||||
d.title = level === 'red' ? t('Un motor no responde') : level === 'amber' ? t('Un motor anda lento o no respondió el último sondeo') : '';
|
||||
}
|
||||
setInterval(() => { if (me) loadEngineAlert(); }, 15000);
|
||||
|
||||
async function loadEngines() {
|
||||
try {
|
||||
if (!channels.length) { const r = await api('GET', '/api/channels'); channels = r.channels; }
|
||||
enginesData = await api('GET', '/api/engines');
|
||||
} catch { return; }
|
||||
setEngineDot(enginesData.alert);
|
||||
renderEngines();
|
||||
}
|
||||
|
||||
const STATE_E = {
|
||||
up: ['running', 'vivo'], down: ['error', 'caído'], doubt: ['connecting', 'sin respuesta'], unknown: ['stopped', 'sin datos'],
|
||||
};
|
||||
|
||||
// Sparkline SVG: mediana por minuto (línea) y máximo (área tenue); fallas como marcas rojas.
|
||||
function sparkline(points, warn) {
|
||||
const W = 300, H = 54, P = 3;
|
||||
const vals = points.flatMap(p => [p.med, p.max]).filter(v => v != null);
|
||||
if (!vals.length) return `<div class="spark-empty muted small">${t('sin pedidos en la última hora')}</div>`;
|
||||
const top = Math.max(...vals, warn || 0) * 1.1 || 1;
|
||||
const x = i => P + i * (W - 2 * P) / Math.max(1, points.length - 1);
|
||||
const y = v => H - P - v / top * (H - 2 * P);
|
||||
const path = k => {
|
||||
let d = '', pen = false;
|
||||
points.forEach((p, i) => {
|
||||
if (p[k] == null) { pen = false; return; }
|
||||
d += `${pen ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[k]).toFixed(1)}`; pen = true;
|
||||
});
|
||||
return d;
|
||||
};
|
||||
const fails = points.map((p, i) => (p.fails ? `<line x1="${x(i).toFixed(1)}" x2="${x(i).toFixed(1)}" y1="${P}" y2="${H - P}" class="sp-fail"/>` : '')).join('');
|
||||
const warnLine = warn && warn < top ? `<line x1="${P}" x2="${W - P}" y1="${y(warn).toFixed(1)}" y2="${y(warn).toFixed(1)}" class="sp-warn"/>` : '';
|
||||
return `<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(t('Tiempo por pedido, última hora'))}">
|
||||
${fails}${warnLine}<path d="${path('max')}" class="sp-max"/><path d="${path('med')}" class="sp-med"/></svg>
|
||||
<div class="spark-legend muted small"><span><i class="sw med"></i>${t('mediana por minuto')}</span><span><i class="sw max"></i>${t('máximo')}</span>${warn ? `<span><i class="sw warn"></i>${t('umbral {s} s', { s: warn })}</span>` : ''}<span>${t('escala 0–{s}', { s: fmtS(top) })}</span></div>`;
|
||||
}
|
||||
|
||||
function row(label, value, cls = '') { return `<div class="eng-row ${cls}"><span class="muted">${label}</span><span>${value}</span></div>`; }
|
||||
|
||||
function statsTable(e) {
|
||||
const h = [e.h1, e.h24];
|
||||
const r = (lbl, f) => `<tr><td class="muted">${lbl}</td>${h.map(x => `<td class="num">${f(x)}</td>`).join('')}</tr>`;
|
||||
return `<table class="tbl eng-tbl"><thead><tr><th></th><th class="num">${t('1 h')}</th><th class="num">${t('24 h')}</th></tr></thead><tbody>
|
||||
${r(t('Pedidos'), x => x.n)}
|
||||
${r(t('Fallas'), x => (x.fails ? `<span class="txt-red">${x.fails}</span>` : 0))}
|
||||
${r(t('Mediana'), x => fmtS(x.median_s))}
|
||||
${r('p95', x => fmtS(x.p95_s))}
|
||||
${e.kind === 'asr' ? r(t('RTF (mediana)'), x => (x.rtf == null ? '—' : x.rtf.toFixed(3))) : ''}
|
||||
</tbody></table>`;
|
||||
}
|
||||
|
||||
function byChannel(e) {
|
||||
if (!e.by_channel.length) return '';
|
||||
return `<table class="tbl eng-tbl"><thead><tr><th>${t('Canal (última hora)')}</th><th class="num">${t('Pedidos')}</th><th class="num">${t('Fallas')}</th><th class="num">${t('Mediana')}</th><th class="num">p95</th></tr></thead><tbody>
|
||||
${e.by_channel.map(c => `<tr><td>${esc(chName(c.channel))} <span class="mono">${esc(c.channel)}</span></td><td class="num">${c.n}</td><td class="num">${c.fails ? `<span class="txt-red">${c.fails}</span>` : 0}</td><td class="num">${fmtS(c.median_s)}</td><td class="num">${fmtS(c.p95_s)}</td></tr>`).join('')}
|
||||
</tbody></table>`;
|
||||
}
|
||||
|
||||
function aliveRows(e) {
|
||||
const out = [];
|
||||
if (e.state === 'down' || e.state === 'doubt') {
|
||||
out.push(row(t('Caído desde'), `<span class="txt-red">${fmtTime(e.down_since)}</span> <span class="muted small">(${fmtAgo(e.down_since)})</span>`));
|
||||
out.push(row(t('Error del sondeo'), `<span class="mono txt-red">${esc(e.last_err || '—')}</span>`));
|
||||
}
|
||||
out.push(row(t('Último OK'), e.last_ok ? `${fmtTime(e.last_ok)} <span class="muted small">(${fmtAgo(e.last_ok)})</span>` : '—'));
|
||||
out.push(row(t('Responde (1 h)'), fmtPct(e.uptime_1h)));
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
function lastErrorRow(e) {
|
||||
if (!e.last_error) return row(t('Último error de un pedido'), `<span class="muted">${t('ninguno guardado')}</span>`);
|
||||
const le = e.last_error;
|
||||
return row(t('Último error de un pedido'), `<span class="mono txt-red">${esc(le.error || '—')}</span><div class="muted small">${new Date(le.ts * 1000).toLocaleString(OrbiLang.locale())} · ${esc(chName(le.channel))}</div>`);
|
||||
}
|
||||
|
||||
function cardHead(title, sub, stateKey, extra = '') {
|
||||
const [cls, label] = STATE_E[stateKey] || STATE_E.unknown;
|
||||
return `<div class="panel-head"><div><h2>${title}</h2><div class="muted small">${sub}</div></div><div class="eng-badges">${extra}<span class="badge ${cls}">${t(label)}</span></div></div>`;
|
||||
}
|
||||
|
||||
function whisperCard(e) {
|
||||
const slow = e.slow ? `<span class="badge connecting" title="${esc(t('p95 de 15 min: {s}', { s: fmtS(e.p95_15m) }))}">${t('lento')}</span>` : '';
|
||||
return `<div class="panel eng-card">
|
||||
${cardHead(t('Whisper (reconocimiento)'), `<span class="mono">${esc(e.url)}</span>`, e.state, slow)}
|
||||
${row(t('Modelo'), `${esc(e.declared.model || '—')} <span class="chip chip-decl" title="${esc(t('whisper.cpp no lo informa: es lo que dice la configuración del panel'))}">${t('declarado')}</span>`)}
|
||||
${row(t('Equipo'), `${esc(e.declared.hw || '—')} <span class="chip chip-decl">${t('declarado')}</span>`)}
|
||||
${aliveRows(e)}
|
||||
<p class="field-hint">${t('Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso.')}</p>
|
||||
${statsTable(e)}
|
||||
${lastErrorRow(e)}
|
||||
<div class="eng-sub">${t('Tiempo por pedido, última hora')}</div>
|
||||
${sparkline(e.spark, e.p95_warn_s)}
|
||||
${byChannel(e)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function llmCard(e) {
|
||||
const i = e.info || {};
|
||||
const slow = e.slow ? `<span class="badge connecting">${t('lento')}</span>` : '';
|
||||
const busyNow = e.slots
|
||||
? (e.slots.busy ? `<span class="txt-amber">${t('ocupado: {b} de {n} slots', { b: e.slots.busy, n: e.slots.total })}</span>` : t('libre ({n} slots)', { n: e.slots.total }))
|
||||
: '—';
|
||||
const model = i.model_path ? `${esc(i.model_path.split('/').pop())}${i.model_ftype ? ` <span class="muted small">${esc(i.model_ftype)}</span>` : ''}` : '—';
|
||||
return `<div class="panel eng-card">
|
||||
${cardHead(t('LLM (traducción)'), `<span class="mono">${esc(e.url)}</span>`, e.state, slow)}
|
||||
${row(t('Modelo'), i.model_path ? `${model} <span class="chip chip-read" title="/props">${t('leído')}</span>` : model)}
|
||||
${row(t('Nombre publicado'), i.published ? `<span class="mono">${esc(i.published)}</span> <span class="chip chip-read" title="/v1/models">${t('leído')}</span>` : '—')}
|
||||
${row('n_ctx', i.n_ctx ? i.n_ctx.toLocaleString(OrbiLang.locale()) : '—')}
|
||||
${row(t('Versión (build)'), i.build ? `<span class="mono">${esc(i.build)}</span>` : '—')}
|
||||
${row(t('Ahora'), busyNow)}
|
||||
${row(t('Ocupado (1 h, sondeado)'), `${fmtPct(e.busy_pct_1h)} <span class="muted small">${t('de {n} sondeos, incluye a otros usuarios', { n: e.busy_polls_1h || 0 })}</span>`)}
|
||||
<p class="field-hint">${t('Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso, así que "ocupado" puede ser batman y no OrbiSubs.')}</p>
|
||||
${aliveRows(e)}
|
||||
${statsTable(e)}
|
||||
${lastErrorRow(e)}
|
||||
<div class="eng-sub">${t('Tiempo por pedido, última hora')}</div>
|
||||
${sparkline(e.spark, e.p95_warn_s)}
|
||||
${byChannel(e)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// Sparkline de uso de GPU: escala fija 0–100 %.
|
||||
function utilSpark(points) {
|
||||
const W = 300, H = 40, P = 3;
|
||||
if (!points.some(p => p.med != null)) return `<div class="spark-empty muted small">${t('sin muestras en la última hora')}</div>`;
|
||||
const x = i => P + i * (W - 2 * P) / Math.max(1, points.length - 1);
|
||||
const y = v => H - P - v * (H - 2 * P);
|
||||
const path = k => { let d = '', pen = false; points.forEach((p, i) => { if (p[k] == null) { pen = false; return; } d += `${pen ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[k]).toFixed(1)}`; pen = true; }); return d; };
|
||||
return `<svg class="spark spark-sm" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(t('Uso de la GPU, última hora'))}"><path d="${path('max')}" class="sp-max"/><path d="${path('med')}" class="sp-med"/></svg>`;
|
||||
}
|
||||
|
||||
function gpuCard(gv) {
|
||||
if (!gv || (!gv.gpus.length && gv.state !== 'down' && gv.state !== 'doubt')) {
|
||||
return `<div class="panel eng-card">${cardHead(t('GPU de gpu02'), gv ? `<span class="mono">${esc(gv.url)}</span>` : '', 'unknown')}<div class="empty">${t('Esperando el primer sondeo del exporter.')}</div></div>`;
|
||||
}
|
||||
const down = gv.state === 'down' || gv.state === 'doubt';
|
||||
const vram = gv.vram_low ? `<span class="badge connecting">${t('poca VRAM')}</span>` : '';
|
||||
const first = gv.gpus[0] || {};
|
||||
const rows = gv.gpus.map(g => {
|
||||
const main = g.index === gv.main_index;
|
||||
const free = g.mem_free != null ? g.mem_free / 1048576 : null;
|
||||
const low = main && free != null && free < gv.vram_warn_mib;
|
||||
return `<div class="gpu-row${main ? ' gpu-main' : ''}">
|
||||
<div class="gpu-name"><b>${esc(String(g.name || `GPU ${g.index}`).replace('NVIDIA GeForce ', ''))}</b> <span class="muted small">GPU ${g.index}</span>${main ? ` <span class="chip chip-main">${t('la que usamos')}</span>` : ''}</div>
|
||||
<div class="gpu-role muted small">${esc(gv.roles[g.index] || '—')} <span class="chip chip-decl">${t('declarado')}</span></div>
|
||||
<div class="gpu-nums">
|
||||
<span><span class="muted small">${t('Uso')}</span> ${fmtPct(g.util)}</span>
|
||||
<span class="${low ? 'txt-red' : ''}"><span class="muted small">VRAM</span> ${fmtBytes(g.mem_used)} / ${fmtBytes(g.mem_total)}${free != null ? ` <span class="muted small">(${t('{m} MiB libres', { m: Math.round(free) })})</span>` : ''}</span>
|
||||
<span><span class="muted small">${t('Temp.')}</span> ${g.temp != null ? `${g.temp} °C` : '—'}</span>
|
||||
<span><span class="muted small">${t('Consumo')}</span> ${g.power != null ? `${Math.round(g.power)} W` : '—'}</span>
|
||||
</div>
|
||||
${utilSpark(g.spark)}
|
||||
</div>`;
|
||||
}).join('');
|
||||
return `<div class="panel eng-card">
|
||||
${cardHead(t('GPU de gpu02'), `<span class="mono">${esc(gv.url)}</span>`, gv.state, vram)}
|
||||
${down ? row(t('Caído desde'), `<span class="txt-red">${fmtTime(gv.down_since)}</span> <span class="mono txt-red">${esc(gv.err || '')}</span>`) : ''}
|
||||
${row(t('Driver / CUDA'), first.driver ? `<span class="mono">${esc(first.driver)} / ${esc(first.cuda || '—')}</span>` : '—')}
|
||||
${row(t('Último dato'), gv.last_ok ? `${fmtTime(gv.last_ok)} <span class="muted small">(${fmtAgo(gv.last_ok)})</span>` : '—')}
|
||||
${rows}
|
||||
<p class="field-hint">${t('Uso por minuto de la última hora (mediana y máximo). Aviso si la VRAM libre de la placa resaltada baja de {m} MiB.', { m: gv.vram_warn_mib })}</p>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function hostCard(h) {
|
||||
const v = h.versions || {};
|
||||
const memPct = h.mem.total ? h.mem.used / h.mem.total : null;
|
||||
const diskUsed = h.disk ? h.disk.total - h.disk.free : null;
|
||||
return `<div class="panel eng-card">
|
||||
${cardHead(t('Este equipo'), `<span class="mono">${esc(h.hostname)}</span>`, 'up')}
|
||||
${row('CPU', `${fmtPct(h.cpu)} <span class="muted small">${t('de {n} cores, medido en el cgroup del CT', { n: h.cores })}</span>`)}
|
||||
${row('RAM', `${fmtBytes(h.mem.used)} / ${fmtBytes(h.mem.total)} <span class="muted small">(${fmtPct(memPct)})</span>`)}
|
||||
${row(t('Disco de /var/www/hls'), h.disk ? `${fmtBytes(diskUsed)} / ${fmtBytes(h.disk.total)} <span class="muted small">${t('{b} en HLS', { b: fmtBytes(h.hls_bytes) })}</span>` : '—')}
|
||||
${row(t('Encendido hace'), fmtUptime(h.uptime_s))}
|
||||
${row('OrbiSubs', v.orbisubs ? `<span class="mono">${esc(v.orbisubs)}</span>` : '—')}
|
||||
${row('ffmpeg', `<span class="mono">${esc(v.ffmpeg || '—')}</span>`)}
|
||||
${row('Node', `<span class="mono">${esc(v.node || '—')}</span>`)}
|
||||
${row('srt-live-transmit', `<span class="mono">${esc(v.srt || '—')}</span>`)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderEngines() {
|
||||
const d = enginesData;
|
||||
if (!d) return;
|
||||
$('#engines-sub').textContent = t('Sondeo cada {s} s · último {a}', { s: d.config.poll_s, a: d.polled_at ? fmtTime(d.polled_at) : '—' });
|
||||
const cards = [
|
||||
...d.engines.filter(e => e.kind === 'asr').map(whisperCard),
|
||||
...d.engines.filter(e => e.kind === 'llm').map(llmCard),
|
||||
gpuCard(d.gpu), hostCard(d.host),
|
||||
];
|
||||
$('#engines-cards').innerHTML = cards.join('');
|
||||
}
|
||||
|
||||
/* ---------- configuración ---------- */
|
||||
$('#btn-engines-cfg').onclick = () => {
|
||||
const c = (enginesData && enginesData.config) || {};
|
||||
const f = $('#engines-form');
|
||||
f.asr_model.value = c.asr ? c.asr.model : '';
|
||||
f.asr_hw.value = c.asr ? c.asr.hw : '';
|
||||
f.asr_p95.value = c.asr ? c.asr.p95_warn_s : 3;
|
||||
f.llm_p95.value = c.llm ? c.llm.p95_warn_s : 3;
|
||||
f.poll_s.value = c.poll_s || 20;
|
||||
f.vram_warn.value = c.gpu ? c.gpu.vram_warn_mib : 512;
|
||||
$('#engines-form-error').classList.add('hidden');
|
||||
$('#engines-modal').classList.remove('hidden');
|
||||
};
|
||||
$('#engines-modal-close').onclick = $('#engines-cancel').onclick = () => $('#engines-modal').classList.add('hidden');
|
||||
$('#engines-form').addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const f = e.target;
|
||||
const n = (v, lo, hi) => { const x = Number(v); return Number.isFinite(x) && x >= lo && x <= hi; };
|
||||
let bad = null;
|
||||
if (!n(f.asr_p95.value, 0.5, 60) || !n(f.llm_p95.value, 0.5, 60)) bad = t('Umbral de p95: entre 0,5 y 60 s');
|
||||
else if (!n(f.poll_s.value, 15, 30)) bad = t('Sondeo: entre 15 y 30 s');
|
||||
else if (!n(f.vram_warn.value, 64, 16384)) bad = t('Aviso de VRAM: entre 64 y 16384 MiB');
|
||||
if (bad) { $('#engines-form-error').textContent = bad; $('#engines-form-error').classList.remove('hidden'); return; }
|
||||
try {
|
||||
await api('PUT', '/api/engines/config', {
|
||||
poll_s: Number(f.poll_s.value),
|
||||
asr: { model: f.asr_model.value, hw: f.asr_hw.value, p95_warn_s: Number(f.asr_p95.value) },
|
||||
llm: { p95_warn_s: Number(f.llm_p95.value) },
|
||||
gpu: { vram_warn_mib: Number(f.vram_warn.value) },
|
||||
});
|
||||
$('#engines-modal').classList.add('hidden');
|
||||
loadEngines();
|
||||
} catch (err) { $('#engines-form-error').textContent = err.message; $('#engines-form-error').classList.remove('hidden'); }
|
||||
});
|
||||
window.addEventListener('orbi-lang', () => { if (me && enginesData) renderEngines(); });
|
||||
@@ -170,4 +170,89 @@ OrbiLang.add({ en: {
|
||||
'La passphrase tenía un %-escape inválido; se copió tal cual.': 'The passphrase had an invalid %-escape; it was copied as is.',
|
||||
'La passphrase tiene {n} caracteres; SRT exige entre 10 y 79.': 'The passphrase has {n} characters; SRT requires between 10 and 79.',
|
||||
'Se dejaron en la URL: {list}.': 'Left in the URL: {list}.',
|
||||
// ---- Motores (080) ----
|
||||
"Motores": "Engines",
|
||||
"Configuración": "Settings",
|
||||
"El panel consulta gpu02 desde el servidor (GET /health, /slots, /props, /v1/models y el exporter de GPU en :9835), una sola vez por sondeo aunque haya varias pestañas abiertas. Los tiempos y las fallas son los de los pedidos de los canales, guardados 7 días.": "The panel queries gpu02 from the server (GET /health, /slots, /props, /v1/models and the GPU exporter on :9835), once per poll no matter how many tabs are open. Times and failures come from the channels' own requests, kept for 7 days.",
|
||||
"Configuración de motores": "Engine settings",
|
||||
"whisper.cpp no informa el modelo ni el equipo: estos dos datos se declaran acá y el panel los muestra como declarados.": "whisper.cpp does not report its model or hardware: these two values are declared here and shown as declared.",
|
||||
"Modelo (declarado)": "Model (declared)",
|
||||
"Equipo (declarado)": "Hardware (declared)",
|
||||
"Aviso si el p95 pasa (s)": "Warn when p95 exceeds (s)",
|
||||
"p95 de los últimos 15 min. Con segmentos de 6 s, 3 s deja margen.": "p95 over the last 15 min. With 6 s segments, 3 s leaves headroom.",
|
||||
"Sondeo cada (s)": "Poll every (s)",
|
||||
"Entre 15 y 30 s. Vale para los dos motores.": "Between 15 and 30 s. Applies to both engines.",
|
||||
"Las URL de los motores son las de cada canal (Reconocimiento y Traducción, en el modal del canal).": "Engine URLs are the ones set in each channel (Recognition and Translation, in the channel dialog).",
|
||||
"Guardar": "Save",
|
||||
"hace {n} s": "{n} s ago",
|
||||
"hace {n} min": "{n} min ago",
|
||||
"hace {n} h": "{n} h ago",
|
||||
"hace {n} días": "{n} days ago",
|
||||
"Un motor no responde": "An engine is not responding",
|
||||
"Un motor anda lento o no respondió el último sondeo": "An engine is slow or missed the last poll",
|
||||
"vivo": "up",
|
||||
"caído": "down",
|
||||
"sin respuesta": "no answer",
|
||||
"sin datos": "no data",
|
||||
"sin pedidos en la última hora": "no requests in the last hour",
|
||||
"Tiempo por pedido, última hora": "Time per request, last hour",
|
||||
"mediana por minuto": "median per minute",
|
||||
"máximo": "max",
|
||||
"umbral {s} s": "threshold {s} s",
|
||||
"escala 0–{s}": "scale 0–{s}",
|
||||
"1 h": "1 h",
|
||||
"24 h": "24 h",
|
||||
"Pedidos": "Requests",
|
||||
"Fallas": "Failures",
|
||||
"Mediana": "Median",
|
||||
"RTF (mediana)": "RTF (median)",
|
||||
"Canal (última hora)": "Channel (last hour)",
|
||||
"Caído desde": "Down since",
|
||||
"Error del sondeo": "Poll error",
|
||||
"Último OK": "Last OK",
|
||||
"Responde (1 h)": "Answering (1 h)",
|
||||
"Último error de un pedido": "Last request error",
|
||||
"ninguno guardado": "none stored",
|
||||
"lento": "slow",
|
||||
"p95 de 15 min: {s}": "15-min p95: {s}",
|
||||
"Whisper (reconocimiento)": "Whisper (recognition)",
|
||||
"Modelo": "Model",
|
||||
"whisper.cpp no lo informa: es lo que dice la configuración del panel": "whisper.cpp does not report it: this is what the panel settings say",
|
||||
"declarado": "declared",
|
||||
"Equipo": "Hardware",
|
||||
"leído": "read",
|
||||
"ocupado: {b} de {n} slots": "busy: {b} of {n} slots",
|
||||
"libre ({n} slots)": "idle ({n} slots)",
|
||||
"LLM (traducción)": "LLM (translation)",
|
||||
"Nombre publicado": "Published name",
|
||||
"Versión (build)": "Version (build)",
|
||||
"Ahora": "Now",
|
||||
"Ocupado (1 h, sondeado)": "Busy (1 h, polled)",
|
||||
"de {n} sondeos, incluye a otros usuarios": "of {n} polls, includes other users",
|
||||
"GPU de gpu02": "gpu02 GPU",
|
||||
"Este equipo": "This host",
|
||||
"de {n} cores, medido en el cgroup del CT": "of {n} cores, measured on the CT cgroup",
|
||||
"Disco de /var/www/hls": "/var/www/hls disk",
|
||||
"{b} en HLS": "{b} in HLS",
|
||||
"Encendido hace": "Up for",
|
||||
"Sondeo cada {s} s · último {a}": "Polled every {s} s · last {a}",
|
||||
"Umbral de p95: entre 0,5 y 60 s": "p95 threshold: between 0.5 and 60 s",
|
||||
"Sondeo: entre 15 y 30 s": "Poll: between 15 and 30 s",
|
||||
"Configuración de motores cambiada": "Engine settings changed",
|
||||
"sin muestras en la última hora": "no samples in the last hour",
|
||||
"Uso de la GPU, última hora": "GPU usage, last hour",
|
||||
"Esperando el primer sondeo del exporter.": "Waiting for the first exporter poll.",
|
||||
"poca VRAM": "low VRAM",
|
||||
"la que usamos": "the one we use",
|
||||
"Uso": "Usage",
|
||||
"{m} MiB libres": "{m} MiB free",
|
||||
"Temp.": "Temp.",
|
||||
"Consumo": "Power",
|
||||
"Driver / CUDA": "Driver / CUDA",
|
||||
"Último dato": "Last sample",
|
||||
"Uso por minuto de la última hora (mediana y máximo). Aviso si la VRAM libre de la placa resaltada baja de {m} MiB.": "Usage per minute over the last hour (median and max). Warns when free VRAM on the highlighted card drops below {m} MiB.",
|
||||
"Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso, así que \"ocupado\" puede ser batman y no OrbiSubs.": "Shared: batman (10.100.101.101) also uses this engine through a reverse SSH tunnel, so \"busy\" may be batman rather than OrbiSubs.",
|
||||
"Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso.": "Shared: batman (10.100.101.101) also uses this engine through a reverse SSH tunnel.",
|
||||
"Aviso de VRAM: entre 64 y 16384 MiB": "VRAM warning: between 64 and 16384 MiB",
|
||||
"Aviso si la VRAM libre de la 3060 baja de (MiB)": "Warn when free 3060 VRAM drops below (MiB)",
|
||||
} });
|
||||
|
||||
@@ -61,6 +61,7 @@
|
||||
<nav class="nav" aria-label="Navegación principal" data-i18n="aria-label">
|
||||
<a href="#channels" data-route="channels"><span class="nav-ico">▶</span> <span data-i18n>Canales</span></a>
|
||||
<a href="#events" data-route="events"><span class="nav-ico">≡</span> <span data-i18n>Eventos</span></a>
|
||||
<a href="#engines" data-route="engines"><span class="nav-ico">◎</span> <span data-i18n>Motores</span><span id="nav-engines-dot" class="nav-dot hidden"></span></a>
|
||||
</nav>
|
||||
<div class="sidebar-foot" id="orbi-foot" data-api="/api/system/nodo" data-me="off" data-logo="logo-orbitv.png">
|
||||
<div id="user-box" class="user-box hidden">
|
||||
@@ -112,6 +113,16 @@
|
||||
<div id="events-empty" class="empty hidden" data-i18n>Sin eventos registrados.</div>
|
||||
</div>
|
||||
</section>
|
||||
<!-- ================= MOTORES (tarea 080) ================= -->
|
||||
<section id="view-engines" class="view hidden">
|
||||
<header class="view-head">
|
||||
<h1 data-i18n>Motores</h1>
|
||||
<span class="view-sub" id="engines-sub"></span>
|
||||
<button class="btn" id="btn-engines-cfg" data-i18n>Configuración</button>
|
||||
</header>
|
||||
<div class="eng-grid" id="engines-cards"></div>
|
||||
<p class="hint" data-i18n="html">El panel consulta gpu02 desde el servidor (GET /health, /slots, /props, /v1/models y el exporter de GPU en :9835), una sola vez por sondeo aunque haya varias pestañas abiertas. Los tiempos y las fallas son los de los pedidos de los canales, guardados 7 días.</p>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -264,6 +275,50 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================= MODAL CONFIGURACIÓN DE MOTORES ================= -->
|
||||
<div id="engines-modal" class="modal-backdrop hidden">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="engines-modal-title">
|
||||
<div class="modal-head">
|
||||
<h2 id="engines-modal-title" data-i18n>Configuración de motores</h2>
|
||||
<button class="btn-close" id="engines-modal-close" aria-label="Cerrar" data-i18n="aria-label">✕</button>
|
||||
</div>
|
||||
<form id="engines-form" class="modal-body" novalidate>
|
||||
<fieldset>
|
||||
<legend>Whisper</legend>
|
||||
<p class="field-hint" data-i18n>whisper.cpp no informa el modelo ni el equipo: estos dos datos se declaran acá y el panel los muestra como declarados.</p>
|
||||
<div class="grid-3">
|
||||
<label><span data-i18n>Modelo (declarado)</span> <input name="asr_model" maxlength="80"></label>
|
||||
<label><span data-i18n>Equipo (declarado)</span> <input name="asr_hw" maxlength="80"></label>
|
||||
<label><span data-i18n>Aviso si el p95 pasa (s)</span> <input name="asr_p95" type="number" min="0.5" max="60" step="0.1">
|
||||
<span class="field-hint" data-i18n>p95 de los últimos 15 min. Con segmentos de 6 s, 3 s deja margen.</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>LLM</legend>
|
||||
<div class="grid-3">
|
||||
<label><span data-i18n>Aviso si el p95 pasa (s)</span> <input name="llm_p95" type="number" min="0.5" max="60" step="0.1"></label>
|
||||
<label><span data-i18n>Sondeo cada (s)</span> <input name="poll_s" type="number" min="15" max="30" step="1">
|
||||
<span class="field-hint" data-i18n>Entre 15 y 30 s. Vale para los dos motores.</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>GPU</legend>
|
||||
<div class="grid-3">
|
||||
<label><span data-i18n>Aviso si la VRAM libre de la 3060 baja de (MiB)</span> <input name="vram_warn" type="number" min="64" max="16384" step="64"></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<p class="field-hint" data-i18n>Las URL de los motores son las de cada canal (Reconocimiento y Traducción, en el modal del canal).</p>
|
||||
<div id="engines-form-error" class="form-error hidden"></div>
|
||||
<div class="modal-foot">
|
||||
<button type="button" class="btn" id="engines-cancel" data-i18n>Cancelar</button>
|
||||
<button type="submit" class="btn btn-amber" data-i18n>Guardar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================= MODAL VER CANAL ================= -->
|
||||
<div id="view-modal" class="modal-backdrop hidden">
|
||||
<div class="modal modal-wide" role="dialog" aria-modal="true" aria-labelledby="view-title">
|
||||
@@ -295,6 +350,7 @@
|
||||
<script src="i18n.js"></script>
|
||||
<script src="url-parse.js"></script>
|
||||
<script src="app.js"></script>
|
||||
<script src="engines.js"></script>
|
||||
<script src="node-foot.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -29,3 +29,36 @@ label.inline select{width:auto}
|
||||
.sub-list li:first-child{color:var(--amber)}
|
||||
.notice{white-space:pre-wrap}
|
||||
.notice.err{background:rgba(232,85,85,.12);border-color:var(--red);color:#ffb4b4}
|
||||
/* Pestaña Motores (tarea 080) */
|
||||
.nav-dot{width:8px;height:8px;border-radius:50%;margin-left:auto;display:inline-block}
|
||||
.nav-dot.red{background:var(--red);box-shadow:0 0 6px var(--red)}
|
||||
.nav-dot.amber{background:var(--amber);box-shadow:0 0 6px var(--amber)}
|
||||
.eng-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(420px,1fr));gap:16px;align-items:start}
|
||||
@media (max-width:520px){.eng-grid{grid-template-columns:1fr}}
|
||||
.eng-card{margin-bottom:0}
|
||||
.eng-badges{display:flex;gap:6px;align-items:center}
|
||||
.eng-row{display:flex;justify-content:space-between;gap:12px;padding:5px 0;border-bottom:1px solid var(--border);font-size:13px}
|
||||
.eng-row>span:last-child{text-align:right;min-width:0;word-break:break-word}
|
||||
.eng-tbl{margin:10px 0 4px;font-size:12.5px}
|
||||
.eng-tbl td,.eng-tbl th{padding:4px 8px}
|
||||
.eng-sub{margin-top:12px;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--text-dim)}
|
||||
.spark{width:100%;height:54px;display:block;margin-top:4px;background:var(--surface-2);border-radius:6px}
|
||||
.sp-med{fill:none;stroke:var(--amber);stroke-width:1.6;vector-effect:non-scaling-stroke}
|
||||
.sp-max{fill:none;stroke:var(--text-dim);stroke-width:1;opacity:.55;vector-effect:non-scaling-stroke}
|
||||
.sp-warn{stroke:var(--red);stroke-dasharray:4 3;stroke-width:1;opacity:.7;vector-effect:non-scaling-stroke}
|
||||
.sp-fail{stroke:var(--red);stroke-width:2;opacity:.6;vector-effect:non-scaling-stroke}
|
||||
.spark-legend{display:flex;gap:12px;flex-wrap:wrap;margin-top:3px}
|
||||
.spark-legend .sw{display:inline-block;width:10px;height:2px;vertical-align:middle;margin-right:4px}
|
||||
.sw.med{background:var(--amber)}.sw.max{background:var(--text-dim)}.sw.warn{background:var(--red)}
|
||||
.spark-empty{padding:14px 0;text-align:center}
|
||||
.chip-decl{border-color:var(--amber);color:var(--amber);font-size:10px}
|
||||
.chip-read{border-color:var(--green);color:var(--green);font-size:10px}
|
||||
.txt-red{color:var(--red)}
|
||||
.txt-amber{color:var(--amber)}
|
||||
.eng-tbl .num{text-align:right}
|
||||
.gpu-row{border:1px solid var(--border);border-radius:8px;padding:10px 12px;margin-top:10px}
|
||||
.gpu-row.gpu-main{border-color:var(--amber);background:var(--amber-dim)}
|
||||
.gpu-role{margin:2px 0 6px}
|
||||
.gpu-nums{display:flex;flex-wrap:wrap;gap:6px 18px;font-size:13px}
|
||||
.spark-sm{height:40px}
|
||||
.chip-main{border-color:var(--amber);background:var(--amber);color:#111;font-size:10px;font-weight:700}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
// engines.js — pestaña Motores (tarea 080). Solo lee lo que junta engine/motores.js:
|
||||
// los browsers nunca consultan gpu02.
|
||||
const express = require('express');
|
||||
const { db, event } = require('../db');
|
||||
const motores = require('../engine/motores');
|
||||
|
||||
const router = express.Router();
|
||||
const channels = () => db.prepare('SELECT slug, cfg FROM channels ORDER BY id').all().map(r => ({ slug: r.slug, cfg: JSON.parse(r.cfg) }));
|
||||
|
||||
router.get('/', (req, res) => res.json(motores.view(channels())));
|
||||
// Para el punto rojo/amarillo al lado de "Motores" en el menú: liviano, sin SQL de pedidos.
|
||||
router.get('/alert', (req, res) => res.json({ alert: motores.alert(channels()) }));
|
||||
router.put('/config', (req, res) => {
|
||||
const c = motores.setConfig(req.body || {});
|
||||
event('info', 'Configuración de motores cambiada', { username: req.user && req.user.username });
|
||||
res.json(c);
|
||||
});
|
||||
|
||||
module.exports = { router, channels };
|
||||
@@ -46,6 +46,8 @@ app.get('/api/system/nodo', (req, res) => {
|
||||
});
|
||||
|
||||
app.use('/api/channels', require('./routes/channels'));
|
||||
const engines = require('./routes/engines');
|
||||
app.use('/api/engines', engines.router);
|
||||
app.get('/api/events', (req, res) => {
|
||||
res.json(db.prepare('SELECT * FROM events ORDER BY id DESC LIMIT 200').all());
|
||||
});
|
||||
@@ -59,3 +61,8 @@ app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
|
||||
});
|
||||
|
||||
app.listen(PORT, () => console.log(`[orbisubs-panel] escuchando en :${PORT}`));
|
||||
|
||||
// Sondeo de los motores (tarea 080): uno solo, acá, para todas las pestañas abiertas.
|
||||
const motores = require('./engine/motores');
|
||||
motores.loadVersions().catch(() => {});
|
||||
if (process.env.ENGINES_POLL !== '0') motores.start(engines.channels);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
// Pestaña Motores (080): lectura de las métricas de los canales y los números.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orbisubs-motores-'));
|
||||
process.env.DATA_DIR = tmp;
|
||||
process.env.LOG_DIR = tmp;
|
||||
const M = require('../src/engine/motores');
|
||||
const { db } = require('../src/db');
|
||||
|
||||
test('parseLine: asr con y sin pedido, con error, y líneas viejas sin hora', () => {
|
||||
assert.deepStrictEqual(M.parseLine('asr', { t: 10, http_s: 1.2, audio_s: 7 }), { ts: 10, dur_s: 1.2, audio_s: 7, ok: 1, error: null });
|
||||
assert.strictEqual(M.parseLine('asr', { t: 10, asr_s: 0 }), null); // sin pedido
|
||||
assert.strictEqual(M.parseLine('asr', { http_s: 1.2 }), null); // de antes de la 080
|
||||
assert.strictEqual(M.parseLine('asr', { t: 10, http_s: 0.01, error: 'Connection refused' }).ok, 0);
|
||||
});
|
||||
|
||||
test('parseLine: llm, traducción vacía cuenta como falla', () => {
|
||||
assert.strictEqual(M.parseLine('llm', { t: 1, es: 'hola', en: 'hi', qwen_s: 0.6 }).ok, 1);
|
||||
const f = M.parseLine('llm', { t: 1, es: 'hola', en: null, qwen_s: 8 });
|
||||
assert.strictEqual(f.ok, 0);
|
||||
assert.strictEqual(f.error, 'sin traducción');
|
||||
assert.strictEqual(M.parseLine('llm', { seg: 5, en_lag_vs_es_s: 6 }), null); // línea de lag, no es pedido
|
||||
});
|
||||
|
||||
test('statsOf: mediana, p95 y RTF sobre los pedidos buenos', () => {
|
||||
const rows = [1, 2, 3, 4].map(d => ({ ok: 1, dur_s: d, audio_s: 8 })).concat([{ ok: 0, dur_s: 9 }]);
|
||||
const s = M.statsOf(rows);
|
||||
assert.strictEqual(s.n, 5);
|
||||
assert.strictEqual(s.fails, 1);
|
||||
assert.strictEqual(s.median_s, 2.5);
|
||||
assert.strictEqual(s.p95_s, 3.85);
|
||||
assert.strictEqual(s.rtf, 0.313);
|
||||
});
|
||||
|
||||
test('buckets: 60 minutos, fallas aparte', () => {
|
||||
const now = 10000;
|
||||
const b = M.buckets([{ ts: now - 30, ok: 1, dur_s: 1 }, { ts: now - 20, ok: 0, dur_s: 0 }, { ts: now - 4000, ok: 1, dur_s: 5 }], now);
|
||||
assert.strictEqual(b.length, 60);
|
||||
assert.strictEqual(b[59].med, 1);
|
||||
assert.strictEqual(b[59].fails, 1);
|
||||
assert.strictEqual(b.filter(x => x.n).length, 1);
|
||||
});
|
||||
|
||||
test('engineList: una tarjeta por URL en uso; sin canales, las de gpu02', () => {
|
||||
const ch = (slug, asr, llm, langs = ['en']) => ({ slug, cfg: { asr: { url: asr }, tr: { url: llm, langs } } });
|
||||
const l = M.engineList([ch('a', 'http://g:8004/', 'http://g:8001'), ch('b', 'http://g:8004', 'http://g:8999', [])]);
|
||||
assert.deepStrictEqual(l.map(e => e.key), ['asr|http://g:8004', 'llm|http://g:8001']);
|
||||
assert.deepStrictEqual(l[0].channels, ['a', 'b']);
|
||||
assert.strictEqual(M.engineList([]).length, 2);
|
||||
});
|
||||
|
||||
test('ingestFile: solo lo nuevo, y no relee después de un reinicio', () => {
|
||||
const f = path.join(tmp, 'c1.jsonl');
|
||||
const now = Date.now() / 1000;
|
||||
fs.writeFileSync(f, JSON.stringify({ t: now, http_s: 1, audio_s: 6 }) + '\n' + JSON.stringify({ seq: 1, http_s: 1 }) + '\n');
|
||||
assert.strictEqual(M.ingestFile(f, 'asr', 'http://g:8004', 'c1'), 1);
|
||||
assert.strictEqual(M.ingestFile(f, 'asr', 'http://g:8004', 'c1'), 0);
|
||||
fs.appendFileSync(f, JSON.stringify({ t: now, http_s: 2, audio_s: 6, error: 'x' }) + '\n{"t": ' + now); // la última a medias
|
||||
assert.strictEqual(M.ingestFile(f, 'asr', 'http://g:8004', 'c1'), 1);
|
||||
fs.appendFileSync(f, ', "http_s": 3}\n');
|
||||
assert.strictEqual(M.ingestFile(f, 'asr', 'http://g:8004', 'c1'), 1);
|
||||
assert.strictEqual(db.prepare('SELECT COUNT(*) n FROM engine_reqs').get().n, 3);
|
||||
});
|
||||
|
||||
test('setConfig: valida rangos', () => {
|
||||
assert.throws(() => M.setConfig({ poll_s: 5 }), /entre 15 y 30/);
|
||||
assert.strictEqual(M.setConfig({ asr: { p95_warn_s: 2.5 } }).asr.p95_warn_s, 2.5);
|
||||
assert.strictEqual(M.config().asr.model, 'large-v3-turbo');
|
||||
});
|
||||
|
||||
test('parseProm: una fila por placa, ordenada por índice', () => {
|
||||
const txt = [
|
||||
'nvidia_smi_gpu_info{cuda_version="12.8",driver_version="570.211.01",index="1",name="NVIDIA GeForce RTX 3060",uuid="b"} 1',
|
||||
'nvidia_smi_gpu_info{cuda_version="12.8",driver_version="570.211.01",index="0",name="NVIDIA GeForce RTX 3080",uuid="a"} 1',
|
||||
'nvidia_smi_name{uuid="b"} 3060',
|
||||
'nvidia_smi_index{uuid="b"} 1',
|
||||
'nvidia_smi_memory_free_bytes{uuid="b"} 1.240465408e+09',
|
||||
'nvidia_smi_utilization_gpu_ratio{uuid="b"} 0.99',
|
||||
'nvidia_smi_temperature_gpu{uuid="a"} 56',
|
||||
'# HELP x', 'go_threads 10',
|
||||
].join('\n');
|
||||
const g = M.parseProm(txt);
|
||||
assert.deepStrictEqual(g.map(x => x.index), [0, 1]);
|
||||
assert.strictEqual(g[1].name, 'NVIDIA GeForce RTX 3060');
|
||||
assert.strictEqual(g[1].util, 0.99);
|
||||
assert.strictEqual(g[1].mem_free, 1240465408);
|
||||
assert.strictEqual(g[0].temp, 56);
|
||||
});
|
||||
Reference in New Issue
Block a user