-
Notifications
You must be signed in to change notification settings - Fork 0
/
subtree_oom_linux.go
97 lines (82 loc) · 1.99 KB
/
subtree_oom_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
//go:build linux
// +build linux
package jasper
import (
"bufio"
"context"
"errors"
"fmt"
"os/exec"
"github.com/tychoish/grip/recovery"
)
func (o *oomTrackerImpl) Clear(ctx context.Context) error {
sudo, err := isSudo(ctx)
if err != nil {
return fmt.Errorf("error checking sudo: %w", err)
}
if sudo {
if err := exec.CommandContext(ctx, "sudo", "dmesg", "-c").Run(); err != nil {
return fmt.Errorf("closing dmesg: %w", err)
}
}
if err := exec.CommandContext(ctx, "dmesg", "-c").Run(); err != nil {
return fmt.Errorf("closing dmesg: %w", err)
}
return nil
}
func (o *oomTrackerImpl) Check(ctx context.Context) error {
wasOOMKilled, pids, err := analyzeDmesg(ctx)
if err != nil {
return fmt.Errorf("error searching log: %w", err)
}
o.WasOOMKilled = wasOOMKilled
o.Pids = pids
return nil
}
func analyzeDmesg(ctx context.Context) (bool, []int, error) {
var cmd *exec.Cmd
wasOOMKilled := false
errs := make(chan error)
sudo, err := isSudo(ctx)
if err != nil {
return false, nil, fmt.Errorf("error checking sudo: %w", err)
}
if sudo {
cmd = exec.CommandContext(ctx, "sudo", "dmesg")
} else {
cmd = exec.CommandContext(ctx, "dmesg")
}
cmdReader, err := cmd.StdoutPipe()
if err != nil {
return false, nil, fmt.Errorf("error creating StdoutPipe for dmesg command: %w", err)
}
scanner := bufio.NewScanner(cmdReader)
if err = cmd.Start(); err != nil {
return false, nil, fmt.Errorf("starting dmesg command: %w", err)
}
go func() {
defer recovery.LogStackTraceAndContinue("log analysis")
select {
case <-ctx.Done():
return
case errs <- cmd.Wait():
return
}
}()
pids := []int{}
for scanner.Scan() {
line := scanner.Text()
if dmesgContainsOOMKill(line) {
wasOOMKilled = true
if pid, hasPid := getPidFromDmesg(line); hasPid {
pids = append(pids, pid)
}
}
}
select {
case <-ctx.Done():
return false, nil, errors.New("request cancelled")
case err = <-errs:
return wasOOMKilled, pids, fmt.Errorf("waiting for dmesg command: %w", err)
}
}