xmtop/widgets/mem.go

77 lines
1.7 KiB
Go
Raw Normal View History

2018-02-19 15:25:02 +08:00
package widgets
import (
"fmt"
2018-02-19 15:25:02 +08:00
"time"
"github.com/VictoriaMetrics/metrics"
2019-01-31 07:20:09 +08:00
2020-04-24 03:07:08 +08:00
"github.com/xxxserxxx/gotop/v4/devices"
ui "github.com/xxxserxxx/gotop/v4/termui"
"github.com/xxxserxxx/gotop/v4/utils"
2018-02-19 15:25:02 +08:00
)
2019-03-01 08:29:52 +08:00
type MemWidget struct {
2018-02-19 15:25:02 +08:00
*ui.LineGraph
2019-03-01 08:29:52 +08:00
updateInterval time.Duration
2019-05-29 02:43:29 +08:00
}
func NewMemWidget(updateInterval time.Duration, horizontalScale int) *MemWidget {
widg := &MemWidget{
2019-03-01 08:29:52 +08:00
LineGraph: ui.NewLineGraph(),
updateInterval: updateInterval,
2018-03-04 09:05:52 +08:00
}
widg.Title = " Memory Usage "
widg.HorizontalScale = horizontalScale
mems := make(map[string]devices.MemoryInfo)
devices.UpdateMem(mems)
for name, mem := range mems {
widg.Data[name] = []float64{0}
widg.renderMemInfo(name, mem)
}
2018-04-13 11:00:34 +08:00
2018-02-19 15:25:02 +08:00
go func() {
for range time.NewTicker(widg.updateInterval).C {
widg.Lock()
devices.UpdateMem(mems)
for label, mi := range mems {
widg.renderMemInfo(label, mi)
}
widg.Unlock()
2018-02-19 15:25:02 +08:00
}
}()
return widg
2018-02-19 15:25:02 +08:00
}
2020-04-28 09:33:41 +08:00
func (mem *MemWidget) EnableMetric() {
mems := make(map[string]devices.MemoryInfo)
devices.UpdateMem(mems)
for l, _ := range mems {
lc := l
metrics.NewGauge(makeName("memory", l), func() float64 {
if ds, ok := mem.Data[lc]; ok {
return ds[len(ds)-1]
}
return 0.0
})
}
}
2020-04-28 09:33:41 +08:00
func (mem *MemWidget) Scale(i int) {
mem.LineGraph.HorizontalScale = i
}
2020-04-28 09:33:41 +08:00
func (mem *MemWidget) renderMemInfo(line string, memoryInfo devices.MemoryInfo) {
mem.Data[line] = append(mem.Data[line], memoryInfo.UsedPercent)
memoryTotalBytes, memoryTotalMagnitude := utils.ConvertBytes(memoryInfo.Total)
memoryUsedBytes, memoryUsedMagnitude := utils.ConvertBytes(memoryInfo.Used)
2020-04-28 09:33:41 +08:00
mem.Labels[line] = fmt.Sprintf("%3.0f%% %5.1f%s/%.0f%s",
memoryInfo.UsedPercent,
memoryUsedBytes,
memoryUsedMagnitude,
memoryTotalBytes,
memoryTotalMagnitude,
)
}