-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathi_cpu.go
85 lines (71 loc) · 1.78 KB
/
i_cpu.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
package main
import (
"os/exec"
"strings"
"strconv"
"time"
"fmt"
)
type CPUStats struct {
ps PS
PerCPU bool `toml:"percpu"`
TotalCPU bool `toml:"totalcpu"`
CollectCPUTime bool `toml:"collect_cpu_time"`
ReportActive bool `toml:"report_active"`
}
func NewCPUStats(ps PS) *CPUStats {
return &CPUStats{
ps: ps,
CollectCPUTime: true,
ReportActive: true,
}
}
func (_ *CPUStats) Description() string {
return "Read metrics about cpu usage"
}
var sampleConfig = `
## Whether to report per-cpu stats or not
percpu = true
## Whether to report total system cpu stats or not
totalcpu = true
## If true, collect raw CPU time metrics.
collect_cpu_time = false
## If true, compute and report the sum of all non-idle CPU states.
report_active = false
`
func (_ *CPUStats) SampleConfig() string {
return sampleConfig
}
func (s *CPUStats) Gather(acc Accumulator) error {
output, err := exec.Command("/usr/bin/vmstat", "-S", "1", "2").CombinedOutput()
if err != nil {
return fmt.Errorf("error getting CPU info: %s", err.Error())
}
now := time.Now()
stats := string(output)
rows := strings.Split(stats, "\n")
rows = rows[1:]
data := make(map[string]float64)
headers := strings.Fields(rows[0])
values := strings.Fields(rows[2])
for count := 0; count < len(headers); count++ {
v, _ := strconv.ParseFloat(values[count], 64)
data[headers[count]] = v
}
tags := map[string]string{
"cpu": "cpu-total",
}
fieldsC := map[string]interface{}{
"usage_idle": data["id"],
"usage_system": data["sy"],
"usage_user": data["us"],
}
acc.AddCounter("cpu", fieldsC, tags, now)
// Task
fields := map[string]interface{}{
"cswch_per_s": data["cs"],
"proc_per_s": data["sy"],
}
acc.AddCounter("task", fields, nil, now)
return nil
}