-
Notifications
You must be signed in to change notification settings - Fork 13
/
shell.go
557 lines (462 loc) · 10.9 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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package shell
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"strings"
"sync"
"syscall"
"time"
"github.com/pkg/errors"
)
var (
ErrLineBufferOverflow = errors.New("line buffer overflow")
ErrAlreadyFinished = errors.New("already finished")
ErrNotFoundCommand = errors.New("command not found")
ErrNotExecutePermission = errors.New("not execute permission")
ErrInvalidArgs = errors.New("Invalid argument to exit")
ErrProcessTimeout = errors.New("throw process timeout")
ErrProcessCancel = errors.New("active cancel process")
DefaultExitCode = 2
)
type Cmd struct {
ctx context.Context
cancel context.CancelFunc
stdcmd *exec.Cmd
sync.Mutex
Bash string
ShellMode bool
Status Status
Env []string
Dir string
isFinalized bool
timeout int
statusChan chan Status
doneChan chan error
output bytes.Buffer // stdout + stderr
stdout bytes.Buffer
stderr bytes.Buffer
}
type Status struct {
PID int
Finish bool
ExitCode int
Error error
CostTime time.Duration
Output string // stdout + stderr
Stdout string
Stderr string
startTime time.Time
endTime time.Time
}
type optionFunc func(*Cmd) error
// WithTimeout command timeout, unit second
func WithTimeout(td int) optionFunc {
if td < 0 {
panic("timeout > 0")
}
return func(o *Cmd) error {
o.timeout = td
return nil
}
}
// WithShellMode set shell mode
func WithShellMode() optionFunc {
return func(o *Cmd) error {
o.ShellMode = true
return nil
}
}
// WithExecMode set exec mode, example: ["curl", "-i", "-v", "xiaorui.cc"]
func WithExecMode(b bool) optionFunc {
return func(o *Cmd) error {
o.ShellMode = false
return nil
}
}
// WithSetDir set work dir
func WithSetDir(dir string) optionFunc {
return func(o *Cmd) error {
o.Dir = dir
return nil
}
}
// WithSetEnv set env
func WithSetEnv(env []string) optionFunc {
return func(o *Cmd) error {
o.Env = env
return nil
}
}
func NewCommand(bash string, options ...optionFunc) *Cmd {
c := &Cmd{
Bash: bash,
Status: Status{},
ShellMode: true,
statusChan: make(chan Status, 1),
doneChan: make(chan error, 1),
}
for _, opt := range options {
opt(c)
}
return c
}
// Clone new Cmd with current config
func (c *Cmd) Clone() *Cmd {
return NewCommand(c.Bash)
}
// Start async execute command
func (c *Cmd) Start() error {
if c.Status.Finish {
return ErrAlreadyFinished
}
return c.run()
}
// Wait wait command finish
func (c *Cmd) Wait() error {
<-c.doneChan
return c.Status.Error
}
// Run start and wait process exit
func (c *Cmd) Run() error {
c.Start()
return c.Wait()
}
func (c *Cmd) buildCtx() {
if c.timeout > 0 {
c.ctx, c.cancel = context.WithTimeout(context.Background(), time.Duration(c.timeout)*time.Second)
} else {
c.ctx, c.cancel = context.WithCancel(context.Background())
}
}
func (c *Cmd) run() error {
var (
cmd *exec.Cmd
sysProcAttr *syscall.SysProcAttr
)
c.buildCtx()
sysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
c.Status.startTime = time.Now()
if c.ShellMode {
cmd = exec.Command("bash", "-c", c.Bash)
} else {
args := strings.Split(c.Bash, " ")
cmd = exec.Command(args[0], args[1:]...)
}
cmd.Dir = c.Dir
cmd.Env = c.Env
cmd.SysProcAttr = sysProcAttr
// merge multi writer
mergeStdout := io.MultiWriter(&c.output, &c.stdout)
mergeStderr := io.MultiWriter(&c.output, &c.stderr)
// reset writer
cmd.Stdout = mergeStdout
cmd.Stderr = mergeStderr
c.stdcmd = cmd
// async start
err := c.stdcmd.Start()
if err != nil {
c.Status.Error = err
return err
}
go c.handleWait()
return nil
}
func (c *Cmd) handleWait() error {
defer func() {
if c.Status.Finish {
return
}
c.statusChan <- c.Status
c.finalize()
}()
c.handleTimeout()
// join process
err := c.stdcmd.Wait()
if c.ctx.Err() == context.DeadlineExceeded {
return err
}
if c.ctx.Err() == context.Canceled {
return err
}
if err != nil {
c.Status.Error = formatExitCode(err)
return err
}
c.Status.Stdout = c.stdout.String()
c.Status.Stderr = c.stderr.String()
c.Status.Output = c.output.String()
return nil
}
// handleTimeout if use commandContext timeout, can't match shell mode.
func (c *Cmd) handleTimeout() {
if c.timeout <= 0 {
return
}
call := func() {
select {
case <-c.doneChan:
// safe exit
case <-c.ctx.Done():
if c.ctx.Err() == context.Canceled {
c.Status.Error = ErrProcessCancel
}
if c.ctx.Err() == context.DeadlineExceeded {
c.Status.Error = ErrProcessTimeout
}
c.Stop()
}
}
time.AfterFunc(time.Duration(c.timeout)*time.Second, call)
}
func (c *Cmd) finalize() {
c.Lock()
defer c.Unlock()
if c.isFinalized {
return
}
c.Status.CostTime = time.Now().Sub(c.Status.startTime)
c.Status.Finish = true
c.Status.PID = c.stdcmd.Process.Pid
c.Status.ExitCode = c.stdcmd.ProcessState.ExitCode()
// notify
close(c.doneChan)
close(c.statusChan)
c.isFinalized = true
}
// Stop kill -9 pid
func (c *Cmd) Stop() {
if c.stdcmd == nil || c.stdcmd.Process == nil {
return
}
c.cancel()
c.finalize()
c.stdcmd.Process.Kill()
syscall.Kill(-c.stdcmd.Process.Pid, syscall.SIGKILL)
}
// Kill send custom signal to process
func (c *Cmd) Kill(sig syscall.Signal) {
syscall.Kill(c.stdcmd.Process.Pid, sig)
}
// Cost
func (c *Cmd) Cost() time.Duration {
return c.Status.CostTime
}
func formatExitCode(err error) error {
if err == nil {
return err
}
if strings.Contains(err.Error(), "exit status 127") {
return ErrNotFoundCommand
}
if strings.Contains(err.Error(), "exit status 126") {
return ErrNotExecutePermission
}
if strings.Contains(err.Error(), "exit status 128") {
return ErrInvalidArgs
}
return err
}
// CheckCmdExists check command in the PATH
func CheckCmdExists(cmd string) bool {
_, err := exec.LookPath(cmd)
if err != nil {
return false
} else {
return true
}
}
// CheckPnameRunning easy method
func CheckPnameRunning(pname string) bool {
out, _, _ := CommandFormat("ps aux | grep %s |grep -v grep", pname)
if strings.Contains(out, pname) {
return true
}
return false
}
// Command easy command, return CombinedOutput, exitcode, err
func Command(args string) (string, int, error) {
cmd := exec.Command("bash", "-c", args)
outbs, err := cmd.CombinedOutput()
out := string(outbs)
return out, cmd.ProcessState.ExitCode(), err
}
// Command easy command format, return CombinedOutput, exitcode, err
func CommandFormat(format string, vals ...interface{}) (string, int, error) {
sh := fmt.Sprintf(format, vals...)
return Command(sh)
}
// CommandContains easy command, then match output with multi substr
func CommandContains(args string, subs ...string) bool {
outbs, _, err := Command(args)
if err != nil {
return false
}
out := string(outbs)
for _, sub := range subs {
if !strings.Contains(out, sub) {
return false
}
}
return true
}
// CommandScript write script to random fname in /tmp directory and bash execute
func CommandScript(script []byte) (string, int, error) {
fpath := fmt.Sprintf("/tmp/go-shell-%s", randString(16))
defer os.RemoveAll(fpath)
err := ioutil.WriteFile(fpath, script, 0666)
if err != nil {
return "", DefaultExitCode, errors.Errorf("dump script to file failed, err: %s", err.Error())
}
out, code, err := CommandFormat("bash %s", fpath)
return out, code, err
}
// CommandWithMultiOut run command and return multi result; return string(stdout), string(stderr), exidcode, err
func CommandWithMultiOut(cmd string) (string, string, int, error) {
var (
stdout, stderr bytes.Buffer
err error
)
runner := exec.Command("bash", "-c", cmd)
runner.Stdout = &stdout
runner.Stderr = &stderr
err = runner.Start()
if err != nil {
return string(stdout.Bytes()), string(stderr.Bytes()), runner.ProcessState.ExitCode(), err
}
err = runner.Wait()
return string(stdout.Bytes()), string(stderr.Bytes()), runner.ProcessState.ExitCode(), err
}
// CommandWithChan return result queue
func CommandWithChan(cmd string, queue chan string) error {
runner := exec.Command("bash", "-c", cmd)
stdout, err := runner.StdoutPipe()
if err != nil {
return err
}
stderr, err := runner.StderrPipe()
if err != nil {
return err
}
runner.Start()
call := func(in io.ReadCloser) {
reader := bufio.NewReader(in)
for {
line, _, err := reader.ReadLine()
if err != nil || io.EOF == err {
break
}
select {
case queue <- string(line):
default:
}
}
}
go call(stdout)
go call(stderr)
runner.Wait()
close(queue)
return nil
}
type OutputBuffer struct {
buf *bytes.Buffer
lines []string
*sync.Mutex
}
func NewOutputBuffer() *OutputBuffer {
out := &OutputBuffer{
buf: &bytes.Buffer{},
lines: []string{},
Mutex: &sync.Mutex{},
}
return out
}
func (rw *OutputBuffer) Write(p []byte) (n int, err error) {
rw.Lock()
n, err = rw.buf.Write(p) // and bytes.Buffer implements io.Writer
rw.Unlock()
return
}
func (rw *OutputBuffer) Lines() []string {
rw.Lock()
s := bufio.NewScanner(rw.buf)
for s.Scan() {
rw.lines = append(rw.lines, s.Text())
}
rw.Unlock()
return rw.lines
}
type OutputStream struct {
streamChan chan string
bufSize int
buf []byte
lastChar int
}
// NewOutputStream creates a new streaming output on the given channel.
func NewOutputStream(streamChan chan string) *OutputStream {
out := &OutputStream{
streamChan: streamChan,
bufSize: 16384,
buf: make([]byte, 16384),
lastChar: 0,
}
return out
}
// Write makes OutputStream implement the io.Writer interface.
func (rw *OutputStream) Write(p []byte) (n int, err error) {
n = len(p) // end of buffer
firstChar := 0
for {
newlineOffset := bytes.IndexByte(p[firstChar:], '\n')
if newlineOffset < 0 {
break // no newline in stream, next line incomplete
}
// End of line offset is start (nextLine) + newline offset. Like bufio.Scanner,
// we allow \r\n but strip the \r too by decrementing the offset for that byte.
lastChar := firstChar + newlineOffset // "line\n"
if newlineOffset > 0 && p[newlineOffset-1] == '\r' {
lastChar -= 1 // "line\r\n"
}
// Send the line, prepend line buffer if set
var line string
if rw.lastChar > 0 {
line = string(rw.buf[0:rw.lastChar])
rw.lastChar = 0 // reset buffer
}
line += string(p[firstChar:lastChar])
rw.streamChan <- line // blocks if chan full
// Next line offset is the first byte (+1) after the newline (i)
firstChar += newlineOffset + 1
}
if firstChar < n {
remain := len(p[firstChar:])
bufFree := len(rw.buf[rw.lastChar:])
if remain > bufFree {
var line string
if rw.lastChar > 0 {
line = string(rw.buf[0:rw.lastChar])
}
line += string(p[firstChar:])
err = ErrLineBufferOverflow
n = firstChar
return // implicit
}
copy(rw.buf[rw.lastChar:], p[firstChar:])
rw.lastChar += remain
}
return // implicit
}
func (rw *OutputStream) Lines() <-chan string {
return rw.streamChan
}
func (rw *OutputStream) SetLineBufferSize(n int) {
rw.bufSize = n
rw.buf = make([]byte, rw.bufSize)
}