2022-03-15 01:36:47 +01:00
|
|
|
const logger = require('./logger.js');
|
2022-02-02 17:07:16 +01:00
|
|
|
const { spawn } = require('child_process')
|
|
|
|
|
2022-03-15 01:36:47 +01:00
|
|
|
const cmds = new Map();
|
|
|
|
|
|
|
|
async function execute(endpoint) {
|
|
|
|
if (endpoint === undefined) {
|
2022-02-02 17:07:16 +01:00
|
|
|
return;
|
|
|
|
}
|
2022-03-15 01:36:47 +01:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
logger.info('executing command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
|
|
|
|
var cmd = spawn(endpoint.command, endpoint.args);
|
|
|
|
cmd.timestamp = new Date().getTime();
|
|
|
|
let result = '';
|
|
|
|
let error = '';
|
|
|
|
cmd.stdout.on('data', (data) => {
|
|
|
|
result += data;
|
|
|
|
});
|
|
|
|
cmd.stderr.on('data', (data) => {
|
|
|
|
error += data;
|
|
|
|
});
|
|
|
|
cmd.on('spawn', () => {
|
|
|
|
logger.info('spawned command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')');
|
|
|
|
addCommand(cmd, endpoint);
|
|
|
|
if (endpoint.detach !== false) {
|
|
|
|
resolve();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
cmd.on('error', (err) => {
|
|
|
|
error += err;
|
|
|
|
removeCommand(endpoint);
|
|
|
|
if (endpoint.detach !== false) {
|
|
|
|
reject();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
cmd.on('close', (code) => {
|
|
|
|
removeCommand(endpoint);
|
|
|
|
let fn = logger.info;
|
|
|
|
let msg = 'command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\') finished with exit code ' + code + ' after ' + (new Date().getTime() - cmd.timestamp) + 'ms';
|
|
|
|
if (error !== undefined && error.length > 0) {
|
|
|
|
msg += ' >>> ' + error;
|
|
|
|
fn = logger.error;
|
|
|
|
reject(error);
|
|
|
|
}
|
|
|
|
if (result !== undefined && result.length > 0) {
|
|
|
|
msg += ' > ' + result;
|
|
|
|
}
|
|
|
|
fn(msg);
|
|
|
|
resolve(result);
|
|
|
|
});
|
2022-02-02 17:07:16 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-03-15 01:36:47 +01:00
|
|
|
function addCommand(command, endpoint) {
|
|
|
|
if (command === undefined || endpoint === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
cmds.set(JSON.stringify(endpoint), command);
|
|
|
|
}
|
|
|
|
|
|
|
|
function removeCommand(endpoint) {
|
|
|
|
if (endpoint === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
cmds.delete(JSON.stringify(endpoint));
|
|
|
|
}
|
|
|
|
|
|
|
|
function isCommandActive(endpoint) {
|
|
|
|
return endpoint !== undefined && cmds.has(JSON.stringify(endpoint));
|
|
|
|
}
|
|
|
|
|
|
|
|
function killCommand(endpoint) {
|
|
|
|
if (endpoint === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const command = cmds.get(JSON.stringify(endpoint));
|
|
|
|
if (command === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
process.kill(command.pid);
|
|
|
|
}
|
|
|
|
|
2022-02-02 17:07:16 +01:00
|
|
|
module.exports = {
|
|
|
|
execute
|
|
|
|
}
|