/
cpu_linux.go
92 lines (84 loc) · 2.35 KB
/
cpu_linux.go
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
package collector
import (
"fmt"
//"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs"
)
const (
cpuCollectorSubsystem = "cpu"
)
var (
nodeCPUSecondsDesc = prometheus.NewDesc(
prometheus.BuildFQName(namespace, cpuCollectorSubsystem, "usage"),
"Usage of the cpus in 100ms.",
[]string{"intervel"}, nil,
)
)
type cpuCollector struct {
fs procfs.FS
cpu *prometheus.Desc
}
func NewCPUCollector() (Collector, error) {
fs, err := procfs.NewFS("/proc") // proc: default path
if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err)
}
return &cpuCollector{
fs: fs,
cpu: nodeCPUSecondsDesc,
}, nil
}
func (c *cpuCollector) Update(ch chan<- prometheus.Metric) error {
if err := c.updateStat(ch); err != nil {
return err
}
return nil
}
func (c *cpuCollector) updateStat(ch chan<- prometheus.Metric) error {
statsS, err := c.fs.Stat()
if err != nil {
return err
}
time.Sleep(100000000)
statsE, err := c.fs.Stat()
if err != nil {
return err
}
if len(statsE.CPU) < len(statsS.CPU) {
return nil
}
var totalUsage, len float64
for cpuID, cpuStatS := range statsS.CPU {
cpuStatE := statsE.CPU[cpuID]
totalS := cpuStatS.User + cpuStatS.Nice + cpuStatS.System + cpuStatS.Idle + cpuStatS.Iowait + cpuStatS.IRQ + cpuStatS.SoftIRQ
totalE := cpuStatE.User + cpuStatE.Nice + cpuStatE.System + cpuStatE.Idle + cpuStatE.Iowait + cpuStatE.IRQ + cpuStatE.SoftIRQ
var usage float64
if cpuStatE.Idle == cpuStatS.Idle {
usage = 0
} else {
usage = 100 - (cpuStatE.Idle-cpuStatS.Idle)/(totalE-totalS)*100
}
totalUsage += usage
len += 1
}
totalUsage /= len
ch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, totalUsage, "100ms")
/*
for cpuID, cpuStatS := range statsS.CPU {
cpuStatE := statsE.CPU[cpuID]
cpuNum := strconv.Itoa(cpuID)
totalS := cpuStatS.User + cpuStatS.Nice + cpuStatS.System + cpuStatS.Idle + cpuStatS.Iowait + cpuStatS.IRQ + cpuStatS.SoftIRQ
totalE := cpuStatE.User + cpuStatE.Nice + cpuStatE.System + cpuStatE.Idle + cpuStatE.Iowait + cpuStatE.IRQ + cpuStatE.SoftIRQ
var usage float64
if cpuStatE.Idle == cpuStatS.Idle {
usage = 0
} else {
usage = 100 - (cpuStatE.Idle-cpuStatS.Idle)/(totalE-totalS)*100
}
ch <- prometheus.MustNewConstMetric(c.cpu, prometheus.CounterValue, usage, cpuNum, "100ms")
}
*/
return nil
}