xmtop/widgets/mem.go

85 lines
2.1 KiB
Go
Raw Normal View History

2018-02-19 15:25:02 +08:00
package widgets
import (
"fmt"
2020-02-29 00:03:41 +08:00
"log"
2018-02-19 15:25:02 +08:00
"time"
"github.com/prometheus/client_golang/prometheus"
2019-01-31 07:20:09 +08:00
2020-02-29 04:48:35 +08:00
"github.com/xxxserxxx/gotop/v3/devices"
ui "github.com/xxxserxxx/gotop/v3/termui"
"github.com/xxxserxxx/gotop/v3/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
metrics map[string]prometheus.Gauge
2019-05-29 02:43:29 +08:00
}
func NewMemWidget(updateInterval time.Duration, horizontalScale int) *MemWidget {
2019-03-01 08:29:52 +08:00
self := &MemWidget{
LineGraph: ui.NewLineGraph(),
updateInterval: updateInterval,
2018-03-04 09:05:52 +08:00
}
2019-01-01 08:55:50 +08:00
self.Title = " Memory Usage "
2019-01-13 08:31:37 +08:00
self.HorizontalScale = horizontalScale
mems := make(map[string]devices.MemoryInfo)
devices.UpdateMem(mems)
for name, mem := range mems {
2020-02-29 00:03:41 +08:00
log.Printf("setting %s to %v", name, mem)
self.Data[name] = []float64{0}
self.renderMemInfo(name, mem)
}
2018-04-13 11:00:34 +08:00
2018-02-19 15:25:02 +08:00
go func() {
2019-03-01 08:29:52 +08:00
for range time.NewTicker(self.updateInterval).C {
self.Lock()
devices.UpdateMem(mems)
for label, mi := range mems {
2020-02-29 00:03:41 +08:00
log.Printf(" updating %s to %v", label, mi)
self.renderMemInfo(label, mi)
if self.metrics != nil && self.metrics[label] != nil {
self.metrics[label].Set(mi.UsedPercent)
}
}
self.Unlock()
2018-02-19 15:25:02 +08:00
}
}()
2018-03-28 05:27:23 +08:00
return self
2018-02-19 15:25:02 +08:00
}
func (b *MemWidget) EnableMetric() {
b.metrics = make(map[string]prometheus.Gauge)
mems := make(map[string]devices.MemoryInfo)
devices.UpdateMem(mems)
for l, mem := range mems {
b.metrics[l] = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "gotop",
Subsystem: "memory",
Name: l,
})
b.metrics[l].Set(mem.UsedPercent)
prometheus.MustRegister(b.metrics[l])
}
}
func (b *MemWidget) Scale(i int) {
b.LineGraph.HorizontalScale = i
}
func (self *MemWidget) renderMemInfo(line string, memoryInfo devices.MemoryInfo) {
self.Data[line] = append(self.Data[line], memoryInfo.UsedPercent)
memoryTotalBytes, memoryTotalMagnitude := utils.ConvertBytes(memoryInfo.Total)
memoryUsedBytes, memoryUsedMagnitude := utils.ConvertBytes(memoryInfo.Used)
self.Labels[line] = fmt.Sprintf("%3.0f%% %5.1f%s/%.0f%s",
memoryInfo.UsedPercent,
memoryUsedBytes,
memoryUsedMagnitude,
memoryTotalBytes,
memoryTotalMagnitude,
)
}