optimized stuff, implemented command timeouts

This commit is contained in:
Daniel Sommer 2022-04-06 15:20:08 +02:00
parent fe57525ed9
commit bb1d8f3f50
5 changed files with 84 additions and 55 deletions

5
.vscode/launch.json vendored
View file

@ -9,7 +9,10 @@
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/remex.js"
"program": "${workspaceFolder}/remex.js",
"args": [
"${workspaceFolder}/example_config.json"
]
}
]
}

View file

@ -9,16 +9,18 @@
},
"api": [
{
"url": "/tail",
"url": "/watch",
"method": "get",
"command": "tail",
"command": "watch",
"args": [
"-f",
"/tmp/example"
"-n",
"3",
"ls"
],
"options": {
"detach": true,
"unique": true
"unique": "restart",
"timeout": 10000
}
},
{

View file

@ -1,52 +1,75 @@
const logger = require('./logger.js');
const { spawn } = require('child_process');
const { create } = require('domain');
const STATE_OK = 'ok';
const STATE_DETACHED = 'detached';
const STATE_REJECTED = 'rejected';
const STATE_KILLED = 'killed';
const STATE_ERROR = 'error';
const cmds = new Map();
let cmdId = -1;
async function execute(endpoint) {
if (endpoint === undefined) {
return;
return createResult(STATE_REJECTED, undefined, 'endpoint is not defined');
}
let unique = endpoint.options?.unique;
let unique = endpoint.options?.unique?.toString();
if (unique !== undefined && isCommandActive(endpoint)) {
unique = unique.toLowerCase();
switch (unique.toLowerCase()) {
case 'true':
logger.info('not executing unique command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\') because it is already active');
throw new Error('command is already active');
return createResult(STATE_REJECTED, undefined, 'unique command is already active');
case 'restart':
logger.info('killing and restarting unique command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')');
logger.info('killing and restarting unique command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
await killCommand(endpoint);
break;
case 'toggle':
logger.info('stopping unique command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')');
return await killCommand(endpoint);
logger.info('stopping unique command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
await killCommand(endpoint);
return createResult(STATE_KILLED);
}
}
return new Promise((resolve, reject) => {
logger.info('executing command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
var cmd = spawn(endpoint.command, endpoint.args);
cmdId++;
logger.info('executing command #' + cmdId + ' \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
let cmd = spawn(endpoint.command, endpoint.args);
cmd.id = cmdId;
cmd.timestamp = new Date().getTime();
let result = '';
let error = '';
cmd.data = '';
cmd.error = '';
cmd.stdout.on('data', (data) => {
result += data;
cmd.data += data;
});
cmd.stderr.on('data', (data) => {
error += data;
cmd.stderr.on('data', (err) => {
if (err.toString().toLowerCase().contains('warning')) {
cmd.data += err;
}
cmd.error += err;
});
cmd.on('spawn', () => {
logger.info('spawned command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')');
logger.info('spawned command #' + cmd.id + ' \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
addCommand(cmd, endpoint);
if (endpoint.options?.timeout && !isNaN(endpoint.options?.timeout)) {
setTimeout(async () => {
if (!cmds.has(endpoint)) {
return;
}
logger.warn('killing timed out command #' + cmd.id + ' \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\') after ' + endpoint.options.timeout + 'ms...');
await killCommand(endpoint);
}, endpoint.options.timeout);
}
if (endpoint.options?.detach) {
resolve();
return resolve(createResult(STATE_DETACHED, cmd.data, cmd.error));
}
});
cmd.on('error', (err) => {
error += err;
cmd.error += err;
removeCommand(endpoint);
if (endpoint.options?.detach) {
reject();
reject(createResult(STATE_ERROR, cmd.data, cmd.error));
}
});
cmd.on('exit', (code) => {
@ -55,23 +78,34 @@ async function execute(endpoint) {
}
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) {
error = error.trim();
msg += ' > error: ' + error;
let msg = 'command #' + cmd.id + ' \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\') finished with exit code ' + code + ' after ' + (new Date().getTime() - cmd.timestamp) + 'ms';
if (cmd.error !== undefined && cmd.error.length > 0) {
cmd.error = error.trim();
msg += ' > error: ' + cmd.error;
fn = logger.error;
reject(error);
reject(createResult(STATE_ERROR, cmd.data, cmd.error));
}
if (result !== undefined && result.length > 0) {
result = result.trim();
msg += ' > data: ' + result;
if (cmd.data !== undefined && cmd.data.length > 0) {
cmd.data = cmd.data.trim();
msg += ' > data: ' + cmd.data;
}
fn(msg);
resolve(result);
resolve(createResult(STATE_OK, cmd.data, cmd.error));
});
});
}
function createResult(state, data, error) {
if (state === undefined ) {
return;
}
return {
state,
data,
error
}
}
function addCommand(command, endpoint) {
if (command === undefined || endpoint === undefined) {
return;

View file

@ -15,7 +15,7 @@ async function start() {
return new Promise((resolve, reject) => {
server.listen(port, listen)
.on('listening', function () {
logger.info('server listening on ' + global.config.server.listen + ':' + global.config.server.port + '...');
logger.info('server listening on ' + listen + ':' + port + '...');
handleRequests();
resolve();
});
@ -34,34 +34,24 @@ async function respond(request, response) {
return;
}
let endpoint = api[request.method]?.[request.url];
if (endpoint === undefined) {
return finishRequest(request, response, { error: 'endpoint not defined' }, 501);
}
try {
endpoint.result = await commands.execute(endpoint);
} catch (err) {
endpoint.error = err.toString();
return finishRequest(request, response, endpoint, 501);
}
return finishRequest(request, response, endpoint);
let result = await commands.execute(endpoint);
result.command = endpoint.command;
result.args = endpoint.args;
return finishRequest(request, response, result);
}
function finishRequest(request, response, data, code) {
function finishRequest(request, response, result) {
if (response === undefined) {
return;
}
data.time = (new Date().getTime() - request.timestamp) + 'ms';
if (code === undefined) {
code = 200;
result.time = (new Date().getTime() - request.timestamp) + 'ms';
let code = result.code || 200;
if (result.error !== undefined && result.error.length > 0) {
code = 501;
}
if (code === 200) {
data.status = 'ok';
} else {
data.status = 'error';
}
delete result.code;
response.writeHead(code);
const json = JSON.stringify(data);
const json = JSON.stringify(result);
response.end(json);
logger.http({ request: request, code: code, data: json });
}

View file

@ -8,7 +8,7 @@ const INTERRUPTS = ['beforeExit', 'SIGINT', 'SIGTERM'];
main();
async function main() {
let configPath = path.resolve(__dirname + '/config.json');
let configPath = path.resolve(process.argv[2] || __dirname + '/config.json');
try {
global.config = require(configPath);
} catch (err) {