159 lines
7.2 KiB
JavaScript
159 lines
7.2 KiB
JavaScript
'use strict';
|
|
// status.js — estado real de cada canal: lo que dice systemd de sus instancias
|
|
// orbisubs-*@<slug> y lo que escriben los procesos en /var/log/orbisubs (las
|
|
// métricas por segmento de orbisubs.py, orbisubs_tr.py y orbisubs_srt.py).
|
|
// Solo lee: no arranca ni para nada.
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { execFile } = require('child_process');
|
|
|
|
const LOG_DIR = process.env.LOG_DIR || '/var/log/orbisubs';
|
|
const HLS_DIR = process.env.HLS_DIR || '/var/www/hls';
|
|
const STALE_S = 60; // métricas más viejas que esto: el proceso no está produciendo
|
|
|
|
function sh(cmd, args, timeout = 5000) {
|
|
return new Promise(resolve => {
|
|
execFile(cmd, args, { timeout, maxBuffer: 4 << 20 }, (err, stdout) => resolve(err && !stdout ? '' : String(stdout)));
|
|
});
|
|
}
|
|
|
|
// Instancias systemd que forman el canal, según su configuración.
|
|
function unitsOf(ch) {
|
|
const u = ['ingest', 'asr'];
|
|
if (ch.cfg.tr && ch.cfg.tr.langs && ch.cfg.tr.langs.length) u.push('tr');
|
|
if (ch.cfg.srt && ch.cfg.srt.enabled) u.push('srt');
|
|
return u.map(k => ({ key: k, unit: `orbisubs-${k}@${ch.slug}.service` }));
|
|
}
|
|
|
|
// Un solo `systemctl show` para todas las unidades de todos los canales.
|
|
async function systemdState(units) {
|
|
if (!units.length) return {};
|
|
const out = await sh('systemctl', ['show', '--no-pager', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState', ...units]);
|
|
const res = {};
|
|
for (const block of out.split(/\n\s*\n/)) {
|
|
const o = {};
|
|
for (const line of block.split('\n')) {
|
|
const i = line.indexOf('=');
|
|
if (i > 0) o[line.slice(0, i)] = line.slice(i + 1);
|
|
}
|
|
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState };
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// Últimas líneas JSON de un .jsonl, leyendo solo la cola del archivo.
|
|
function tailJsonl(file, maxBytes = 256 * 1024) {
|
|
let fd;
|
|
try {
|
|
fd = fs.openSync(file, 'r');
|
|
const st = fs.fstatSync(fd);
|
|
const len = Math.min(st.size, maxBytes);
|
|
const buf = Buffer.alloc(len);
|
|
fs.readSync(fd, buf, 0, len, st.size - len);
|
|
const lines = buf.toString('utf8').split('\n');
|
|
if (st.size > len) lines.shift(); // la primera puede venir cortada
|
|
const rows = [];
|
|
for (const l of lines) { if (l.trim()) { try { rows.push(JSON.parse(l)); } catch { /* línea a medias */ } } }
|
|
return { rows, mtime: st.mtimeMs };
|
|
} catch { return { rows: [], mtime: 0 }; }
|
|
finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
}
|
|
|
|
const median = a => {
|
|
if (!a.length) return null;
|
|
const s = [...a].sort((x, y) => x - y), m = s.length >> 1;
|
|
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
};
|
|
const round = (v, d = 2) => (v == null ? null : Math.round(v * 10 ** d) / 10 ** d);
|
|
|
|
function metrics(ch, { last = 1 } = {}) {
|
|
const now = Date.now();
|
|
const asr = tailJsonl(path.join(LOG_DIR, `${ch.slug}.jsonl`));
|
|
const segs = asr.rows.filter(r => r.seq != null && r.dur != null);
|
|
const lastSeg = segs[segs.length - 1];
|
|
const fresh = asr.mtime && now - asr.mtime < STALE_S * 1000;
|
|
const m = {
|
|
fresh: !!fresh,
|
|
age_s: asr.mtime ? Math.round((now - asr.mtime) / 1000) : null,
|
|
delay_s: fresh && lastSeg ? lastSeg.channel_extra_s : null,
|
|
held_segments: fresh && lastSeg ? lastSeg.held_segments : null,
|
|
pending_s: fresh && lastSeg ? lastSeg.pending_s : null,
|
|
last: {},
|
|
recent: {},
|
|
};
|
|
const conTexto = segs.filter(r => r.text);
|
|
if (conTexto.length) m.last[ch.cfg.asr.lang] = conTexto[conTexto.length - 1].text.replace(/ \| /g, ' ');
|
|
m.recent[ch.cfg.asr.lang] = conTexto.slice(-last).map(r => ({ seq: r.seq, text: r.text.replace(/ \| /g, ' ') }));
|
|
// Pedidos al motor de reconocimiento (gpu02 :8004): los últimos 100 segmentos.
|
|
const asrT = segs.slice(-100).map(r => r.http_s ?? r.asr_s).filter(v => typeof v === 'number');
|
|
m.asr = { n: asrT.length, median_s: round(median(asrT)) };
|
|
|
|
if (ch.cfg.tr.langs.length) {
|
|
const tr = tailJsonl(path.join(LOG_DIR, `${ch.slug}-en.jsonl`));
|
|
const frases = tr.rows.filter(r => 'en' in r);
|
|
const lags = tr.rows.filter(r => r.en_lag_vs_es_s != null).slice(-100).map(r => r.en_lag_vs_es_s);
|
|
const okT = frases.slice(-100).map(r => r.qwen_s).filter(v => typeof v === 'number');
|
|
const conEn = frases.filter(r => r.en);
|
|
if (conEn.length) m.last.en = conEn[conEn.length - 1].en;
|
|
m.recent.en = conEn.slice(-last).map(r => ({ text: r.en, es: r.es }));
|
|
m.tr = { n: okT.length, median_s: round(median(okT)), lag_median_s: round(median(lags)), fresh: !!(tr.mtime && now - tr.mtime < STALE_S * 1000) };
|
|
}
|
|
|
|
if (ch.cfg.srt.enabled) {
|
|
const s = tailJsonl(path.join(LOG_DIR, `${ch.slug}-srt.jsonl`), 64 * 1024);
|
|
const r = s.rows[s.rows.length - 1];
|
|
if (r) {
|
|
const pick = k => (r[k] ? { cues: r[k].cues, tarde: r[k].tarde, perdidos: r[k].perdidos, tarde_max_s: r[k].tarde_max_s ?? null } : null);
|
|
m.srt = {
|
|
fresh: !!(s.mtime && now - s.mtime < STALE_S * 1000),
|
|
delay_s: r.retraso_fijo_s, send_lag_s: r.atraso_envio_s,
|
|
es608: pick('es608'), en608: pick('en608'), es708: pick('es708'), en708: pick('en708'),
|
|
};
|
|
}
|
|
}
|
|
return m;
|
|
}
|
|
|
|
// Fallas de los pedidos a gpu02 en la última hora, contadas en el journal
|
|
// (orbisubs.py escribe asr_error y orbisubs_tr.py translate_error).
|
|
async function failures(ch) {
|
|
const count = async (unit, word) => {
|
|
const out = await sh('journalctl', ['-u', unit, '--since', '-1h', '-o', 'cat', '--no-pager', '-q'], 8000);
|
|
return out.split('\n').filter(l => l.includes(`"${word}"`)).length;
|
|
};
|
|
const r = { asr_errors_1h: await count(`orbisubs-asr@${ch.slug}.service`, 'asr_error') };
|
|
if (ch.cfg.tr.langs.length) r.tr_errors_1h = await count(`orbisubs-tr@${ch.slug}.service`, 'translate_error');
|
|
return r;
|
|
}
|
|
|
|
// Resume las unidades en un estado del canal: corriendo, parado, error, arrancando.
|
|
function summarize(ch, sd) {
|
|
const units = unitsOf(ch).map(u => ({ ...u, ...(sd[u.unit] || { load: 'not-found', active: 'inactive' }) }));
|
|
const act = units.map(u => u.active);
|
|
let state;
|
|
if (act.every(a => a === 'active')) state = 'running';
|
|
else if (act.some(a => a === 'failed')) state = 'error';
|
|
else if (act.every(a => a === 'inactive')) state = 'stopped';
|
|
else if (act.some(a => a === 'activating' || a === 'reloading')) state = 'connecting';
|
|
else state = 'error'; // a medias: algunas andan y otras no
|
|
const notes = units.filter(u => u.active !== 'active' && state !== 'stopped').map(u => `${u.key}: ${u.active}${u.result && u.result !== 'success' ? ` (${u.result})` : ''}`);
|
|
return { state, units, notes, managed: units.some(u => u.load === 'loaded') };
|
|
}
|
|
|
|
async function all(channels) {
|
|
const sd = await systemdState(channels.flatMap(ch => unitsOf(ch).map(u => u.unit)));
|
|
const res = {};
|
|
for (const ch of channels) {
|
|
const s = summarize(ch, sd);
|
|
const m = metrics(ch);
|
|
// Corriendo según systemd pero sin producir subtítulos: se muestra como error.
|
|
if (s.state === 'running' && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
|
|
s.state = 'error'; s.notes.push(`sin subtítulos nuevos hace ${m.age_s} s`);
|
|
}
|
|
res[ch.id] = { ...s, metrics: m };
|
|
}
|
|
return res;
|
|
}
|
|
|
|
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, LOG_DIR, HLS_DIR };
|