-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.go
More file actions
177 lines (152 loc) · 4.1 KB
/
executor.go
File metadata and controls
177 lines (152 loc) · 4.1 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
package glue
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os/exec"
"time"
)
// DefaultExecMaxOutputBytes is the per-stream output cap used by
// LocalExecutor when ExecCommand.MaxOutputBytes is zero.
const DefaultExecMaxOutputBytes = 64 * 1024
// Executor abstracts command execution for shell-capable tools. The
// default implementation, LocalExecutor, runs commands on the local
// machine; sandboxed or remote executors can implement the same
// interface without changing tool code.
type Executor interface {
Run(ctx context.Context, cmd ExecCommand) (ExecResult, error)
}
// ExecCommand describes one argv-style command execution request.
type ExecCommand struct {
// Argv is the executable plus arguments. It must be non-empty and
// is never interpreted through a shell.
Argv []string
// Dir, when non-empty, is the child process working directory.
Dir string
// Env is the exact child environment. Nil means inherit no
// environment from the agent process.
Env []string
// Stdin, when non-nil, is connected to the child process stdin.
Stdin io.Reader
// Timeout limits this command independently from the caller's
// context. Zero means no executor-level timeout.
Timeout time.Duration
// MaxOutputBytes caps stdout and stderr independently. Zero uses
// DefaultExecMaxOutputBytes.
MaxOutputBytes int
}
// ExecResult is the captured result of one command execution.
type ExecResult struct {
Stdout []byte
Stderr []byte
ExitCode int
TimedOut bool
Truncated bool
}
// LocalExecutor runs commands on the local machine with os/exec. It is
// intentionally not a sandbox.
type LocalExecutor struct{}
var _ Executor = LocalExecutor{}
// Run implements Executor.
func (LocalExecutor) Run(ctx context.Context, cmd ExecCommand) (ExecResult, error) {
if ctx == nil {
ctx = context.Background()
}
if len(cmd.Argv) == 0 || cmd.Argv[0] == "" {
return ExecResult{ExitCode: -1}, errors.New("glue: exec argv is required")
}
if cmd.Timeout < 0 {
return ExecResult{ExitCode: -1}, errors.New("glue: exec timeout must be non-negative")
}
if cmd.MaxOutputBytes < 0 {
return ExecResult{ExitCode: -1}, errors.New("glue: exec max output bytes must be non-negative")
}
maxOutput := cmd.MaxOutputBytes
if maxOutput == 0 {
maxOutput = DefaultExecMaxOutputBytes
}
runCtx := ctx
cancel := func() {}
if cmd.Timeout > 0 {
runCtx, cancel = context.WithTimeout(ctx, cmd.Timeout)
}
defer cancel()
c := exec.CommandContext(runCtx, cmd.Argv[0], cmd.Argv[1:]...)
if cmd.Dir != "" {
c.Dir = cmd.Dir
}
if cmd.Env == nil {
c.Env = []string{}
} else {
c.Env = append([]string(nil), cmd.Env...)
}
if cmd.Stdin != nil {
c.Stdin = cmd.Stdin
}
stdout := &limitedOutput{limit: maxOutput}
stderr := &limitedOutput{limit: maxOutput}
c.Stdout = stdout
c.Stderr = stderr
err := c.Run()
result := ExecResult{
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
ExitCode: exitCode(c),
Truncated: stdout.Truncated() || stderr.Truncated(),
}
if ctxErr := ctx.Err(); ctxErr != nil {
return result, ctxErr
}
if cmd.Timeout > 0 && errors.Is(runCtx.Err(), context.DeadlineExceeded) {
result.TimedOut = true
if result.ExitCode == 0 {
result.ExitCode = -1
}
return result, nil
}
if err == nil {
return result, nil
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
result.ExitCode = exitErr.ExitCode()
return result, nil
}
return result, fmt.Errorf("glue: exec %q: %w", cmd.Argv[0], err)
}
func exitCode(c *exec.Cmd) int {
if c.ProcessState == nil {
return -1
}
return c.ProcessState.ExitCode()
}
type limitedOutput struct {
buf bytes.Buffer
limit int
truncated bool
}
func (w *limitedOutput) Write(p []byte) (int, error) {
originalLen := len(p)
if originalLen == 0 {
return 0, nil
}
remaining := w.limit - w.buf.Len()
if remaining <= 0 {
w.truncated = true
return originalLen, nil
}
if len(p) > remaining {
w.truncated = true
p = p[:remaining]
}
_, _ = w.buf.Write(p)
return originalLen, nil
}
func (w *limitedOutput) Bytes() []byte {
return append([]byte(nil), w.buf.Bytes()...)
}
func (w *limitedOutput) Truncated() bool {
return w.truncated
}