From 2071512b202887c8ea28b77ca9c3c24c246dcb8c Mon Sep 17 00:00:00 2001 From: Mark Nadal Date: Sat, 27 Apr 2019 00:16:12 -0700 Subject: [PATCH] add health stats --- lib/server.js | 1 + lib/stats.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 lib/stats.js diff --git a/lib/server.js b/lib/server.js index 509af9e5..90159bd0 100644 --- a/lib/server.js +++ b/lib/server.js @@ -17,6 +17,7 @@ require('./file'); require('./evict'); require('./multicast'); + require('./stats'); if('debug' === process.env.GUN_ENV){ require('./debug') } module.exports = Gun; }()); diff --git a/lib/stats.js b/lib/stats.js new file mode 100644 index 00000000..40c9be4f --- /dev/null +++ b/lib/stats.js @@ -0,0 +1,43 @@ +var Gun = (typeof window !== "undefined")? window.Gun : require('../gun'); + +Gun.on('opt', function(root){ + this.to.next(root); + if(root.once){ return } + if(typeof process === 'undefined'){ return } + if(typeof require === 'undefined'){ return } + var noop = function(){}; + var os = require('os') || {}; + var fs = require('fs') || {}; + fs.existsSync = fs.existsSync || require('path').existsSync; + if(!fs.existsSync){ return } + if(!process){ return } + process.uptime = process.uptime || noop; + process.cpuUsage = process.cpuUsage || noop; + process.memoryUsage = process.memoryUsage || noop; + os.totalmem = os.totalmem || noop; + os.freemem = os.freemem || noop; + os.loadavg = os.loadavg || noop; + os.cpus = os.cpus || noop; + setTimeout(function(){ + root.stats = Gun.obj.ify((fs.existsSync(__dirname+'/../stats.'+root.opt.file) && fs.readFileSync(__dirname+'/../stats.'+root.opt.file).toString())) || {}; + root.stats.up = root.stats.up || {}; + root.stats.up.start = root.stats.up.start || +(new Date); + root.stats.up.count = (root.stats.up.count || 0) + 1; + },1); + setInterval(function(){ + if(!root.stats){ return } + var stats = root.stats, tmp; + (stats.up||{}).time = process.uptime(); + stats.memory = process.memoryUsage() || {}; + stats.memory.totalmem = os.totalmem(); + stats.memory.freemem = os.freemem(); + stats.cpu = process.cpuUsage() || {}; + stats.cpu.loadavg = os.loadavg(); + stats.peers = {}; + stats.peers.count = Object.keys(root.opt.peers||{}).length; + stats.node = {}; + stats.node.count = Object.keys(root.graph||{}).length; + fs.writeFile(__dirname+'/../stats.'+root.opt.file, JSON.stringify(stats, null, 2), function(err){}); + }, 1000 * 15); + Object.keys = Object.keys || function(o){ return Gun.obj.map(o, function(v,k,t){t(k)}) } +}); \ No newline at end of file