This repository has been archived by the owner on Jun 2, 2023. It is now read-only.
/
shell.go
150 lines (125 loc) · 3.29 KB
/
shell.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
package executors
import (
"bufio"
"context"
"fmt"
"io"
"os/exec"
"strconv"
"strings"
"time"
"github.com/golangci/golangci-worker/app/analytics"
"github.com/shirou/gopsutil/process"
)
type shell struct {
envStore
wd string
}
func newShell(workDir string) *shell {
return &shell{
wd: workDir,
envStore: *newEnvStore(),
}
}
func trackMemoryEveryNSeconds(ctx context.Context, name string, pid int) {
rssValues := []uint64{}
ticker := time.NewTicker(100 * time.Millisecond)
for {
p, _ := process.NewProcess(int32(pid))
mi, err := p.MemoryInfoWithContext(ctx)
if err != nil {
analytics.Log(ctx).Debugf("Can't fetch memory info on subprocess: %s", err)
return
}
rssValues = append(rssValues, mi.RSS)
stop := false
select {
case <-ctx.Done():
stop = true
case <-ticker.C: // track every second
}
if stop {
break
}
}
var avg, max uint64
for _, v := range rssValues {
avg += v
if v > max {
max = v
}
}
avg /= uint64(len(rssValues))
const MB = 1024 * 1024
maxMB := float64(max) / MB
if maxMB >= 10 {
analytics.Log(ctx).Infof("Subprocess %q memory: got %d rss values, avg is %.1fMB, max is %.1fMB",
name, len(rssValues), float64(avg)/MB, maxMB)
}
}
func (s shell) wait(ctx context.Context, name string, childPid int, outReader io.Reader) []string {
trackCtx, cancel := context.WithCancel(ctx)
defer cancel()
go trackMemoryEveryNSeconds(trackCtx, name, childPid)
scanner := bufio.NewScanner(outReader)
lines := []string{}
for scanner.Scan() {
line := scanner.Text()
analytics.Log(ctx).Debugf("%s", line)
lines = append(lines, line)
}
if err := scanner.Err(); err != nil {
analytics.Log(ctx).Warnf("Out lines scanning error: %s", err)
}
return lines
}
func (s shell) Run(ctx context.Context, name string, args ...string) (string, error) {
for i := range args {
unquotedArg, err := strconv.Unquote(args[i])
if err == nil {
args[i] = unquotedArg
}
}
startedAt := time.Now()
pid, outReader, finish, err := s.runAsync(ctx, name, args...)
if err != nil {
return "", err
}
endCh := make(chan struct{})
defer close(endCh)
go func() {
select {
case <-ctx.Done():
analytics.Log(ctx).Warnf("Closing shell reader on timeout")
if cerr := outReader.Close(); cerr != nil {
analytics.Log(ctx).Warnf("Failed to close shell reader on deadline: %s", cerr)
}
case <-endCh:
}
}()
lines := s.wait(ctx, name, pid, outReader)
err = finish()
logger := analytics.Log(ctx).Debugf
if err != nil {
logger = analytics.Log(ctx).Infof
}
logger("shell[%s]: %s %v executed for %s: %v", s.wd, name, args, time.Since(startedAt), err)
// XXX: it's important to not change error here, because it holds exit code
return strings.Join(lines, "\n"), err
}
type finishFunc func() error
func (s shell) runAsync(ctx context.Context, name string, args ...string) (int, io.ReadCloser, finishFunc, error) {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = s.env
cmd.Dir = s.wd
outReader, err := cmd.StdoutPipe()
if err != nil {
return 0, nil, nil, fmt.Errorf("can't make out pipe: %s", err)
}
cmd.Stderr = cmd.Stdout // Set the same pipe
if err := cmd.Start(); err != nil {
return 0, nil, nil, err
}
// XXX: it's important to not change error here, because it holds exit code
return cmd.Process.Pid, outReader, cmd.Wait, nil
}