-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathstats_reader_linux.go
225 lines (187 loc) · 5.29 KB
/
stats_reader_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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// (c) Copyright IBM Corp. 2021
// (c) Copyright Instana Inc. 2020
//go:build linux
// +build linux
package process
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
)
const (
pageSize = 4 << 10 // standard setting, applicable for most systems
procPath = "/proc"
)
type statsReader struct {
ProcPath string
Command string
}
// Stats returns a process resource stats reader for current process
func Stats() statsReader {
return statsReader{
ProcPath: procPath,
Command: path.Base(os.Args[0]),
}
}
// Memory returns memory stats for current process
func (rdr statsReader) Memory() (MemStats, error) {
fd, err := os.Open(rdr.ProcPath + "/self/statm")
if err != nil {
return MemStats{}, nil
}
defer fd.Close()
var total, rss, shared int
// The fields come in order described in `/proc/[pid]/statm` section
// of https://man7.org/linux/man-pages/man5/proc.5.html
if _, err := fmt.Fscanf(fd, "%d %d %d",
&total, // size
&rss, // resident
&shared, // shared
// ... the rest of the fields are not used and thus omitted
); err != nil {
return MemStats{}, fmt.Errorf("failed to parse %s: %s", fd.Name(), err)
}
return MemStats{
Total: total * pageSize,
Rss: rss * pageSize,
Shared: shared * pageSize,
}, nil
}
// CPU returns CPU stats for current process and the CPU tick they were taken on
func (rdr statsReader) CPU() (CPUStats, int, error) {
fd, err := os.Open(rdr.ProcPath + "/self/stat")
if err != nil {
return CPUStats{}, 0, nil
}
defer fd.Close()
var (
stats CPUStats
skipInt int
skipCh byte
)
// The command in `/proc/self/stat` output is truncated to 15 bytes (16 including the terminating null byte)
comm := rdr.Command
if len(comm) > 15 {
comm = comm[:15]
}
// The fields come in order described in `/proc/[pid]/stat` section
// of https://man7.org/linux/man-pages/man5/proc.5.html. We skip parsing
// the `comm` field since it may contain space characters that break fmt.Fscanf format.
if _, err := fmt.Fscanf(fd, "%d ("+comm+") %c %d %d %d %d %d %d %d %d %d %d %d %d",
&skipInt, // pid
&skipCh, // state
&skipInt, // ppid
&skipInt, // pgrp
&skipInt, // session
&skipInt, // tty_nr
&skipInt, // tpgid
&skipInt, // flags
&skipInt, // minflt
&skipInt, // cminflt
&skipInt, // majflt
&skipInt, // cmajflt
&stats.User, // utime
&stats.System, // stime
// ... the rest of the fields are not used and thus omitted
); err != nil {
return stats, 0, fmt.Errorf("failed to parse %s: %s", fd.Name(), err)
}
tick, err := rdr.currentTick()
if err != nil {
return stats, 0, fmt.Errorf("failed to get current CPU tick: %s", err)
}
return stats, tick, nil
}
// currentTick parses /proc/stat, sums up the total number of ticks spent on each CPU and averages them
// by the number of CPUs
func (rdr statsReader) currentTick() (int, error) {
fd, err := os.Open(rdr.ProcPath + "/stat")
if err != nil {
return 0, nil
}
defer fd.Close()
sc := bufio.NewScanner(fd)
sc.Split(bufio.ScanLines)
var (
ticks, cpuCount int
user, nice, sys, idle, iowait, irq, softIRQ, steal int
skipStr string
)
for sc.Scan() {
s := sc.Text()
if !strings.HasPrefix(s, "cpu") {
continue
}
if strings.HasPrefix(s, "cpu ") { // skip total CPU line
continue
}
// The fields come in order described in `/proc/stat` section
// of https://man7.org/linux/man-pages/man5/proc.5.html
if _, err := fmt.Sscanf(s, "%s %d %d %d %d %d %d %d %d",
&skipStr, // CPU label
&user,
&nice,
&sys,
&idle,
&iowait,
&irq,
&softIRQ,
&steal,
// ... the rest of the fields are not used and thus omitted
); err != nil {
return 0, fmt.Errorf("failed to parse %s: %s", fd.Name(), err)
}
ticks += user + nice + sys + idle + iowait + irq + softIRQ + steal
cpuCount++
}
if err := sc.Err(); err != nil {
return 0, fmt.Errorf("failed to read %s: %s", fd.Name(), err)
}
if cpuCount < 2 {
return ticks, nil
}
return ticks / cpuCount, nil
}
// Limits returns resource limits configured for current process
func (rdr statsReader) Limits() (ResourceLimits, error) {
fd, err := os.Open(rdr.ProcPath + "/self/limits")
if err != nil {
return ResourceLimits{}, nil
}
defer fd.Close()
sc := bufio.NewScanner(fd)
sc.Split(bufio.ScanLines)
var limits ResourceLimits
for sc.Scan() {
s := sc.Text()
if !strings.HasPrefix(s, "Max open files") {
continue
}
s = strings.TrimLeft(s[14:], " \t") // trim the "max open files" prefix along with trailing space
if !strings.HasPrefix(s, "unlimited") {
if _, err := fmt.Sscanf(s, "%d", &limits.OpenFiles.Max); err != nil {
return limits, fmt.Errorf("unexpected %s format: %s", fd.Name(), err)
}
}
break
}
if err := sc.Err(); err != nil {
return limits, fmt.Errorf("failed to read %s: %s", fd.Name(), err)
}
fdNum, err := rdr.currentOpenFiles()
if err != nil {
return limits, fmt.Errorf("failed to get the number of open files: %s", err)
}
limits.OpenFiles.Current = fdNum
return limits, nil
}
func (rdr statsReader) currentOpenFiles() (int, error) {
fds, err := ioutil.ReadDir(rdr.ProcPath + "/self/fd/")
if err != nil {
return 0, fmt.Errorf("failed to list %s: %s", rdr.ProcPath+"/fd/", err)
}
return len(fds), nil
}