1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
'use strict'
const baseWidget = require('../../src/baseWidget')
class myWidget extends baseWidget() {
constructor ({ blessed = {}, contrib = {}, screen = {}, grid = {} }) {
super()
this.blessed = blessed
this.contrib = contrib
this.screen = screen
this.grid = grid
this.label = 'Containers Utilization (%)'
this.widget = this.getWidget()
}
init () {
if (!this.widgetsRepo.has('containers')) {
return null
}
const dockerHook = this.widgetsRepo.get('containers')
dockerHook.on('containerUtilization', (data) => {
return this.update(data)
})
}
getWidget () {
return this.grid.gridObj.set(...this.grid.gridLayout, this.contrib.bar, {
label: this.label,
style: this.getWidgetStyle({ fg: 'blue' }),
border: {
type: 'line',
fg: '#00ff00'
},
barBgColor: 'cyan',
barFgColor: 'white',
barWidth: 6,
barSpacing: 15,
xOffset: 3,
maxHeight: 15,
labelColor: this.getWidgetStyle().fg
})
}
update (data) {
if (!data || (typeof data !== 'object')) {
return
}
if (!data.cpu_stats || !data.precpu_stats || !data.cpu_stats.cpu_usage ||
!data.precpu_stats.cpu_usage || !data.cpu_stats.cpu_usage.total_usage ||
!data.precpu_stats.cpu_usage.total_usage ||
!data.cpu_stats.system_cpu_usage || !data.precpu_stats.system_cpu_usage ||
!data.cpu_stats.cpu_usage.percpu_usage) {
return this.widget.setData({
titles: ['CPU', 'Memory'],
data: [
0,
0
]
})
}
// Calculate CPU usage based on delta from previous measurement
let cpuUsageDelta = data.cpu_stats.cpu_usage.total_usage - data.precpu_stats.cpu_usage.total_usage
let systemUsageDelta = data.cpu_stats.system_cpu_usage - data.precpu_stats.system_cpu_usage
let cpuCoresAvail = data.cpu_stats.cpu_usage.percpu_usage ? data.cpu_stats.cpu_usage.percpu_usage.length : 0
let cpuUsagePercent = 0
if (systemUsageDelta !== 0 || cpuCoresAvail !== 0) {
let totalUsage = systemUsageDelta * cpuCoresAvail * 100
cpuUsagePercent = 0
if (totalUsage && totalUsage !== 0) {
cpuUsagePercent = cpuUsageDelta / totalUsage
}
}
// Calculate Memory usage
let memUsage = data.memory_stats.usage
let memAvail = data.memory_stats.limit
let memUsagePercent = 0
if ((memUsage !== undefined && memAvail !== undefined) && memAvail !== 0) {
memUsagePercent = memUsage / memAvail * 100
}
this.widget.setData({
titles: ['CPU', 'Memory'],
data: [
Math.round(Number(cpuUsagePercent)),
Math.round(Number(memUsagePercent))
]
})
this.screen.render()
}
}
module.exports = myWidget
|