diff options
Diffstat (limited to 'widgets/cpu.go')
-rw-r--r-- | widgets/cpu.go | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/widgets/cpu.go b/widgets/cpu.go index 8e8819c..37c4220 100644 --- a/widgets/cpu.go +++ b/widgets/cpu.go @@ -1,11 +1,13 @@ package widgets import ( + "context" "fmt" "log" "sync" "time" + "github.com/prometheus/client_golang/prometheus" psCpu "github.com/shirou/gopsutil/cpu" ui "github.com/xxxserxxx/gotop/termui" @@ -19,6 +21,7 @@ type CpuWidget struct { updateInterval time.Duration formatString string updateLock sync.Mutex + metric []prometheus.Gauge } func NewCpuWidget(updateInterval time.Duration, horizontalScale int, showAverageLoad bool, showPerCpuLoad bool) *CpuWidget { @@ -71,6 +74,35 @@ func NewCpuWidget(updateInterval time.Duration, horizontalScale int, showAverage return self } +func (self *CpuWidget) EnableMetric() { + if self.ShowAverageLoad { + self.metric = make([]prometheus.Gauge, 1) + self.metric[0] = prometheus.NewGauge(prometheus.GaugeOpts{ + Subsystem: "cpu", + Name: "avg", + }) + } else { + ctx, ccl := context.WithTimeout(context.Background(), time.Second*5) + defer ccl() + percents, err := psCpu.PercentWithContext(ctx, self.updateInterval, true) + if err != nil { + log.Printf("error setting up metrics: %v", err) + return + } + self.metric = make([]prometheus.Gauge, self.CpuCount) + for i, perc := range percents { + gauge := prometheus.NewGauge(prometheus.GaugeOpts{ + Namespace: "gotop", + Subsystem: "cpu", + Name: fmt.Sprintf("%d", i), + }) + gauge.Set(perc) + prometheus.MustRegister(gauge) + self.metric[i] = gauge + } + } +} + func (b *CpuWidget) Scale(i int) { b.LineGraph.HorizontalScale = i } @@ -88,6 +120,9 @@ func (self *CpuWidget) update() { defer self.updateLock.Unlock() self.Data["AVRG"] = append(self.Data["AVRG"], percent[0]) self.Labels["AVRG"] = fmt.Sprintf("%3.0f%%", percent[0]) + if self.metric != nil { + self.metric[0].Set(percent[0]) + } } }() } @@ -109,6 +144,13 @@ func (self *CpuWidget) update() { key := fmt.Sprintf(self.formatString, i) self.Data[key] = append(self.Data[key], percent) self.Labels[key] = fmt.Sprintf("%3.0f%%", percent) + if self.metric != nil { + if self.metric[i] == nil { + log.Printf("ERROR: not enough metrics %d", i) + } else { + self.metric[i].Set(percent) + } + } } } } |