Files
orbisubs/panel/src/engine/motores.js
T
guy 43055e44b7 OrbiSubs: each metrics line carries the engine URL it used, so failures land on the right card
En la prueba de caída de la 080, las fallas de :8999 se leyeron después de volver a :8001 y quedaron contadas en la tarjeta de :8001. Ahora orbisubs.py y orbisubs_tr.py escriben la url, y el panel usa la del canal solo para las líneas viejas.
2026-11-17 01:09:15 -03:00

485 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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, url: r.url ? normUrl(r.url) : 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, url: r.url ? normUrl(r.url) : 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;
// La URL que escribió el proceso; si no la trae (líneas viejas), la del canal ahora.
insReq.run(q.ts, kind, q.url || 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,
};