From bb1d8f3f50eed0e087feb93c59d0d24a84260e9e Mon Sep 17 00:00:00 2001 From: velvettear Date: Wed, 6 Apr 2022 15:20:08 +0200 Subject: [PATCH] optimized stuff, implemented command timeouts --- .vscode/launch.json | 5 ++- example_config.json | 12 ++++--- libs/commands.js | 86 +++++++++++++++++++++++++++++++-------------- libs/server.js | 34 +++++++----------- remex.js | 2 +- 5 files changed, 84 insertions(+), 55 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index a38205e..3947f96 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -9,7 +9,10 @@ "skipFiles": [ "/**" ], - "program": "${workspaceFolder}/remex.js" + "program": "${workspaceFolder}/remex.js", + "args": [ + "${workspaceFolder}/example_config.json" + ] } ] } \ No newline at end of file diff --git a/example_config.json b/example_config.json index 2bea21b..81cc2f6 100644 --- a/example_config.json +++ b/example_config.json @@ -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 } }, { diff --git a/libs/commands.js b/libs/commands.js index 35def77..c982eaa 100644 --- a/libs/commands.js +++ b/libs/commands.js @@ -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; diff --git a/libs/server.js b/libs/server.js index dbf5713..ec45687 100644 --- a/libs/server.js +++ b/libs/server.js @@ -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 }); } diff --git a/remex.js b/remex.js index 6cbdd04..453e53e 100644 --- a/remex.js +++ b/remex.js @@ -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) {