-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathexecutor.go
272 lines (208 loc) · 5.99 KB
/
executor.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
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
package executor
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"os/exec"
"strings"
"syscall"
"time"
"github.com/deckhouse/deckhouse/pkg/log"
utils "github.com/flant/shell-operator/pkg/utils/labels"
)
func Run(cmd *exec.Cmd) error {
// TODO context: hook name, hook phase, hook binding
// TODO observability
log.Debug("Executing command", slog.String("command", strings.Join(cmd.Args, " ")), slog.String("dir", cmd.Dir))
return cmd.Run()
}
type Executor struct {
cmd *exec.Cmd
logProxyHookJSON bool
proxyJsonKey string
logger *log.Logger
}
func (e *Executor) WithLogProxyHookJSON(logProxyHookJSON bool) *Executor {
e.logProxyHookJSON = logProxyHookJSON
return e
}
func (e *Executor) WithLogProxyHookJSONKey(logProxyHookJSONKey string) *Executor {
if logProxyHookJSONKey == "" {
return e
}
e.proxyJsonKey = logProxyHookJSONKey
return e
}
func (e *Executor) WithLogger(logger *log.Logger) *Executor {
e.logger = logger
return e
}
func (e *Executor) WithCMDStdout(w io.Writer) *Executor {
e.cmd.Stdout = w
return e
}
func (e *Executor) WithCMDStderr(w io.Writer) *Executor {
e.cmd.Stderr = w
return e
}
func NewExecutor(dir string, entrypoint string, args []string, envs []string) *Executor {
cmd := exec.Command(entrypoint, args...)
cmd.Env = append(cmd.Env, envs...)
cmd.Dir = dir
ex := &Executor{
cmd: cmd,
proxyJsonKey: "proxyJsonLog",
logger: log.NewLogger(log.Options{}).Named("auto-executor"),
}
return ex
}
func (e *Executor) Output() ([]byte, error) {
e.logger.Debug("Executing command",
slog.String("command", strings.Join(e.cmd.Args, " ")),
slog.String("dir", e.cmd.Dir))
return e.cmd.Output()
}
type CmdUsage struct {
Sys time.Duration
User time.Duration
MaxRss int64
}
func (e *Executor) RunAndLogLines(logLabels map[string]string) (*CmdUsage, error) {
stdErr := bytes.NewBuffer(nil)
logEntry := utils.EnrichLoggerWithLabels(e.logger, logLabels)
stdoutLogEntry := logEntry.With("output", "stdout")
stderrLogEntry := logEntry.With("output", "stderr")
log.Debug("Executing command",
slog.String("command", strings.Join(e.cmd.Args, " ")),
slog.String("dir", e.cmd.Dir))
plo := &proxyLogger{e.logProxyHookJSON, e.proxyJsonKey, stdoutLogEntry, make([]byte, 0)}
ple := &proxyLogger{e.logProxyHookJSON, e.proxyJsonKey, stderrLogEntry, make([]byte, 0)}
e.cmd.Stdout = plo
e.cmd.Stderr = io.MultiWriter(ple, stdErr)
err := e.cmd.Run()
if err != nil {
if len(stdErr.Bytes()) > 0 {
return nil, fmt.Errorf("stderr: %s", stdErr.String())
}
return nil, fmt.Errorf("cmd run: %w", err)
}
var usage *CmdUsage
if e.cmd.ProcessState != nil {
usage = &CmdUsage{
Sys: e.cmd.ProcessState.SystemTime(),
User: e.cmd.ProcessState.UserTime(),
}
// FIXME Maxrss is Unix specific.
sysUsage := e.cmd.ProcessState.SysUsage()
if v, ok := sysUsage.(*syscall.Rusage); ok {
// v.Maxrss is int32 on arm/v7
usage.MaxRss = int64(v.Maxrss) //nolint:unconvert
}
}
return usage, nil
}
type proxyLogger struct {
logProxyHookJSON bool
proxyJsonLogKey string
logger *log.Logger
buf []byte
}
func (pl *proxyLogger) Write(p []byte) (int, error) {
if !pl.logProxyHookJSON {
pl.writerScanner(p)
return len(p), nil
}
// join all parts of json
pl.buf = append(pl.buf, p...)
var line interface{}
err := json.Unmarshal(pl.buf, &line)
if err != nil {
if err.Error() == "unexpected end of JSON input" {
return len(p), nil
}
pl.logger.Debug("output is not json", log.Err(err))
pl.writerScanner(p)
return len(p), nil
}
logMap, ok := line.(map[string]interface{})
defer func() {
pl.buf = []byte{}
}()
if !ok {
pl.logger.Debug("json log line not map[string]interface{}", slog.Any("line", line))
// fall back to using the logger
pl.logger.Info(string(p))
return len(p), nil
}
// logEntry.Log(log.FatalLevel, string(logLine))
pl.mergeAndLogInputLog(context.TODO(), logMap, "hook")
return len(p), nil
}
func (pl *proxyLogger) writerScanner(p []byte) {
scanner := bufio.NewScanner(bytes.NewReader(p))
// Set the buffer size to the maximum token size to avoid buffer overflows
scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize)
// Define a split function to split the input into chunks of up to 64KB
chunkSize := bufio.MaxScanTokenSize // 64KB
splitFunc := func(data []byte, atEOF bool) (int, []byte, error) {
if len(data) >= chunkSize {
return chunkSize, data[:chunkSize], nil
}
return bufio.ScanLines(data, atEOF)
}
// Use the custom split function to split the input
scanner.Split(splitFunc)
// Scan the input and write it to the logger using the specified print function
for scanner.Scan() {
// prevent empty logging
str := strings.TrimSpace(scanner.Text())
if str == "" {
continue
}
if len(str) > 10000 {
str = fmt.Sprintf("%s:truncated", str[:10000])
}
pl.logger.Info(str)
}
// If there was an error while scanning the input, log an error
if err := scanner.Err(); err != nil {
pl.logger.Error("reading from scanner", log.Err(err))
}
}
// level = level
// msg = msg
// prefix for all fields hook_
// source = hook_source
// stacktrace = hook_stacktrace
func (pl *proxyLogger) mergeAndLogInputLog(ctx context.Context, inputLog map[string]interface{}, prefix string) {
var lvl log.Level
lvlRaw, ok := inputLog[slog.LevelKey].(string)
if ok {
lvl = log.LogLevelFromStr(lvlRaw)
delete(inputLog, slog.LevelKey)
}
msg, ok := inputLog[slog.MessageKey].(string)
if !ok {
msg = "hook result"
}
delete(inputLog, slog.MessageKey)
delete(inputLog, slog.TimeKey)
logLineRaw, _ := json.Marshal(inputLog)
logLine := string(logLineRaw)
logger := pl.logger.With(pl.proxyJsonLogKey, true)
if len(logLine) > 10000 {
logLine = fmt.Sprintf("%s:truncated", logLine[:10000])
logger.Log(ctx, lvl.Level(), msg, slog.Any("hook", map[string]any{
"truncated": logLine,
}))
return
}
for key, val := range inputLog {
logger = logger.With(slog.Any(prefix+"_"+key, val))
}
logger.Log(ctx, lvl.Level(), msg)
}