forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpu.go
105 lines (89 loc) · 2.28 KB
/
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// +build darwin linux openbsd windows
package cpu
import (
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/metricbeat/mb"
system "github.com/elastic/beats/metricbeat/module/system/common"
"github.com/pkg/errors"
)
func init() {
if err := mb.Registry.AddMetricSet("system", "cpu", New); err != nil {
panic(err)
}
}
// MetricSet for fetching system CPU metrics.
type MetricSet struct {
mb.BaseMetricSet
cpu *system.CPU
}
// New is a mb.MetricSetFactory that returns a cpu.MetricSet.
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
config := struct {
CpuTicks bool `config:"cpu_ticks"` // export CPU usage in ticks
}{
CpuTicks: false,
}
if err := base.Module().UnpackConfig(&config); err != nil {
return nil, err
}
return &MetricSet{
BaseMetricSet: base,
cpu: &system.CPU{
CpuTicks: config.CpuTicks,
},
}, nil
}
// Fetch fetches CPU metrics from the OS.
func (m *MetricSet) Fetch() (common.MapStr, error) {
stat, err := system.GetCpuTimes()
if err != nil {
return nil, errors.Wrap(err, "cpu times")
}
m.cpu.AddCpuPercentage(stat)
loadStat, err := system.GetSystemLoad()
if err != nil {
return nil, errors.Wrap(err, "load statistics")
}
cpuStat := common.MapStr{
"user": common.MapStr{
"pct": stat.UserPercent,
},
"system": common.MapStr{
"pct": stat.SystemPercent,
},
"idle": common.MapStr{
"pct": stat.IdlePercent,
},
"iowait": common.MapStr{
"pct": stat.IOwaitPercent,
},
"irq": common.MapStr{
"pct": stat.IrqPercent,
},
"nice": common.MapStr{
"pct": stat.NicePercent,
},
"softirq": common.MapStr{
"pct": stat.SoftIrqPercent,
},
"steal": common.MapStr{
"pct": stat.StealPercent,
},
}
if m.cpu.CpuTicks {
cpuStat["user"].(common.MapStr)["ticks"] = stat.User
cpuStat["system"].(common.MapStr)["ticks"] = stat.Sys
cpuStat["nice"].(common.MapStr)["ticks"] = stat.Nice
cpuStat["idle"].(common.MapStr)["ticks"] = stat.Idle
cpuStat["iowait"].(common.MapStr)["ticks"] = stat.Wait
cpuStat["irq"].(common.MapStr)["ticks"] = stat.Irq
cpuStat["softirq"].(common.MapStr)["ticks"] = stat.SoftIrq
cpuStat["steal"].(common.MapStr)["ticks"] = stat.Stolen
}
cpuStat["load"] = common.MapStr{
"1": loadStat.Load1,
"5": loadStat.Load5,
"15": loadStat.Load15,
}
return cpuStat, nil
}