forked from pingcap/sysutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystem_info.go
129 lines (120 loc) · 2.57 KB
/
system_info.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package sysutil
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
pb "github.com/pingcap/kvproto/pkg/diagnosticspb"
"github.com/shirou/gopsutil/process"
)
func tryProcFs() []*pb.ServerInfoItem {
const dir = "/proc/sys/"
item := &pb.ServerInfoItem{
Tp: "system",
Name: "sysctl",
}
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
content, err := ioutil.ReadFile(path)
// Ignore this file
if err != nil {
return nil
}
item.Pairs = append(item.Pairs, &pb.ServerInfoPair{
Key: strings.ReplaceAll(strings.TrimPrefix(path, dir), "/", "."),
Value: string(content),
})
return nil
})
if err != nil {
return nil
}
return []*pb.ServerInfoItem{item}
}
func getSystemInfo() []*pb.ServerInfoItem {
if results := tryProcFs(); len(results) > 0 {
return results
}
// fallback to command line
cmd := exec.Command("sysctl", "-a")
out, err := cmd.CombinedOutput()
if err != nil {
return nil
}
buf := bytes.NewBuffer(out)
reader := bufio.NewReader(buf)
pairs := make([]*pb.ServerInfoPair, 0, 2048)
for {
l, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
break
}
return nil
}
kv := strings.Split(string(l), ":")
if len(kv) >= 2 {
pairs = append(pairs, &pb.ServerInfoPair{
Key: kv[0],
Value: strings.TrimSpace(kv[1]),
})
}
}
var results []*pb.ServerInfoItem
results = append(results, &pb.ServerInfoItem{
Tp: "system",
Name: "sysctl",
Pairs: pairs,
})
return results
}
// TODO: use different `ServerInfoType` to collect process list
func getProcessList() []*pb.ServerInfoItem {
var results []*pb.ServerInfoItem
pids, err := process.Pids()
if err != nil {
return results
}
for _, pid := range pids {
p, err := process.NewProcess(pid)
if err != nil {
continue
}
name, err := p.Name()
if err != nil {
continue
}
prop := func(fn func() (string, error)) string {
s, _ := fn()
return s
}
ct, err := p.CreateTime()
if err != nil {
continue
}
us, err := p.CPUPercent()
if err != nil {
continue
}
results = append(results, &pb.ServerInfoItem{
Tp: "process",
Name: fmt.Sprintf("%s(%d)", name, pid),
Pairs: []*pb.ServerInfoPair{
{Key: "executable", Value: prop(p.Exe)},
{Key: "cmd", Value: prop(p.Cmdline)},
{Key: "cwd", Value: prop(p.Cwd)},
{Key: "start-time", Value: fmt.Sprintf("%d", ct)},
{Key: "status", Value: prop(p.Status)},
{Key: "cpu-usage", Value: fmt.Sprintf("%.2f", us)},
},
})
}
return results
}