Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 169 additions & 0 deletions cli/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* MFF HTTP-JSON-RPC CLI-client for administrative operation
*/

var http = require('http')

var JSONRPCClient = function(port, host, path = null) {
this.port = port;
this.host = host;
this.path = path;

this.call = function(method, params, callback) {
var requestJSON = JSON.stringify({
'jsonrpc': '2.0',
'id': (new Date().getTime()),
'method': method,
'params': params,
'cl': 'mffcli'
});
var headers = {
'host': host,
'Content-Length': requestJSON.length,
'Content-Type': 'application/json',
'Accept': 'application/json'
};

if (this.path === null) {
this.path = '/';
}

var options = {
host: host,
port: port,
path: this.path,
headers: headers,
method: 'POST'
}

var buffer = '';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стоит переходить на современные стандарты и использовать let/const

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошее замечание, спасибо


var req = http.request(options, function(res) {
res.on('data', function(chunk) {
buffer = buffer + chunk;
});

res.on('end', function() {
var decoded = {}
try {
decoded = JSON.parse(buffer);
} catch (error) {
callback(error, null);
return
}

if (decoded.hasOwnProperty('result')) {
callback(null, decoded.result);
} else {
callback(decoded.error, null);
}
});

res.on('error', function(err) {
callback(err, null);
});
});

req.on('error', function(err) {
console.error('ClientError:', err.code);
});

req.write(requestJSON);
req.end();
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Код, связанный с отправкой и обработкой запроса можно несколько сократить при использовании сторонней библиотеки axios или https://www.npmjs.com/package/node-fetch .

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно узнать, почему?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Есть несколько моментов:

  1. большой размер зависимостей и их зависимостей, что увеличивает размер билда
  2. при формировании билда (использую webpack для формирования единого JS-файла) поподает очень много "мусора" (т.е. реально не используемого кода на который ссылаются реализации)
  3. если не использовать билды - проблема развертывания в изолированных пром. средах
  4. желание иметь только реально задействованный код (пример: если подтянуть lodash для использования 2-3 методов, в билд упаковывается почти весь lodash)


const ARGUMENT_SEPARATION_REGEX = /([^=\s]+)=?\s*(.*)/;

function Parse(argv) {
// Removing node/bin and called script name
argv = argv.slice(2);

const parsedArgs = {};
let argName, argValue;

argv.forEach(function(arg) {
// Separate argument for a key/value return
arg = arg.match(ARGUMENT_SEPARATION_REGEX);
arg.splice(0, 1);

// Retrieve the argument name
argName = arg[0];

// Remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
}

// Parse argument value or set it to `true` if empty
argValue =
arg[1] !== '' ?
parseFloat(arg[1]).toString() === arg[1] ?
+arg[1] :
arg[1] :
true;

parsedArgs[argName] = argValue;
});

return parsedArgs;
}

/** Read args from cmd */
var args = Parse(process.argv);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Возможно, для парсинга аргументов имеет смысл воспользоваться готовыми библиотеками, на подобие minimist

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код.
Функция Parse взята из одной библиотеки по разбору аргументов - думаю стоит указать автора

/** Set from args or use defs */
var host = args.host || '127.0.0.1'
var port = args.port || 20799
var path = args.path || '/'
var method = args.method || 'ping'
var params = {}

for (const key in args) {
if (Object.hasOwnProperty.call(args, key)) {
const value = args[key];
switch (key) {
case 'host':
case 'port':
case 'path':
case 'method':
break;

default:
if (value === true) {
method = key
} else if (key.match(/^p\.(.*)$/)) {
params[key.replace(/^p\./, '')] = value
}
break;
}
}
}

if (Object.keys(args).length == 0) {
console.log('')
console.log(' MFF HTTP-JSON-RPC CLI-client')
console.log('')
console.log('use: node cli.js method [args,...]')
console.log(' node cli.js ping --port=20799')
console.log(' node cli.js ping --p.alpha=5 --p.beta=7 => params: {"alpha":5,"beta":7}')
console.log('')
console.log('\targ\t\treq\tdescription \tdefault')
console.log('')
console.log('\t--host\t\t\tserver host \t"127.0.0.1"')
console.log('\t--port\t\t\tserver port \t20799 (back-RPC)')
console.log('\t--path\t\t\tserver path \t"/"')
console.log('\t--p.[key]\t\tset params key \t"{}"')
console.log('\t--method\t*\texecuted method')
console.log('')
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

; в конце выражений в одних файлах есть везде (местами пропущены), в других их нет совсем.
В пределах проекта стоит придерживаться одного стиля кода

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спасибо, буду внимательнее

}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Библиотека commander.js предоставляет удобный интерфейс для вывода подобного рода сообщений (да и предоставляет больше возможностей для работы с командной строкой, чем упоминаемый ранее minimist )

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код.
Однако спасибо за подсказки в части предлагаемых библиотек


/** Run client */
var client = new JSONRPCClient(port, host, path)
client.call(method, params, function(error, result) {
if (error) {
console.error('ServerError:', error);
}
console.log('ServerResult:', result);
});
/** End of CLI */
64 changes: 53 additions & 11 deletions config.json._
Original file line number Diff line number Diff line change
@@ -1,17 +1,59 @@
{
"server": {
"port": 20744,
"logs": false
"rpc": {
"front": {
"active": true,
"driver": "json",
"dsn": {
"type": "front",
"host": "127.0.0.1",
"port": 20744,
"path": "/"
}
},
"back": {
"active": true,
"driver": "json",
"dsn": {
"type": "back",
"host": "127.0.0.1",
"port": 20799,
"path": "/"
}
}
},
"metric": {
"check": {
"interval": 15,
"run": "/usr/bin/sh /home/user/check.sh",
"notice": 20,
"warning": 35,
"error": 45,
"history": 10,
"call": "/usr/bin/sh /home/user/send.sh --metric=$1 --level=$2 --time=$3"
"test": {
"active": true,
"metric": {
"interval": 1000,
"driver": "dns",
"path": {
"rec": "google.com",
"type": "A",
"dns": "8.8.8.8"
}
},
"call": {
"caller": "shell",
"path": "echo $1 $2 $3 >> call.log"
},
"log": {
"logger": "local"
}
}
},
"caller": {
"shell": {
"active": true,
"driver": "shell",
"path": "echo $1 $2 $3 >> $1.call.log"
}
},
"logger": {
"local": {
"active": true,
"driver": "file",
"path": "./logs/$1.log"
}
}
}
41 changes: 0 additions & 41 deletions ext/dns.js

This file was deleted.

15 changes: 15 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Metric From Future
* Metric Server for calculation timing of script execution time
*
* @author AlexMcArrow <alex.mcarrow@gmail.com>
* @version 0.3.0
* @package metricfromfuture
*/

const server = require('./src/server')

var MFF = new server()
MFF.start(process.env.PATH_CONFIG || './config.json')

/** End of index */
9 changes: 4 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
{
"name": "@alexmcarrow/metricfromfuture",
"version": "0.2.18",
"version": "0.3.0",
"description": "Metric Server with realtime calculation",
"main": "./server.js",
"main": "./index.js",
"scripts": {
"test": "node server.js",
"start": "node ./dist/mff.js",
"dev": "node index.js",
"build": "webpack --config webpack.config.js"
},
"keywords": [
"metric",
"server",
"realtime",
"rpc"
"json-rpc"
],
"repository": {
"type": "git",
Expand Down
Loading