Update CPU and RAM collection and display methods

install-with-shinobicctv-user-instead-of-root
Moe 2020-08-27 15:40:30 -07:00
parent 2886e58918
commit a3df638988
5 changed files with 189 additions and 85 deletions

View File

@ -1,12 +1,28 @@
var fs = require('fs');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
const { getCpuUsageOnLinux, getRamUsageOnLinux } = require('./health/utils.js')
module.exports = function(s,config,lang,io){
s.heartBeat = function(){
setTimeout(s.heartBeat, 8000);
io.sockets.emit('ping',{beat:1});
}
s.heartBeat()
s.cpuUsage = function(callback){
let hasProcStat = false
try{
fs.statSync("/proc/stat")
hasProcStat = true
}catch(err){
}
if(hasProcStat){
s.cpuUsage = async () => {
const percent = await getCpuUsageOnLinux()
return percent
}
}else{
s.cpuUsage = () => {
return new Promise((resolve, reject) => {
var k = {}
switch(s.platform){
case'win32':
@ -30,7 +46,7 @@ module.exports = function(s,config,lang,io){
if(s.isWin===true) {
d = d.replace(/(\r\n|\n|\r)/gm, "").replace(/%/g, "")
}
callback(d)
resolve(d)
s.onGetCpuUsageExtensions.forEach(function(extender){
extender(d)
})
@ -40,16 +56,32 @@ module.exports = function(s,config,lang,io){
if(s.isWin===true){
d=d.replace(/(\r\n|\n|\r)/gm,"").replace(/%/g,"")
}
callback(d)
resolve(d)
s.onGetCpuUsageExtensions.forEach(function(extender){
extender(d)
})
})
} else {
callback(0)
resolve(0)
}
})
}
}
s.ramUsage = function(callback){
let hasProcMeminfo = false
try{
fs.statSync("/proc/meminfo")
hasProcMeminfo = true
}catch(err){
}
if(hasProcMeminfo){
s.ramUsage = async () => {
const used = await getRamUsageOnLinux()
return used
}
}else{
s.ramUsage = () => {
return new Promise((resolve, reject) => {
k={}
switch(s.platform){
case'win32':
@ -73,13 +105,24 @@ module.exports = function(s,config,lang,io){
if(s.isWin===true){
d=(parseInt(d.split('=')[1])/(s.totalmem/1000))*100
}
callback(d)
resolve(d)
s.onGetRamUsageExtensions.forEach(function(extender){
extender(d)
})
})
}else{
callback(0)
resolve(0)
}
})
}
}
setInterval(async () => {
const cpu = await s.cpuUsage()
const ram = await s.ramUsage()
s.tx({
f: 'os',
cpu: cpu,
ram: ram
},'CPU')
},10000)
}

67
libs/health/utils.js Normal file
View File

@ -0,0 +1,67 @@
const fs = require('fs');
const calculateCPUPercentage = function(oldVals, newVals){
var totalDiff = newVals.total - oldVals.total;
var activeDiff = newVals.active - oldVals.active;
return Math.ceil((activeDiff / totalDiff) * 100);
};
const currentCPUInfo = {
total: 0,
active: 0
}
const lastCPUInfo = {
total: 0,
active: 0
}
exports.getCpuUsageOnLinux = () => {
lastCPUInfo.active = currentCPUInfo.active;
lastCPUInfo.idle = currentCPUInfo.idle;
lastCPUInfo.total = currentCPUInfo.total;
return new Promise((resolve,reject) => {
const getUsage = function(callback){
fs.readFile("/proc/stat" ,'utf8', function(err, data){
var lines = data.split('\n');
var cpuTimes = lines[0].match(/[0-9]+/gi);
currentCPUInfo.total = 0;
// We'll count both idle and iowait as idle time
currentCPUInfo.idle = parseInt(cpuTimes[3]) + parseInt(cpuTimes[4]);
for (var i = 0; i < cpuTimes.length; i++){
currentCPUInfo.total += parseInt(cpuTimes[i]);
}
currentCPUInfo.active = currentCPUInfo.total - currentCPUInfo.idle
currentCPUInfo.percentUsed = calculateCPUPercentage(lastCPUInfo, currentCPUInfo);
callback(currentCPUInfo.percentUsed)
})
}
getUsage(function(percentage){
setTimeout(function(){
getUsage(function(percentage){
resolve(percentage);
})
}, 3000)
})
})
}
exports.getRamUsageOnLinux = () => {
return new Promise((resolve,reject) => {
fs.readFile("/proc/meminfo", function(err, data){
const rows = data.toString().split('\n');
const parsed = {}
rows.forEach((row) => {
const rowParts = row.split(':')
const label = rowParts[0].trim()
if(label === 'MemTotal' || label === 'MemFree' || label === 'MemAvailable'){
console.log(row)
const memoryUsed = parseFloat(rowParts[1].trim().split(' ')[0]) / 1000
parsed[label] = memoryUsed
}
})
const memFree = parsed.MemFree || parsed.MemAvailable
const ramUsed = parsed.MemTotal - memFree
const ramUsedPercent = parsed.MemTotal / memFree * 100 - 100
resolve({
used: ramUsed,
percent: ramUsedPercent,
});
})
})
}

View File

@ -418,13 +418,6 @@ module.exports = function(s,config,lang,io){
}
if(config.childNodes.mode !== 'child'){
//master node - startup functions
setInterval(function(){
s.cpuUsage(function(cpu){
s.ramUsage(function(ram){
s.tx({f:'os',cpu:cpu,ram:ram},'CPU');
})
})
},10000)
//hourly check to see if sizePurge has failed to unlock
//checks to see if request count is the number of monitors + 10
s.checkForStalePurgeLocks()

View File

@ -129,7 +129,7 @@ $.ccio.globalWebsocket=function(d,user){
$.ccio.pm(3,d.apis,null,user);
$('.os_platform').html(d.os.platform)
$('.os_cpuCount').html(d.os.cpuCount)
$('.os_totalmem').html((d.os.totalmem/1048576).toFixed(2))
$('.os_totalmem').attr('title',`Total : ${(d.os.totalmem/1048576).toFixed(2)}`)
if(d.os.cpuCount>1){
$('.os_cpuCount_trailer').html('s')
}
@ -148,13 +148,14 @@ $.ccio.globalWebsocket=function(d,user){
break;
case'os'://indicator
//cpu
d.cpu=parseFloat(d.cpu).toFixed(0)+'%';
$('.cpu_load .progress-bar').css('width',d.cpu);
$('.cpu_load .percent').html(d.cpu);
var cpuPercent = parseFloat(d.cpu).toFixed(1) + '%'
$('.cpu_load .progress-bar').css('width',cpuPercent)
$('.cpu_load .percent').html(cpuPercent)
//ram
d.ram=(100-parseFloat(d.ram)).toFixed(0)+'%';
$('.ram_load .progress-bar').css('width',d.ram);
$('.ram_load .percent').html(d.ram);
var ramPercent = d.ram.percent.toFixed(1) + '%'
$('.ram_load .progress-bar').css('width',ramPercent)
$('.ram_load .percent').html(ramPercent)
$('.ram_load .used').html(d.ram.used.toFixed(2))
break;
case'diskUsed':
if(!d.limit||d.limit===''){d.limit=10000}

View File

@ -73,7 +73,7 @@
</div>
<div class="ram_load display-table-cell">
<span class="pull-right percent"></span>
<label><span class="os_totalmem" style="letter-spacing:2px;font-weight:100"></span> <%-lang.MB%> <%-lang.RAM%></label>
<label><span class="os_totalmem used" style="letter-spacing:2px;font-weight:100"></span> <%-lang.MB%> <%-lang.RAM%></label>
<div class="progress">
<div class="progress-bar progress-bar-warning" role="progressbar" style="width:0%"></div>
</div>