-
Notifications
You must be signed in to change notification settings - Fork 0
/
subtree_oom_darwin.go
92 lines (78 loc) · 1.9 KB
/
subtree_oom_darwin.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
//go:build darwin
// +build darwin
package jasper
import (
"bufio"
"context"
"errors"
"fmt"
"os/exec"
"strings"
"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 {
return exec.CommandContext(ctx, "sudo", "log", "erase", "--all").Run()
}
return exec.CommandContext(ctx, "log", "erase", "--all").Run()
}
func (o *oomTrackerImpl) Check(ctx context.Context) error {
wasOOMKilled, pids, err := analyzeLogs(ctx)
if err != nil {
return fmt.Errorf("error searching log: %w", err)
}
o.WasOOMKilled = wasOOMKilled
o.Pids = pids
return nil
}
func analyzeLogs(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", "log", "show")
} else {
cmd = exec.CommandContext(ctx, "log", "show")
}
cmdReader, err := cmd.StdoutPipe()
if err != nil {
return false, nil, fmt.Errorf("error creating StdoutPipe for log command: %w", err)
}
scanner := bufio.NewScanner(cmdReader)
if err = cmd.Start(); err != nil {
return false, nil, fmt.Errorf("Error starting log 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 strings.Contains(line, "low swap") {
wasOOMKilled = true
if pid, hasPid := getPidFromLog(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("Error waiting for dmesg command: %w", err)
}
}