diff options
author | Sean E. Russell <ser@ser1.net> | 2020-02-27 16:13:23 -0600 |
---|---|---|
committer | Sean E. Russell <ser@ser1.net> | 2020-02-27 16:13:23 -0600 |
commit | 4fce1654c5c263797205997e7635c7d06c393a85 (patch) | |
tree | 06a0e382b9cfc292d978d45033f26aaaaa28fa12 /widgets/cpu.go | |
parent | e38f6fc8c488ed9379efc32060be18f45b18329b (diff) | |
parent | a5b039cd923270683a777c7e3851116076a663e9 (diff) |
Merge branch 'v3.4.x' into nvidia
Diffstat (limited to 'widgets/cpu.go')
-rw-r--r-- | widgets/cpu.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/widgets/cpu.go b/widgets/cpu.go index 937aa8f..c0f25bc 100644 --- a/widgets/cpu.go +++ b/widgets/cpu.go @@ -1,12 +1,16 @@ package widgets import ( + "context" "fmt" "log" "sync" "time" + "github.com/prometheus/client_golang/prometheus" + psCpu "github.com/shirou/gopsutil/cpu" "github.com/xxxserxxx/gotop/devices" + ui "github.com/xxxserxxx/gotop/termui" ) @@ -18,6 +22,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 { @@ -70,6 +75,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 } @@ -87,6 +121,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]) + } } }() } @@ -108,6 +145,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) + } + } } } } |