OrbiSubs panel: start/stop via systemd, per-channel SRT output, T13 as a panel channel
El panel genera /etc/orbisubs/<id>.env, arranca o para las instancias y mira 12 s que queden andando; si no, vuelve a lo anterior. Salida SRT por canal (listener o caller, latency, passphrase, CC1/CC3 y servicios 708, UDP internos puerto+10000). Ingesta numerada con la hora: al reiniciar, la secuencia volvía a 0 y el ASR se trababa. Tope de 2 canales andando (gpu02) y throttle de arranques. Tarea 079.
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
'use strict';
|
||||
// apply.js — lleva un canal del panel a las instancias systemd que ya existen
|
||||
// (orbisubs-ingest@, -asr@, -tr@, -srt@, -srthls@): escribe /etc/orbisubs/<id>.env
|
||||
// y las arranca o las para. Si algo no arranca, vuelve al .env anterior y lo dice:
|
||||
// guardar no deja un canal a medias.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execFile } = require('child_process');
|
||||
const status = require('./status');
|
||||
|
||||
const ETC = process.env.ORBISUBS_ETC || '/etc/orbisubs';
|
||||
const CHECK_S = Number(process.env.APPLY_CHECK_S || 12); // cuánto mirar después de arrancar
|
||||
|
||||
function sh(cmd, args, timeout = 30000) {
|
||||
return new Promise(resolve => {
|
||||
execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({ ok: !err, out: String(stdout || ''), err: String(stderr || (err && err.message) || '') }));
|
||||
});
|
||||
}
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
// URL de entrada para ffmpeg. Ojo: en ffmpeg la latency de SRT va en MICROsegundos
|
||||
// (el mismo error que url-parse.js documenta para OrbiStream: 2000 → 2 ms).
|
||||
function inputUrl(i) {
|
||||
if (i.kind !== 'srt') return i.url;
|
||||
const q = [`mode=${i.mode}`, `latency=${i.latency_ms * 1000}`];
|
||||
if (i.streamid) q.push(`streamid=${encodeURIComponent(i.streamid)}`);
|
||||
if (i.passphrase) q.push(`passphrase=${encodeURIComponent(i.passphrase)}`);
|
||||
return `srt://${i.mode === 'listener' ? '0.0.0.0' : i.host}:${i.port}?${q.join('&')}`;
|
||||
}
|
||||
|
||||
const q = v => `"${String(v).replace(/[\\"]/g, '\\$&')}"`;
|
||||
|
||||
function envText(ch) {
|
||||
const c = ch.cfg;
|
||||
const asrExtra = [`--lang ${c.asr.lang}`, `--window ${c.hls.list_size}`];
|
||||
if (c.tr.langs.includes('en')) asrExtra.unshift('--en');
|
||||
const lines = [
|
||||
`# /etc/orbisubs/${ch.slug}.env — lo genera el panel de OrbiSubs (${new Date().toISOString()}).`,
|
||||
'# No editar a mano: se pisa cada vez que se guarda o se inicia el canal desde el panel.',
|
||||
`INPUT=${q(inputUrl(c.input))}`,
|
||||
`HLS_TIME=${c.hls.seg_s}`,
|
||||
`MAP_VIDEO=${c.input.program ? `0:p:${c.input.program}:v` : '0:v:0'}`,
|
||||
`MAP_AUDIO=${c.input.audio_pid ? `0:i:${c.input.audio_pid}` : (c.input.program ? `0:p:${c.input.program}:a` : '0:a:0')}`,
|
||||
'ENGINE=http',
|
||||
`URL=${q(c.asr.url)}`,
|
||||
// Solo los usa engine=local (faster-whisper); el ExecStart del asr los pide igual.
|
||||
'MODEL=small', 'DEVICE=cpu', 'COMPUTE=int8', 'THREADS=4', 'BEAM=1',
|
||||
`ASR_EXTRA=${q(asrExtra.join(' '))}`,
|
||||
`ASR_PROMPT=${q(c.asr.prompt || '')}`,
|
||||
`LLM_URL=${q(c.tr.url)}`,
|
||||
`LLM_MODEL=${q(c.tr.model || 'qwen2.5-7b-instruct')}`,
|
||||
];
|
||||
if (c.srt.enabled) {
|
||||
const s = c.srt;
|
||||
const extra = [`--mode ${s.mode}`, `--latency ${s.latency_ms}`,
|
||||
`--cc608-main ${s.cc608[c.asr.lang] || '-'}`, `--cc608-en ${s.cc608.en || '-'}`,
|
||||
`--svc-main ${s.cc708[c.asr.lang] || 0}`, `--svc-en ${s.cc708.en || 0}`];
|
||||
if (s.mode === 'caller') extra.push(`--host ${s.host}`);
|
||||
if (s.passphrase) extra.push(`--passphrase ${s.passphrase}`);
|
||||
lines.push(`SRT_DELAY=${s.delay_s}`, `SRT_PORT=${s.port}`,
|
||||
`SRT_PORT_TEST=${s.mode === 'listener' && s.test ? s.port + 1 : 0}`, `SRT_EXTRA=${q(extra.join(' '))}`);
|
||||
}
|
||||
return lines.join('\n') + '\n';
|
||||
}
|
||||
|
||||
// Instancias que el canal tiene que tener andando según su configuración.
|
||||
function wanted(ch) {
|
||||
const u = status.unitsOf(ch).map(x => x.unit);
|
||||
if (ch.cfg.srt.enabled && ch.cfg.srt.mode === 'listener' && ch.cfg.srt.test) u.push(`orbisubs-srthls@${ch.slug}.service`);
|
||||
return u;
|
||||
}
|
||||
const ALL_KINDS = ['ingest', 'asr', 'tr', 'srt', 'srthls'];
|
||||
const allUnits = slug => ALL_KINDS.map(k => `orbisubs-${k}@${slug}.service`);
|
||||
|
||||
function writeEnv(slug, text) {
|
||||
const file = path.join(ETC, `${slug}.env`);
|
||||
fs.mkdirSync(ETC, { recursive: true });
|
||||
let prev = null;
|
||||
try { prev = fs.readFileSync(file, 'utf8'); } catch { /* canal nuevo */ }
|
||||
// Un .env armado a mano (T13 de la 076-078) se guarda la primera vez que lo pisa el panel.
|
||||
if (prev !== null && !prev.includes('lo genera el panel') && !fs.existsSync(`${file}.antes-panel`)) {
|
||||
fs.writeFileSync(`${file}.antes-panel`, prev, { mode: 0o640 });
|
||||
}
|
||||
const tmp = `${file}.tmp-${process.pid}`;
|
||||
fs.writeFileSync(tmp, text, { mode: 0o640 });
|
||||
fs.renameSync(tmp, file); // atómico: un servicio que arranca justo nunca lee medio archivo
|
||||
return prev;
|
||||
}
|
||||
function restoreEnv(slug, prev) {
|
||||
const file = path.join(ETC, `${slug}.env`);
|
||||
if (prev === null) { try { fs.unlinkSync(file); } catch { /* ya no está */ } return; }
|
||||
fs.writeFileSync(`${file}.tmp-${process.pid}`, prev, { mode: 0o640 });
|
||||
fs.renameSync(`${file}.tmp-${process.pid}`, file);
|
||||
}
|
||||
|
||||
// Lo último que dijo el proceso (no systemd: "Started…", "Scheduled restart…" no explican nada).
|
||||
async function journalTail(unit) {
|
||||
const r = await sh('journalctl', ['-u', unit, '-n', '30', '-o', 'json', '--no-pager', '-q']);
|
||||
const lines = [];
|
||||
for (const l of r.out.split('\n')) {
|
||||
try { const j = JSON.parse(l); if (j._PID !== '1' && j.MESSAGE) lines.push(String(j.MESSAGE)); } catch { /* línea vacía */ }
|
||||
}
|
||||
return (lines.slice(-2).join(' | ') || 'sin mensajes del proceso').slice(0, 400);
|
||||
}
|
||||
|
||||
// Mira las instancias unos segundos: tienen que quedar activas y sin reinicios nuevos.
|
||||
async function verify(units) {
|
||||
const before = await status.systemdState(units);
|
||||
const deadline = Date.now() + CHECK_S * 1000;
|
||||
let st = before;
|
||||
while (Date.now() < deadline) {
|
||||
await sleep(1500);
|
||||
st = await status.systemdState(units);
|
||||
const bad = units.filter(u => st[u] && (st[u].active === 'failed' || st[u].restarts > (before[u] ? before[u].restarts : 0)));
|
||||
if (bad.length) break;
|
||||
}
|
||||
const errors = [];
|
||||
for (const u of units) {
|
||||
const s = st[u] || {};
|
||||
const restarted = s.restarts > (before[u] ? before[u].restarts : 0);
|
||||
if (s.active !== 'active' || restarted) {
|
||||
errors.push(`${u.replace(/\.service$/, '')}: ${s.active || '?'}${s.result && s.result !== 'success' ? ` (${s.result})` : ''}${restarted ? ', se reinició' : ''} — ${await journalTail(u)}`);
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
async function stopUnits(units) {
|
||||
if (!units.length) return;
|
||||
await sh('systemctl', ['disable', '--now', ...units], 60000);
|
||||
await sh('systemctl', ['reset-failed', ...units]);
|
||||
}
|
||||
|
||||
// Arranca (o re-aplica) el canal. Devuelve {ok, errors}.
|
||||
async function start(ch, { prevCh = null } = {}) {
|
||||
const units = wanted(ch);
|
||||
const extra = allUnits(ch.slug).filter(u => !units.includes(u));
|
||||
const prev = writeEnv(ch.slug, envText(ch));
|
||||
await stopUnits(extra); // p. ej. se apagó la traducción
|
||||
await sh('systemctl', ['reset-failed', ...units]);
|
||||
// restart (no start): si ya andaba, toma el .env nuevo.
|
||||
const r = await sh('systemctl', ['restart', ...units], 60000);
|
||||
if (ch.enabled) await sh('systemctl', ['enable', ...units]);
|
||||
let errors = r.ok ? await verify(units) : [`systemctl restart: ${r.err.trim().slice(0, 300)}`];
|
||||
if (!errors.length) return { ok: true, errors: [] };
|
||||
// No quedó andando: se vuelve a lo anterior para no dejarlo a medias.
|
||||
if (prevCh && prev !== null) {
|
||||
restoreEnv(ch.slug, prev);
|
||||
const pu = wanted(prevCh);
|
||||
await stopUnits(allUnits(ch.slug).filter(u => !pu.includes(u)));
|
||||
await sh('systemctl', ['reset-failed', ...pu]);
|
||||
await sh('systemctl', ['restart', ...pu], 60000);
|
||||
errors.push('Se volvió a la configuración anterior del canal.');
|
||||
} else {
|
||||
await stopUnits(allUnits(ch.slug));
|
||||
restoreEnv(ch.slug, prev);
|
||||
errors.push('El canal quedó parado.');
|
||||
}
|
||||
return { ok: false, errors };
|
||||
}
|
||||
|
||||
async function stop(ch) {
|
||||
await stopUnits(allUnits(ch.slug));
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
function removeEnv(slug) {
|
||||
try { fs.unlinkSync(path.join(ETC, `${slug}.env`)); } catch { /* no estaba */ }
|
||||
}
|
||||
|
||||
module.exports = { start, stop, envText, inputUrl, wanted, allUnits, removeEnv };
|
||||
Reference in New Issue
Block a user