-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocess_linux.go
More file actions
423 lines (389 loc) · 9.97 KB
/
Copy pathprocess_linux.go
File metadata and controls
423 lines (389 loc) · 9.97 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//go:build linux
package vminfo
import (
"bufio"
"bytes"
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/shirou/gopsutil/v3/process"
"github.com/tklauser/go-sysconf"
)
const (
processTerminateTimeout = 3 * time.Second
procListWorkers = 32
)
// procClockTicks resolves _SC_CLK_TCK once. Falls back to 100 (x86_64
// default) if sysconf fails. Some kernels use 250 or 1000 (CONFIG_HZ),
// so a hardcode breaks CPU% on ARM and embedded hosts.
var procClockTicks = func() int64 {
v, err := sysconf.Sysconf(sysconf.SC_CLK_TCK)
if err != nil || v <= 0 {
return 100
}
return v
}()
func listProcesses(ctx context.Context) ([]ProcessInfo, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
pids, err := readProcPids()
if err != nil {
return nil, err
}
systemUptime, _ := readProcUptime()
memTotal, _ := readMemTotalBytes()
users := readPasswdMap()
type result struct {
info ProcessInfo
ok bool
}
jobs := make(chan int32, len(pids))
out := make(chan result, len(pids))
var wg sync.WaitGroup
workers := min(procListWorkers, len(pids))
for range workers {
wg.Go(func() {
for pid := range jobs {
if info, ok := readProcEntry(pid, systemUptime, memTotal, users); ok {
out <- result{info: info, ok: true}
}
}
})
}
for _, pid := range pids {
jobs <- pid
}
close(jobs)
wg.Wait()
close(out)
items := make([]ProcessInfo, 0, len(pids))
for r := range out {
items = append(items, r.info)
}
return items, nil
}
func readProcEntry(pid int32, systemUptime float64, memTotal uint64, users map[uint32]string) (ProcessInfo, bool) {
stat, ok := readProcStat(pid)
if !ok {
return ProcessInfo{}, false
}
rssBytes := readProcRSSBytes(pid)
userName := ""
if uid, ok := readProcUID(pid); ok {
userName = lookupUser(uid, users)
}
command := firstNonEmptyString(readProcCommandLine(pid), stat.comm)
clkTck := float64(procClockTicks)
procUptimeSecs := systemUptime - float64(stat.starttime)/clkTck
cpuPercent := 0.0
if procUptimeSecs > 0 {
totalSecs := float64(stat.utime+stat.stime) / clkTck
cpuPercent = totalSecs / procUptimeSecs * 100
}
memPercent := float32(0)
if memTotal > 0 {
memPercent = float32(float64(rssBytes) / float64(memTotal) * 100)
}
uptime := uint64(0)
if procUptimeSecs > 0 {
uptime = uint64(procUptimeSecs)
}
startedAtUnix := int64(0)
if systemUptime > 0 && procUptimeSecs > 0 {
startedAtUnix = time.Now().Add(-time.Duration(procUptimeSecs * float64(time.Second))).Unix()
}
return ProcessInfo{
PID: pid,
PPID: stat.ppid,
Name: stat.comm,
Command: command,
User: userName,
State: stat.state,
CPUPercent: cpuPercent,
MemoryPercent: memPercent,
RSSBytes: rssBytes,
Threads: stat.numThreads,
Nice: stat.nice,
Uptime: uptime,
StartedAtUnix: startedAtUnix,
}, true
}
func readProcPids() ([]int32, error) {
entries, err := os.ReadDir("/proc")
if err != nil {
return nil, err
}
pids := make([]int32, 0, len(entries))
for _, e := range entries {
if !e.IsDir() {
continue
}
name := e.Name()
if name[0] < '0' || name[0] > '9' {
continue
}
v, err := strconv.ParseInt(name, 10, 32)
if err != nil || v <= 0 {
continue
}
pids = append(pids, int32(v))
}
return pids, nil
}
type procStat struct {
comm string
state string
ppid int32
numThreads int32
nice int32
utime uint64
stime uint64
starttime uint64
}
// readProcStat parses /proc/<pid>/stat. Format:
// pid (comm) state ppid pgrp session tty_nr tpgid flags minflt cminflt
// majflt cmajflt utime(14) stime(15) cutime cstime priority nice(19)
// num_threads(20) itrealvalue starttime(22) ...
func readProcStat(pid int32) (procStat, bool) {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
if err != nil {
return procStat{}, false
}
rOpen := bytes.IndexByte(data, '(')
rClose := bytes.LastIndexByte(data, ')')
if rOpen < 0 || rClose < 0 || rClose <= rOpen {
return procStat{}, false
}
comm := string(data[rOpen+1 : rClose])
rest := data[rClose+2:] // skip ") "
fields := bytes.Fields(rest)
if len(fields) < 20 {
return procStat{}, false
}
// fields[0] = state, [1] = ppid, [11] = utime, [12] = stime,
// [16] = nice, [17] = num_threads, [19] = starttime
s := procStat{comm: comm, state: string(fields[0])}
if v, err := strconv.ParseInt(string(fields[1]), 10, 32); err == nil {
s.ppid = int32(v)
}
if v, err := strconv.ParseUint(string(fields[11]), 10, 64); err == nil {
s.utime = v
}
if v, err := strconv.ParseUint(string(fields[12]), 10, 64); err == nil {
s.stime = v
}
if v, err := strconv.ParseInt(string(fields[16]), 10, 32); err == nil {
s.nice = int32(v)
}
if v, err := strconv.ParseInt(string(fields[17]), 10, 32); err == nil {
s.numThreads = int32(v)
}
if v, err := strconv.ParseUint(string(fields[19]), 10, 64); err == nil {
s.starttime = v
}
return s, true
}
// readProcRSSBytes parses /proc/<pid>/statm — fields are pages.
// Format: size resident shared text lib data dt
func readProcRSSBytes(pid int32) uint64 {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/statm", pid))
if err != nil {
return 0
}
fields := bytes.Fields(data)
if len(fields) < 2 {
return 0
}
pages, err := strconv.ParseUint(string(fields[1]), 10, 64)
if err != nil {
return 0
}
return pages * uint64(os.Getpagesize())
}
// readProcCommandLine parses /proc/<pid>/cmdline into a displayable command
// line. Kernel threads and short-lived processes often have an empty or
// unreadable cmdline; callers should fall back to comm in those cases.
func readProcCommandLine(pid int32) string {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
if err != nil {
return ""
}
data = bytes.TrimRight(data, "\x00")
if len(data) == 0 {
return ""
}
parts := bytes.Split(data, []byte{0})
values := make([]string, 0, len(parts))
for _, part := range parts {
part = bytes.TrimSpace(part)
if len(part) == 0 {
continue
}
values = append(values, string(part))
}
return strings.Join(values, " ")
}
// readProcUID parses /proc/<pid>/status for the real UID (Uid: line).
func readProcUID(pid int32) (uint32, bool) {
data, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
if err != nil {
return 0, false
}
idx := bytes.Index(data, []byte("\nUid:"))
if idx < 0 {
if !bytes.HasPrefix(data, []byte("Uid:")) {
return 0, false
}
idx = -1
}
rest := data[idx+1:] // skip newline (or use full when prefix)
end := bytes.IndexByte(rest, '\n')
if end < 0 {
end = len(rest)
}
line := rest[:end]
fields := bytes.Fields(line)
if len(fields) < 2 {
return 0, false
}
v, err := strconv.ParseUint(string(fields[1]), 10, 32)
if err != nil {
return 0, false
}
return uint32(v), true
}
// readProcUptime returns system uptime in seconds.
func readProcUptime() (float64, error) {
data, err := os.ReadFile("/proc/uptime")
if err != nil {
return 0, err
}
fields := bytes.Fields(data)
if len(fields) == 0 {
return 0, fmt.Errorf("empty uptime")
}
return strconv.ParseFloat(string(fields[0]), 64)
}
// readMemTotalBytes returns MemTotal from /proc/meminfo.
func readMemTotalBytes() (uint64, error) {
f, err := os.Open("/proc/meminfo")
if err != nil {
return 0, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "MemTotal:") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
return 0, fmt.Errorf("malformed MemTotal")
}
kb, err := strconv.ParseUint(fields[1], 10, 64)
if err != nil {
return 0, err
}
return kb * 1024, nil
}
if err := scanner.Err(); err != nil {
return 0, err
}
return 0, fmt.Errorf("MemTotal not found")
}
// readPasswdMap returns uid → username from /etc/passwd. On error, empty map.
func readPasswdMap() map[uint32]string {
f, err := os.Open("/etc/passwd")
if err != nil {
return map[uint32]string{}
}
defer f.Close()
m := make(map[uint32]string, 64)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, ":", 4)
if len(parts) < 3 {
continue
}
uid, err := strconv.ParseUint(parts[2], 10, 32)
if err != nil {
continue
}
if _, exists := m[uint32(uid)]; !exists {
m[uint32(uid)] = parts[0]
}
}
// Best-effort lookup: return entries parsed before any read error or
// oversize line rather than dropping the whole map.
_ = scanner.Err()
return m
}
// lookupUser resolves uid from the local passwd snapshot. Avoiding NSS here
// keeps process collection bounded when remote identity providers are slow.
func lookupUser(uid uint32, cached map[uint32]string) string {
if name, ok := cached[uid]; ok && name != "" {
return name
}
return strconv.FormatUint(uint64(uid), 10)
}
func firstNonEmptyString(values ...string) string {
for _, value := range values {
value = strings.TrimSpace(value)
if value != "" {
return value
}
}
return ""
}
func terminateProcess(ctx context.Context, pid int32) error {
if pid <= 0 {
return fmt.Errorf("invalid pid")
}
if pid == 1 {
return fmt.Errorf("refuse to terminate pid 1")
}
if pid == int32(os.Getpid()) {
return fmt.Errorf("refuse to terminate current process")
}
procItem, err := process.NewProcessWithContext(ctx, pid)
if err != nil {
return err
}
if err := procItem.TerminateWithContext(ctx); err != nil {
return err
}
return waitProcessStopped(ctx, procItem, processTerminateTimeout)
}
func waitProcessStopped(ctx context.Context, procItem *process.Process, timeout time.Duration) error {
if procItem == nil {
return nil
}
if timeout <= 0 {
timeout = processTerminateTimeout
}
waitCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
running, err := procItem.IsRunningWithContext(waitCtx)
if err != nil {
return err
}
if !running {
return nil
}
select {
case <-waitCtx.Done():
return fmt.Errorf("process %d did not exit after SIGTERM", procItem.Pid)
case <-ticker.C:
}
}
}