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 };
|
||||
@@ -9,7 +9,8 @@
|
||||
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
|
||||
// Puertos del CT que no puede tomar ningún canal (ssh, smtp local, nginx, este panel).
|
||||
const RESERVED = new Set([22, 25, 80, 443, Number(process.env.PORT) || 4700]);
|
||||
const CC608 = ['CC1', 'CC2', 'CC3', 'CC4'];
|
||||
// El codificador de la 078 escribe CC1 (campo 1) y CC3 (campo 2); CC2/CC4 no.
|
||||
const CC608 = ['CC1', 'CC3'];
|
||||
const LANGS = ['es', 'en', 'pt'];
|
||||
|
||||
class ValidationError extends Error {
|
||||
@@ -47,6 +48,8 @@ function host(v, field, label) {
|
||||
function passphrase(v, field) {
|
||||
const s = str(v);
|
||||
if (s && (s.length < 10 || s.length > 79)) bad('La passphrase SRT tiene que tener entre 10 y 79 caracteres', field);
|
||||
// Va en una URL y en la línea de comando del servicio: sin espacios ni caracteres de URL.
|
||||
if (s && !/^[A-Za-z0-9._~!*+,;:@%-]+$/.test(s)) bad('La passphrase SRT no puede tener espacios, comillas, &, ?, # ni /', field);
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -63,7 +66,7 @@ function input(i = {}) {
|
||||
passphrase: passphrase(i.passphrase, 'in_passphrase'),
|
||||
};
|
||||
if (out.streamid.length > 512 || /[\s&]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid');
|
||||
if (mode === 'listener' && RESERVED.has(out.port)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port');
|
||||
if (mode === 'listener' && (RESERVED.has(out.port) || out.port < 1024)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port');
|
||||
return Object.assign(out, avPick(i));
|
||||
}
|
||||
if (kind === 'udp') {
|
||||
@@ -121,18 +124,22 @@ function channel(body = {}) {
|
||||
},
|
||||
srt: { enabled: !!srt.enabled },
|
||||
};
|
||||
if (cfg.tr.langs.length && cfg.asr.lang === 'en') bad('El audio ya es inglés: no hace falta traducir a inglés', 'tr_langs');
|
||||
// El traductor (orbisubs_tr.py) está armado para español de Chile → inglés.
|
||||
if (cfg.tr.langs.length && cfg.asr.lang !== 'es') bad('Por ahora la traducción es solo de español a inglés', 'tr_en');
|
||||
|
||||
if (cfg.srt.enabled) {
|
||||
const mode = str(srt.mode) === 'caller' ? 'caller' : 'listener';
|
||||
Object.assign(cfg.srt, {
|
||||
mode,
|
||||
host: mode === 'caller' ? host(srt.host, 'srt_host', 'Destino de la salida SRT') : '',
|
||||
port: int(srt.port, 'srt_port', 1024, 65534, 'Puerto de la salida SRT'),
|
||||
// Hasta 55000: los UDP internos hacia srt-live-transmit van en puerto + 10000.
|
||||
port: int(srt.port, 'srt_port', 1024, 55000, 'Puerto de la salida SRT'),
|
||||
latency_ms: int(srt.latency_ms === '' || srt.latency_ms == null ? 200 : srt.latency_ms, 'srt_latency', 20, 8000, 'Latency de la salida (ms)'),
|
||||
passphrase: passphrase(srt.passphrase, 'srt_passphrase'),
|
||||
delay_s: num(srt.delay_s ?? 24, 'srt_delay', 5, 60, 'Retraso fijo del video (s)'),
|
||||
cc608: {}, cc708: {},
|
||||
// HLS de prueba con -c copy desde la salida SRT (/hls/<id>-cc/, como OrbiOrigin; 078).
|
||||
test: !!srt.test,
|
||||
});
|
||||
// Qué idioma va en cada canal 608 y servicio 708. Vacío = ese idioma no va.
|
||||
const langsOut = [cfg.asr.lang, ...cfg.tr.langs];
|
||||
@@ -140,7 +147,7 @@ function channel(body = {}) {
|
||||
for (const l of langsOut) {
|
||||
const v608 = str((srt.cc608 || {})[l]);
|
||||
if (v608) {
|
||||
if (!CC608.includes(v608)) bad(`608 de ${l}: CC1 a CC4`, 'srt_cc608');
|
||||
if (!CC608.includes(v608)) bad(`608 de ${l}: CC1 o CC3`, 'srt_cc608');
|
||||
if (used608.has(v608)) bad(`${v608} está repetido entre idiomas`, 'srt_cc608');
|
||||
used608.add(v608); cfg.srt.cc608[l] = v608;
|
||||
}
|
||||
@@ -167,6 +174,9 @@ function portsOf(cfg) {
|
||||
if (cfg.srt && cfg.srt.enabled && cfg.srt.mode === 'listener') {
|
||||
out.push({ port: cfg.srt.port, what: 'salida SRT' }, { port: cfg.srt.port + 1, what: 'prueba interna de la salida SRT' });
|
||||
}
|
||||
if (cfg.srt && cfg.srt.enabled) {
|
||||
out.push({ port: cfg.srt.port + 10000, what: 'UDP interno de la salida SRT' }, { port: cfg.srt.port + 10001, what: 'UDP interno de la salida SRT' });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user