forked from toolkits/nux
/
cpustat_linux.go
113 lines (97 loc) · 1.8 KB
/
cpustat_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package nux
import (
"bufio"
"bytes"
"io"
"io/ioutil"
"strconv"
"strings"
"github.com/toolkits/file"
)
func CurrentProcStat() (*ProcStat, error) {
f := "/proc/stat"
bs, err := ioutil.ReadFile(f)
if err != nil {
return nil, err
}
ps := &ProcStat{Cpus: make([]*CpuUsage, NumCpu())}
reader := bufio.NewReader(bytes.NewBuffer(bs))
for {
line, err := file.ReadLine(reader)
if err == io.EOF {
err = nil
break
} else if err != nil {
return ps, err
}
parseLine(line, ps)
}
return ps, nil
}
func parseLine(line []byte, ps *ProcStat) {
fields := strings.Fields(string(line))
if len(fields) < 2 {
return
}
fieldName := fields[0]
if fieldName == "cpu" {
ps.Cpu = parseCpuFields(fields)
return
}
if strings.HasPrefix(fieldName, "cpu") {
idx, err := strconv.Atoi(fieldName[3:])
if err != nil || idx >= len(ps.Cpus) {
return
}
ps.Cpus[idx] = parseCpuFields(fields)
return
}
if fieldName == "ctxt" {
ps.Ctxt, _ = strconv.ParseUint(fields[1], 10, 64)
return
}
if fieldName == "processes" {
ps.Processes, _ = strconv.ParseUint(fields[1], 10, 64)
return
}
if fieldName == "procs_running" {
ps.ProcsRunning, _ = strconv.ParseUint(fields[1], 10, 64)
return
}
if fieldName == "procs_blocked" {
ps.ProcsBlocked, _ = strconv.ParseUint(fields[1], 10, 64)
return
}
}
func parseCpuFields(fields []string) *CpuUsage {
cu := new(CpuUsage)
sz := len(fields)
for i := 1; i < sz; i++ {
val, err := strconv.ParseFloat(fields[i], 64)
if err != nil {
continue
}
cu.Total += val
switch i {
case 1:
cu.User = val
case 2:
cu.Nice = val
case 3:
cu.System = val
case 4:
cu.Idle = val
case 5:
cu.Iowait = val
case 6:
cu.Irq = val
case 7:
cu.SoftIrq = val
case 8:
cu.Steal = val
case 9:
cu.Guest = val
}
}
return cu
}