209 lines
9.3 KiB
JavaScript
Executable File
209 lines
9.3 KiB
JavaScript
Executable File
const { spawn } = require('node:child_process');
|
|
const path = require('node:path');
|
|
const { config } = require('../lib/config');
|
|
const { getDb } = require('../lib/mongo');
|
|
|
|
const WORKER_SEQUENCE_ID = 'worker-name-sequence';
|
|
const QUERY_TIMEOUT_MS = 5000;
|
|
|
|
function runPm2Command(args) {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn('pm2', args, { cwd: config.projectRoot, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
let stdout = '';
|
|
let stderr = '';
|
|
let settled = false;
|
|
function finish(error, code) {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(timer);
|
|
if (error) reject(error);
|
|
else resolve({ code, stdout, stderr });
|
|
}
|
|
const timer = setTimeout(() => {
|
|
child.kill();
|
|
finish(new Error('PM2 did not respond in time.'));
|
|
}, 10000);
|
|
for (const [stream, field] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']]) {
|
|
stream.on('data', (data) => {
|
|
if (field === 'stdout') stdout += data.toString();
|
|
else stderr += data.toString();
|
|
if (stdout.length + stderr.length > 1024 * 1024) {
|
|
child.kill();
|
|
finish(new Error('PM2 response exceeded the supported size.'));
|
|
}
|
|
});
|
|
}
|
|
child.on('error', () => finish(new Error('PM2 is unavailable for this account.')));
|
|
child.on('close', (code) => finish(null, code));
|
|
});
|
|
}
|
|
|
|
function humanUptime(timestamp) {
|
|
if (!timestamp || timestamp <= 0) return '—';
|
|
const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000));
|
|
const days = Math.floor(seconds / 86400);
|
|
const hours = Math.floor((seconds % 86400) / 3600);
|
|
const minutes = Math.floor((seconds % 3600) / 60);
|
|
return [days && `${days}d`, hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' ') || `${seconds % 60}s`;
|
|
}
|
|
|
|
function normalizeProcess(process) {
|
|
const env = process.pm2_env || {};
|
|
const cpu = process.monit?.cpu;
|
|
const memory = process.monit?.memory;
|
|
const startedAt = typeof env.pm_uptime === 'number' && Number.isFinite(env.pm_uptime) && env.pm_uptime > 0
|
|
? new Date(env.pm_uptime) : null;
|
|
return {
|
|
name: String(process.name || env.name || '—'),
|
|
pid: process.pid || '—',
|
|
pm_id: String(process.pm_id ?? env.pm_id ?? '—'),
|
|
status: String(env.status || process.status || 'unknown'),
|
|
cpu: typeof cpu === 'number' ? `${cpu.toFixed(1)}%` : '—',
|
|
memoryMB: typeof memory === 'number' ? `${Math.round(memory / 1024 / 1024)} MB` : '—',
|
|
uptime: humanUptime(env.pm_uptime),
|
|
startedAtISO: startedAt && Number.isFinite(startedAt.getTime()) ? startedAt.toISOString() : null,
|
|
execPath: env.pm_exec_path || '—',
|
|
};
|
|
}
|
|
|
|
function validName(name) {
|
|
return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all';
|
|
}
|
|
|
|
function createPm2Controller({ run = runPm2Command, settings = config, getDb: connect = getDb } = {}) {
|
|
function managed(process) {
|
|
const executable = process.pm2_env?.pm_exec_path;
|
|
return typeof executable === 'string' && path.resolve(executable) === settings.workerScript;
|
|
}
|
|
|
|
async function processes() {
|
|
const response = await run(['jlist']);
|
|
if (response.code !== 0) throw new Error('PM2 process list is unavailable.');
|
|
let parsed;
|
|
try { parsed = JSON.parse(response.stdout); } catch { throw new Error('PM2 returned an invalid process list.'); }
|
|
if (!Array.isArray(parsed)) throw new Error('PM2 returned an invalid process list.');
|
|
return parsed;
|
|
}
|
|
|
|
async function resolveManagedProcess(name) {
|
|
if (!validName(name)) return null;
|
|
const matches = (await processes()).filter((process) => managed(process) && (process.name || process.pm2_env?.name) === name);
|
|
if (matches.length !== 1) return null;
|
|
const id = matches[0].pm_id ?? matches[0].pm2_env?.pm_id;
|
|
if (!Number.isInteger(id) || id < 0) return null;
|
|
return { ...normalizeProcess(matches[0]), pm_id: String(id) };
|
|
}
|
|
|
|
async function listManagedProcesses() {
|
|
return (await processes()).filter(managed).map(normalizeProcess);
|
|
}
|
|
|
|
function createArguments(name) {
|
|
return ['start', settings.workerScript, '--name', name, '--cwd', settings.projectRoot,
|
|
'--interpreter', process.execPath, '--kill-timeout', '10000'];
|
|
}
|
|
|
|
async function reserveWorkerName(existing) {
|
|
let highest = 0;
|
|
for (const worker of existing) {
|
|
const match = /^proxer-worker-(\d+)$/.exec(worker.name || worker.pm2_env?.name || '');
|
|
if (!match) continue;
|
|
const number = Number(match[1]);
|
|
if (!Number.isSafeInteger(number) || number >= Number.MAX_SAFE_INTEGER) return null;
|
|
highest = Math.max(highest, number);
|
|
}
|
|
const collection = (await connect()).collection('settings');
|
|
const seed = { $max: { value: highest } };
|
|
let seeded;
|
|
try {
|
|
seeded = await collection.updateOne({ _id: WORKER_SEQUENCE_ID }, seed, { upsert: true, maxTimeMS: QUERY_TIMEOUT_MS });
|
|
} catch (error) {
|
|
// Two first requests can race to create the sequence. The _id index
|
|
// selects one winner; the other request can safely seed that same row.
|
|
if (error?.code !== 11000) throw error;
|
|
seeded = await collection.updateOne({ _id: WORKER_SEQUENCE_ID }, seed, { maxTimeMS: QUERY_TIMEOUT_MS });
|
|
}
|
|
if (seeded?.acknowledged !== true) throw new Error('Worker number could not be reserved.');
|
|
const reserved = await collection.findOneAndUpdate({
|
|
_id: WORKER_SEQUENCE_ID, value: { $gte: 0, $lt: Number.MAX_SAFE_INTEGER },
|
|
}, { $inc: { value: 1 } }, {
|
|
returnDocument: 'after', includeResultMetadata: false, projection: { value: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
|
|
});
|
|
if (!reserved || !Number.isSafeInteger(reserved.value) || reserved.value < 1) return null;
|
|
return `proxer-worker-${reserved.value}`;
|
|
}
|
|
|
|
async function quickAdd(req, res) {
|
|
if (req.body && (typeof req.body !== 'object' || Array.isArray(req.body) || Object.keys(req.body).length)) {
|
|
return res.status(400).json({ ok: false, error: 'Quick add chooses the worker name and executable automatically.' });
|
|
}
|
|
let name;
|
|
try {
|
|
// Inspect every process, including unrelated services, before reserving
|
|
// a persistent number. Deleting a worker never reuses its number.
|
|
name = await reserveWorkerName(await processes());
|
|
if (!name) return res.status(409).json({ ok: false, error: 'A numbered worker name could not be reserved. Use a custom worker name or check the saved worker counter.' });
|
|
} catch {
|
|
return res.status(503).json({ ok: false, error: 'Quick add requires the worker supervisor and database to be available. Try again after checking the service.' });
|
|
}
|
|
try {
|
|
const { code } = await run(createArguments(name));
|
|
return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code, name,
|
|
message: code === 0 ? `${name} was created and started.` : `Could not start ${name}. Check the worker list and supervisor before trying again.` });
|
|
} catch {
|
|
return res.status(503).json({ ok: false, name,
|
|
error: `Could not confirm whether ${name} started. Refresh the worker list before trying again.` });
|
|
}
|
|
}
|
|
|
|
async function getManage(req, res, next) {
|
|
try {
|
|
res.render('pm2', { title: 'Proxer Workers', processes: await listManagedProcesses() });
|
|
} catch (error) { next(error); }
|
|
}
|
|
|
|
async function listJson(req, res) {
|
|
try {
|
|
res.json({ ok: true, processes: await listManagedProcesses() });
|
|
} catch {
|
|
res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' });
|
|
}
|
|
}
|
|
|
|
async function postCommand(req, res) {
|
|
const { cmd, name, scriptPath } = req.body || {};
|
|
if (!['start', 'stop', 'restart', 'delete', 'save', 'create'].includes(cmd)) {
|
|
return res.status(400).json({ ok: false, error: 'Invalid command.' });
|
|
}
|
|
if (cmd === 'save') {
|
|
return res.status(409).json({ ok: false, error: 'Saving the full PM2 process list is a host-level operation. Run pm2 save as the download user during deployment.' });
|
|
}
|
|
if (!validName(name)) return res.status(400).json({ ok: false, error: 'Invalid worker name.' });
|
|
try {
|
|
let args;
|
|
if (cmd === 'create') {
|
|
if (scriptPath !== undefined && scriptPath !== settings.workerScript) {
|
|
return res.status(400).json({ ok: false, error: 'The worker executable is configured by the server.' });
|
|
}
|
|
if ((await processes()).some((process) => (process.name || process.pm2_env?.name) === name)) {
|
|
return res.status(409).json({ ok: false, error: 'This process name is already in use.' });
|
|
}
|
|
args = createArguments(name);
|
|
} else {
|
|
const worker = await resolveManagedProcess(name);
|
|
if (!worker) return res.status(404).json({ ok: false, error: 'The selected downloader worker was not found.' });
|
|
args = [cmd, worker.pm_id];
|
|
}
|
|
const { code } = await run(args);
|
|
return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code,
|
|
message: code === 0 ? 'Worker command completed.' : 'Worker command failed. Check the supervisor on the server.' });
|
|
} catch {
|
|
return res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' });
|
|
}
|
|
}
|
|
|
|
return { getManage, listJson, postCommand, quickAdd, resolveManagedProcess, listManagedProcesses };
|
|
}
|
|
|
|
module.exports = { ...createPm2Controller(), createPm2Controller, normalizeProcess, validName };
|