forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
system.go
106 lines (86 loc) · 1.94 KB
/
system.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
106
package system
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/load"
)
type SystemStats struct{}
func (_ *SystemStats) Description() string {
return "Read metrics about system load & uptime"
}
func (_ *SystemStats) SampleConfig() string {
return `
## Uncomment to remove deprecated metrics.
# fielddrop = ["uptime_format"]
`
}
func (_ *SystemStats) Gather(acc telegraf.Accumulator) error {
loadavg, err := load.Avg()
if err != nil && !strings.Contains(err.Error(), "not implemented") {
return err
}
numCPUs, err := cpu.Counts(true)
if err != nil {
return err
}
fields := map[string]interface{}{
"load1": loadavg.Load1,
"load5": loadavg.Load5,
"load15": loadavg.Load15,
"n_cpus": numCPUs,
}
users, err := host.Users()
if err == nil {
fields["n_users"] = len(users)
} else if os.IsNotExist(err) {
log.Printf("D! [inputs.system] Error reading users: %v", err)
} else if os.IsPermission(err) {
log.Printf("D! [inputs.system] %v", err)
}
now := time.Now()
acc.AddGauge("system", fields, nil, now)
uptime, err := host.Uptime()
if err != nil {
return err
}
acc.AddCounter("system", map[string]interface{}{
"uptime": uptime,
}, nil, now)
acc.AddFields("system", map[string]interface{}{
"uptime_format": formatUptime(uptime),
}, nil, now)
return nil
}
func formatUptime(uptime uint64) string {
buf := new(bytes.Buffer)
w := bufio.NewWriter(buf)
days := uptime / (60 * 60 * 24)
if days != 0 {
s := ""
if days > 1 {
s = "s"
}
fmt.Fprintf(w, "%d day%s, ", days, s)
}
minutes := uptime / 60
hours := minutes / 60
hours %= 24
minutes %= 60
fmt.Fprintf(w, "%2d:%02d", hours, minutes)
w.Flush()
return buf.String()
}
func init() {
inputs.Add("system", func() telegraf.Input {
return &SystemStats{}
})
}