-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.go
314 lines (270 loc) · 6.17 KB
/
exec.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package sh
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"syscall"
"github.com/rs/xid"
)
type Exec struct {
id string
xid string
lastWorkDir string // 执行完毕后工作目录位置
cmd *exec.Cmd
ctx context.Context
err error
file *os.File
finished bool
finishedRawLen int
hide bool
opts *ExecOptions
stdin io.WriteCloser
stdout io.ReadCloser
}
func NewExec(execOpts ...*ExecOptions) (*Exec, error) {
return NewExecContext(context.Background(), execOpts...)
}
func NewExecContext(ctx context.Context, execOpts ...*ExecOptions) (*Exec, error) {
opts := GlobalExecOptionsOverwrite(execOpts...)
e := &Exec{
id: opts.IDCreator(),
xid: xid.New().String(),
ctx: ctx,
opts: opts,
}
if e.id == "" {
return nil, errors.New("id is empty")
}
valid, err := CheckStorage(opts.Storage)
if err != nil {
return nil, err
}
if valid {
if e.file, err = opts.Storage.CreateFile(e.id); err != nil {
return nil, err
}
e.stdin = e.file
args := append(opts.Shell.GetFullArgs(), e.file.Name())
e.cmd = exec.CommandContext(ctx, opts.Shell.Path(), args...)
} else {
e.cmd = exec.CommandContext(ctx, opts.Shell.Path(), opts.Shell.GetFullArgs()...)
if e.stdin, err = e.cmd.StdinPipe(); err != nil {
return nil, err
}
}
e.cmd.SysProcAttr = &syscall.SysProcAttr{
// reference:https://jarv.org/posts/command-with-timeout/
Setpgid: true,
}
if opts.User != "" {
if osUser, err := user.Lookup(opts.User); err != nil {
return nil, err
} else {
uid, _ := strconv.Atoi(osUser.Uid)
gid, _ := strconv.Atoi(osUser.Gid)
e.cmd.SysProcAttr.Credential = &syscall.Credential{
Uid: uint32(uid),
Gid: uint32(gid),
NoSetGroups: true,
}
}
}
if opts.WorkDir != "" {
e.cmd.Dir = opts.WorkDir
}
if e.stdout, err = e.cmd.StdoutPipe(); err != nil {
return nil, err
}
// redirect stderr to stdout
e.cmd.Stderr = e.cmd.Stdout
return e, nil
}
func (e *Exec) ID() string {
return e.id
}
func (e *Exec) GetLastWorkDir() string {
return e.lastWorkDir
}
// Finished returns the value of whether it is finished
func (e *Exec) Finished() bool {
return e.finished
}
func (e *Exec) String() string {
if e.cmd != nil {
return e.cmd.String()
}
return ""
}
func (e *Exec) setErr(err error, force bool) {
if err == nil {
return
}
if force || e.err == nil {
e.err = &ExecError{
ID: e.id,
Context: e.ctx,
Err: err,
}
}
}
func (e *Exec) setFinished() {
if !e.finished {
e.finished = true
var err error
if e.opts.Storage != nil && e.file != nil {
err = e.opts.Storage.RemoveOrTruncate(e.file, int64(e.finishedRawLen))
e.setErr(err, false)
}
if err = e.stdin.Close(); err != nil {
e.setErr(err, false)
}
if e.cmd.Process.Pid > 0 {
// 关闭进程组,包括子进程
// 只调用c.cmd.Process.Kill(),子进程不会被杀死,原因来自go语言
// see: https://github.com/golang/go/issues/23019
_ = syscall.Kill(-e.cmd.Process.Pid, syscall.SIGKILL)
}
}
}
// Cancel this execution
func (e *Exec) Cancel() error {
defer e.setFinished()
return e.err
}
func (e *Exec) AddCommand(name string, args ...string) error {
if name == "" {
return nil
}
n := len(name) + len(args)
for _, arg := range args {
n += len(arg)
}
builder := new(bytes.Buffer)
builder.Grow(n)
builder.WriteString(name)
for _, arg := range args {
builder.WriteByte(' ')
builder.WriteString(arg)
}
raw := append(bytes.TrimSpace(builder.Bytes()), '\n')
return e.AddRawCommand(raw)
}
func (e *Exec) AddRawCommand(raw []byte) error {
if len(raw) == 0 {
return nil
}
if _, err := e.stdin.Write(raw); err != nil {
return err
}
return nil
}
func (e *Exec) key(key string) string {
return fmt.Sprintf("%s:%s", e.xid, key)
}
func (e *Exec) echoKey(key string, dbQuote ...bool) string {
if len(dbQuote) > 0 && dbQuote[0] {
return fmt.Sprintf(`echo "%s"`, e.key(key))
}
return fmt.Sprintf("echo '%s'", e.key(key))
}
func (e *Exec) getKey(key, line string) (val string, found bool) {
return strings.CutPrefix(line, e.key(key))
}
func (e *Exec) addFinishedRawCommand() error {
builder := new(bytes.Buffer)
builder.WriteString(e.echoKey("start"))
builder.WriteByte('\n')
builder.WriteString("set +x")
builder.WriteByte('\n')
builder.WriteString("wait")
builder.WriteByte('\n')
builder.WriteString(e.echoKey("pwd:$(pwd)", true))
builder.WriteByte('\n')
builder.WriteString(e.echoKey("end"))
builder.WriteByte('\n')
raw := builder.Bytes()
e.finishedRawLen = len(raw)
return e.AddRawCommand(raw)
}
func (e *Exec) parseOutput(num int, lineByte []byte) bool {
line := bytesToString(lineByte)
if _, ok := e.getKey("end", line); ok {
e.setFinished()
return false
}
if _, ok := e.getKey("start", line); ok {
e.hide = true
return true
}
if e.hide {
if val, ok := e.getKey("pwd:", line); ok {
e.lastWorkDir = val
return true
}
}
if e.opts != nil && e.opts.Output != nil &&
!e.hide && !strings.Contains(line, e.xid) {
e.opts.Output(num, lineByte)
}
return true
}
func (e *Exec) Run(command ...string) error {
if e.cmd == nil {
return errors.New("exec: uninitialized")
}
if e.finished {
return errors.New("exec: already finished")
}
defer e.setFinished()
var err error
if err = e.cmd.Start(); err != nil {
return err
}
for _, s := range command {
if err = e.AddCommand(s); err != nil {
return err
}
}
if err = e.addFinishedRawCommand(); err != nil {
return err
}
go func() {
scanner := bufio.NewScanner(e.stdout)
var num int
for scanner.Scan() {
num++
if !e.parseOutput(num, scanner.Bytes()) {
break
}
}
if scanner.Err() != nil {
e.setErr(fmt.Errorf("read: %s", scanner.Err()), false)
}
}()
if err = e.cmd.Wait(); err != nil {
e.setErr(err, true)
}
return e.err
}
type ExecError struct {
ID string
Context context.Context
Err error
}
func (e *ExecError) Error() string {
if e.Context != nil && e.Context.Err() != nil {
return e.Context.Err().Error()
}
return e.Err.Error()
}
func IsDeadlineExceeded(err error) bool {
return err.Error() == context.DeadlineExceeded.Error()
}