refactoring and ES6 improvements

This commit is contained in:
Sebastian Hildebrandt 2016-11-15 08:58:32 +01:00
parent 3e1669e3fb
commit aa67440b9c
11 changed files with 89 additions and 89 deletions

View File

@ -52,7 +52,7 @@ function getCpu() {
reject(error); reject(error);
} }
var result = { let result = {
manufacturer: 'unknown', manufacturer: 'unknown',
brand: 'unknown', brand: 'unknown',
speed: '0.00', speed: '0.00',
@ -183,7 +183,7 @@ function cpuTemperature(callback) {
reject(error); reject(error);
} }
var result = { let result = {
main: -1.0, main: -1.0,
cores: [], cores: [],
max: -1.0 max: -1.0

View File

@ -21,8 +21,8 @@ let _platform = os.type();
const _windows = (_platform == 'Windows_NT'); const _windows = (_platform == 'Windows_NT');
const NOT_SUPPORTED = 'not supported'; const NOT_SUPPORTED = 'not supported';
var _docker_container_stats = {}; let _docker_container_stats = {};
var _docker_socket; let _docker_socket;
// -------------------------- // --------------------------
@ -48,7 +48,7 @@ function dockerContainers(all, callback) {
} }
all = all || false; all = all || false;
var result = []; let result = [];
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
process.nextTick(() => { process.nextTick(() => {
if (_windows) { if (_windows) {
@ -62,13 +62,13 @@ function dockerContainers(all, callback) {
} }
_docker_socket.listContainers(all, data => { _docker_socket.listContainers(all, data => {
var docker_containers = {}; let docker_containers = {};
// let cmd = "curl --unix-socket /var/run/docker.sock http:/containers/json" + (all ? "?all=1" : ""); // let cmd = "curl --unix-socket /var/run/docker.sock http:/containers/json" + (all ? "?all=1" : "");
// exec(cmd, function (error, stdout) { // exec(cmd, function (error, stdout) {
// if (!error) { // if (!error) {
try { try {
// let jsonString = stdout.toString(); // let jsonString = stdout.toString();
// var docker_containers = JSON.parse(jsonString); // let docker_containers = JSON.parse(jsonString);
docker_containers = data; docker_containers = data;
if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) { if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) {
docker_containers.forEach(function (element) { docker_containers.forEach(function (element) {
@ -109,7 +109,7 @@ function dockerContainers(all, callback) {
// } // }
// GC in _docker_container_stats // GC in _docker_container_stats
for (var key in _docker_container_stats) { for (let key in _docker_container_stats) {
if (_docker_container_stats.hasOwnProperty(key)) { if (_docker_container_stats.hasOwnProperty(key)) {
if (!inContainers(docker_containers, key)) delete _docker_container_stats[key]; if (!inContainers(docker_containers, key)) delete _docker_container_stats[key];
} }
@ -136,11 +136,11 @@ function docker_calcCPUPercent(cpu_stats, id) {
* @property {Array} cpu_usage.percpu_usage * @property {Array} cpu_usage.percpu_usage
*/ */
var cpuPercent = 0.0; let cpuPercent = 0.0;
// calculate the change for the cpu usage of the container in between readings // calculate the change for the cpu usage of the container in between readings
var cpuDelta = cpu_stats.cpu_usage.total_usage - (_docker_container_stats[id] && _docker_container_stats[id].prev_CPU ? _docker_container_stats[id].prev_CPU : 0); let cpuDelta = cpu_stats.cpu_usage.total_usage - (_docker_container_stats[id] && _docker_container_stats[id].prev_CPU ? _docker_container_stats[id].prev_CPU : 0);
// calculate the change for the entire system between readings // calculate the change for the entire system between readings
var systemDelta = cpu_stats.system_cpu_usage - (_docker_container_stats[id] && _docker_container_stats[id].prev_system ? _docker_container_stats[id].prev_system : 0); let systemDelta = cpu_stats.system_cpu_usage - (_docker_container_stats[id] && _docker_container_stats[id].prev_system ? _docker_container_stats[id].prev_system : 0);
if (systemDelta > 0.0 && cpuDelta > 0.0) { if (systemDelta > 0.0 && cpuDelta > 0.0) {
cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0; cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
@ -153,9 +153,9 @@ function docker_calcCPUPercent(cpu_stats, id) {
} }
function docker_calcNetworkIO(networks) { function docker_calcNetworkIO(networks) {
var rx; let rx;
var tx; let tx;
for (var key in networks) { for (let key in networks) {
// skip loop if the property is from prototype // skip loop if the property is from prototype
if (!networks.hasOwnProperty(key)) continue; if (!networks.hasOwnProperty(key)) continue;
@ -164,7 +164,7 @@ function docker_calcNetworkIO(networks) {
* @property {number} rx_bytes * @property {number} rx_bytes
* @property {number} tx_bytes * @property {number} tx_bytes
*/ */
var obj = networks[key]; let obj = networks[key];
rx = +obj.rx_bytes; rx = +obj.rx_bytes;
tx = +obj.tx_bytes; tx = +obj.tx_bytes;
} }
@ -208,7 +208,7 @@ function docker_calcBlockIO(blkio_stats) {
function dockerContainerStats(containerID, callback) { function dockerContainerStats(containerID, callback) {
containerID = containerID || ''; containerID = containerID || '';
var result = { let result = {
id: containerID, id: containerID,
mem_usage: 0, mem_usage: 0,
mem_limit: 0, mem_limit: 0,
@ -291,7 +291,7 @@ exports.dockerContainerStats = dockerContainerStats;
function dockerContainerProcesses(containerID, callback) { function dockerContainerProcesses(containerID, callback) {
containerID = containerID || ''; containerID = containerID || '';
var result = []; let result = [];
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
process.nextTick(() => { process.nextTick(() => {
if (_windows) { if (_windows) {
@ -316,20 +316,20 @@ function dockerContainerProcesses(containerID, callback) {
let titles = data.Titles.map(function(value) { let titles = data.Titles.map(function(value) {
return value.toUpperCase(); return value.toUpperCase();
}); });
var pos_pid = titles.indexOf('PID'); let pos_pid = titles.indexOf('PID');
var pos_ppid = titles.indexOf('PPID'); let pos_ppid = titles.indexOf('PPID');
var pos_pgid = titles.indexOf('PGID'); let pos_pgid = titles.indexOf('PGID');
var pos_vsz = titles.indexOf('VSZ'); let pos_vsz = titles.indexOf('VSZ');
var pos_time = titles.indexOf('TIME'); let pos_time = titles.indexOf('TIME');
var pos_elapsed = titles.indexOf('ELAPSED'); let pos_elapsed = titles.indexOf('ELAPSED');
var pos_ni = titles.indexOf('NI'); let pos_ni = titles.indexOf('NI');
var pos_ruser = titles.indexOf('RUSER'); let pos_ruser = titles.indexOf('RUSER');
var pos_user = titles.indexOf('USER'); let pos_user = titles.indexOf('USER');
var pos_rgroup = titles.indexOf('RGROUP'); let pos_rgroup = titles.indexOf('RGROUP');
var pos_group = titles.indexOf('GROUP'); let pos_group = titles.indexOf('GROUP');
var pos_stat = titles.indexOf('STAT'); let pos_stat = titles.indexOf('STAT');
var pos_rss = titles.indexOf('RSS'); let pos_rss = titles.indexOf('RSS');
var pos_command = titles.indexOf('COMMAND'); let pos_command = titles.indexOf('COMMAND');
data.Processes.forEach(process => { data.Processes.forEach(process => {
result.push({ result.push({
@ -375,7 +375,7 @@ function dockerAll(callback) {
} }
dockerContainers(true).then(result => { dockerContainers(true).then(result => {
if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) { if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) {
var l = result.length; let l = result.length;
result.forEach(function (element) { result.forEach(function (element) {
dockerContainerStats(element.id).then(res => { dockerContainerStats(element.id).then(res => {
// include stats in array // include stats in array

View File

@ -147,8 +147,8 @@ const users = require('./users');
const internet = require('./internet'); const internet = require('./internet');
const docker = require('./docker'); const docker = require('./docker');
var _platform = os.type(); let _platform = os.type();
var _windows = (_platform == 'Windows_NT'); let _windows = (_platform == 'Windows_NT');
const NOT_SUPPORTED = 'not supported'; const NOT_SUPPORTED = 'not supported';
@ -177,7 +177,7 @@ function getStaticData(callback) {
reject(error); reject(error);
} }
var data = {}; let data = {};
data.version = version(); data.version = version();
@ -236,8 +236,8 @@ function getDynamicData(srv, iface, callback) {
srv = srv || ''; srv = srv || '';
// use closure to track ƒ completion // use closure to track ƒ completion
var functionProcessed = (function () { let functionProcessed = (function () {
var totalFunctions = 14; let totalFunctions = 14;
return function () { return function () {
if (--totalFunctions === 0) { if (--totalFunctions === 0) {
@ -255,7 +255,7 @@ function getDynamicData(srv, iface, callback) {
// } // }
// } // }
var data = {}; let data = {};
// get time // get time
data.time = osInfo.time(); data.time = osInfo.time();
@ -359,12 +359,12 @@ function getAllData(srv, iface, callback) {
reject(error); reject(error);
} }
var data = {}; let data = {};
getStaticData().then(res => { getStaticData().then(res => {
data = res; data = res;
getDynamicData(srv, iface).then(res => { getDynamicData(srv, iface).then(res => {
for (var key in res) { for (let key in res) {
if (res.hasOwnProperty(key)) { if (res.hasOwnProperty(key)) {
data[key] = res[key]; data[key] = res[key];
} }

View File

@ -36,14 +36,14 @@ function inetChecksite(url, callback) {
reject(error); reject(error);
} }
var result = { let result = {
url: url, url: url,
ok: false, ok: false,
status: 404, status: 404,
ms: -1 ms: -1
}; };
if (url) { if (url) {
var t = Date.now(); let t = Date.now();
let args = " -I --connect-timeout 5 -m 5 " + url + " 2>/dev/null | head -n 1 | cut -d ' ' -f2"; let args = " -I --connect-timeout 5 -m 5 " + url + " 2>/dev/null | head -n 1 | cut -d ' ' -f2";
let cmd = "curl"; let cmd = "curl";
exec(cmd + args, function (error, stdout) { exec(cmd + args, function (error, stdout) {
@ -85,7 +85,7 @@ function inetLatency(host, callback) {
reject(error); reject(error);
} }
var t = Date.now(); let t = Date.now();
let cmd; let cmd;
if (_linux) { if (_linux) {
cmd = "ping -c 2 -w 3 " + host + " | grep rtt | cut -d'/' -f4 | awk '{ print $3 }'"; cmd = "ping -c 2 -w 3 " + host + " | grep rtt | cut -d'/' -f4 | awk '{ print $3 }'";

View File

@ -84,7 +84,7 @@ module.exports = function (callback) {
reject(error); reject(error);
} }
var result = { let result = {
total: os.totalmem(), total: os.totalmem(),
free: os.freemem(), free: os.freemem(),
used: os.totalmem() - os.freemem(), used: os.totalmem() - os.freemem(),

View File

@ -272,12 +272,12 @@ function networkConnections(callback) {
reject(error); reject(error);
} }
var result = []; let result = [];
if (_linux) { if (_linux) {
let cmd = "netstat -tuna | grep 'ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN\\|VERBUNDEN'"; let cmd = "netstat -tuna | grep 'ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN\\|VERBUNDEN'";
exec(cmd, function (error, stdout) { exec(cmd, function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
line = line.replace(/ +/g, " ").split(' '); line = line.replace(/ +/g, " ").split(' ');
if (line.length >= 6) { if (line.length >= 6) {
@ -320,7 +320,7 @@ function networkConnections(callback) {
exec(cmd, function (error, stdout) { exec(cmd, function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
line = line.replace(/ +/g, " ").split(' '); line = line.replace(/ +/g, " ").split(' ');
if (line.length >= 6) { if (line.length >= 6) {

View File

@ -90,7 +90,7 @@ function osInfo(callback) {
reject(error); reject(error);
} }
var result = { let result = {
platform: _platform, platform: _platform,
distro: 'unknown', distro: 'unknown',
@ -114,8 +114,8 @@ function osInfo(callback) {
* @property {string} VERSION_ID * @property {string} VERSION_ID
* @property {string} DISTRIB_CODENAME * @property {string} DISTRIB_CODENAME
*/ */
var release = {}; let release = {};
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
if (line.indexOf('=') != -1) { if (line.indexOf('=') != -1) {
release[line.split('=')[0].trim().toUpperCase()] = line.split('=')[1].trim(); release[line.split('=')[0].trim().toUpperCase()] = line.split('=')[1].trim();
@ -132,7 +132,7 @@ function osInfo(callback) {
} }
if (_darwin) { if (_darwin) {
exec("sw_vers", function (error, stdout) { exec("sw_vers", function (error, stdout) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
if (line.indexOf('ProductName') != -1) { if (line.indexOf('ProductName') != -1) {
result.distro = line.split(':')[1].trim(); result.distro = line.split(':')[1].trim();

View File

@ -225,15 +225,15 @@ function services(srv, callback) {
} }
srv = srv.trim().replace(/,+/g, " ").replace(/ +/g, " ").replace(/ +/g, "|"); srv = srv.trim().replace(/,+/g, " ").replace(/ +/g, " ").replace(/ +/g, "|");
var srvs = srv.split('|'); let srvs = srv.split('|');
var comm = (_darwin) ? "ps -caxm -o pcpu,pmem,comm" : "ps axo pcpu,pmem,comm"; let comm = (_darwin) ? "ps -caxm -o pcpu,pmem,comm" : "ps axo pcpu,pmem,comm";
var data = []; let data = [];
if (srv != '' && srvs.length > 0) { if (srv != '' && srvs.length > 0) {
exec(comm + " | grep -v grep | egrep '" + srv + "'", function (error, stdout) { exec(comm + " | grep -v grep | egrep '" + srv + "'", function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().replace(/ +/g, " ").replace(/,+/g, ".").split('\n'); let lines = stdout.toString().replace(/ +/g, " ").replace(/,+/g, ".").split('\n');
srvs.forEach(function (srv) { srvs.forEach(function (srv) {
var ps = lines.filter(function (e) { let ps = lines.filter(function (e) {
return e.indexOf(srv) != -1 return e.indexOf(srv) != -1
}); });
data.push({ data.push({
@ -535,7 +535,7 @@ function processLoad(proc, callback) {
reject(error); reject(error);
} }
var result = { let result = {
'proc': proc, 'proc': proc,
'pid': -1, 'pid': -1,
'cpu': 0, 'cpu': 0,

View File

@ -39,7 +39,7 @@ module.exports = function (callback) {
reject(error); reject(error);
} }
var result = { let result = {
manufacturer: '', manufacturer: '',
model: 'Computer', model: 'Computer',
version: '', version: '',
@ -50,7 +50,7 @@ module.exports = function (callback) {
if (_linux) { if (_linux) {
exec("dmidecode -t system", function (error, stdout) { exec("dmidecode -t system", function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
if (line.indexOf(':') != -1) { if (line.indexOf(':') != -1) {
if (line.toLowerCase().indexOf('manufacturer') != -1) result.manufacturer = result.manufacturer || line.split(':')[1].trim(); if (line.toLowerCase().indexOf('manufacturer') != -1) result.manufacturer = result.manufacturer || line.split(':')[1].trim();
@ -69,7 +69,7 @@ module.exports = function (callback) {
// Check Raspberry Pi // Check Raspberry Pi
exec("grep Hardware /proc/cpuinfo; grep Serial /proc/cpuinfo; grep Revision /proc/cpuinfo", function (error, stdout) { exec("grep Hardware /proc/cpuinfo; grep Serial /proc/cpuinfo; grep Revision /proc/cpuinfo", function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
if (line.indexOf(':') != -1) { if (line.indexOf(':') != -1) {
if (line.toLowerCase().indexOf('hardware') != -1) result.model = line.split(':')[1].trim(); if (line.toLowerCase().indexOf('hardware') != -1) result.model = line.split(':')[1].trim();
@ -122,7 +122,7 @@ module.exports = function (callback) {
} else { } else {
exec("dmesg | grep -i virtual | grep -iE 'vmware|qemu|kvm|xen'", function (error, stdout) { exec("dmesg | grep -i virtual | grep -iE 'vmware|qemu|kvm|xen'", function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
if (lines.length > 0) result.model = 'Virtual machine' if (lines.length > 0) result.model = 'Virtual machine'
} }
if (fs.existsSync('/.dockerenv') || fs.existsSync('/.dockerinit')) { if (fs.existsSync('/.dockerenv') || fs.existsSync('/.dockerinit')) {
@ -137,7 +137,7 @@ module.exports = function (callback) {
if (_darwin) { if (_darwin) {
exec("ioreg -c IOPlatformExpertDevice -d 2", function (error, stdout) { exec("ioreg -c IOPlatformExpertDevice -d 2", function (error, stdout) {
if (!error) { if (!error) {
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
lines.forEach(function (line) { lines.forEach(function (line) {
line = line.replace(/[<>"]/g, ""); line = line.replace(/[<>"]/g, "");
if (line.indexOf('=') != -1) { if (line.indexOf('=') != -1) {
@ -155,4 +155,4 @@ module.exports = function (callback) {
} }
}); });
}); });
} };

View File

@ -27,21 +27,21 @@ const NOT_SUPPORTED = 'not supported';
// array of users online = sessions // array of users online = sessions
function parseUsers1(lines) { function parseUsers1(lines) {
var result = []; let result = [];
var result_who = []; let result_who = [];
var result_w = {}; let result_w = {};
var w_first = true; let w_first = true;
var w_header = []; let w_header = [];
var w_pos = []; let w_pos = [];
var w_headerline = ''; let w_headerline = '';
var who_line = {}; let who_line = {};
var is_whopart = true; let is_whopart = true;
lines.forEach(function (line) { lines.forEach(function (line) {
if (line == '---') { if (line == '---') {
is_whopart = false; is_whopart = false;
} else { } else {
var l = line.replace(/ +/g, " ").split(' '); let l = line.replace(/ +/g, " ").split(' ');
// who part // who part
if (is_whopart) { if (is_whopart) {
@ -89,17 +89,17 @@ function parseUsers1(lines) {
} }
function parseUsers2(lines) { function parseUsers2(lines) {
var result = []; let result = [];
var result_who = []; let result_who = [];
var result_w = {}; let result_w = {};
var who_line = {}; let who_line = {};
var is_whopart = true; let is_whopart = true;
lines.forEach(function (line) { lines.forEach(function (line) {
if (line == '---') { if (line == '---') {
is_whopart = false; is_whopart = false;
} else { } else {
var l = line.replace(/ +/g, " ").split(' '); let l = line.replace(/ +/g, " ").split(' ');
// who part // who part
if (is_whopart) { if (is_whopart) {
@ -146,14 +146,14 @@ function users(callback) {
reject(error); reject(error);
} }
var result = []; let result = [];
// linux // linux
if (_linux) { if (_linux) {
exec("who --ips; echo '---'; w | tail -n +2", function (error, stdout) { exec("who --ips; echo '---'; w | tail -n +2", function (error, stdout) {
if (!error) { if (!error) {
// lines / split // lines / split
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
result = parseUsers1(lines); result = parseUsers1(lines);
if (result.length == 0) { if (result.length == 0) {
exec("who; echo '---'; w | tail -n +2", function (error, stdout) { exec("who; echo '---'; w | tail -n +2", function (error, stdout) {
@ -183,7 +183,7 @@ function users(callback) {
exec("who; echo '---'; w -ih", function (error, stdout) { exec("who; echo '---'; w -ih", function (error, stdout) {
if (!error) { if (!error) {
// lines / split // lines / split
var lines = stdout.toString().split('\n'); let lines = stdout.toString().split('\n');
result = parseUsers2(lines); result = parseUsers2(lines);
if (callback) { callback(result) } if (callback) { callback(result) }

View File

@ -16,18 +16,18 @@ const os = require('os');
let _cores = 0; let _cores = 0;
function isFunction(functionToCheck) { function isFunction(functionToCheck) {
var getType = {}; let getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
} }
function unique(obj){ function unique(obj){
var uniques=[]; let uniques=[];
var stringify={}; let stringify={};
for(var i=0;i<obj.length;i++){ for(let i=0;i<obj.length;i++){
var keys=Object.keys(obj[i]); let keys=Object.keys(obj[i]);
keys.sort(function(a,b) {return a-b}); keys.sort(function(a,b) {return a-b});
var str=''; let str='';
for(var j=0;j<keys.length;j++){ for(let j=0;j<keys.length;j++){
str+= JSON.stringify(keys[j]); str+= JSON.stringify(keys[j]);
str+= JSON.stringify(obj[i][keys[j]]); str+= JSON.stringify(obj[i][keys[j]]);
} }