-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrunner.go
More file actions
93 lines (62 loc) · 1.71 KB
/
runner.go
File metadata and controls
93 lines (62 loc) · 1.71 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
package rac
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"time"
)
type runner struct {
Timeout time.Duration
TryTimeoutCount int
log Logger
}
func (r *runner) RunCtx(ctx context.Context, command string, args []string) (respond []byte, err error) {
respond, err = r.runTry(ctx, command, args)
if err == context.DeadlineExceeded {
for tryCount := 1; tryCount < r.TryTimeoutCount; tryCount++ {
respond, err = r.runTry(ctx, command, args)
if err == context.DeadlineExceeded {
continue
}
return
}
}
return
}
func (r *runner) runTry(ctx context.Context, command string, args []string) (respond []byte, err error) {
ctx, _ = context.WithTimeout(ctx, r.Timeout)
cmd := exec.CommandContext(ctx, command, args...)
cmd.Stdout = new(bytes.Buffer)
cmd.Stderr = new(bytes.Buffer)
errch := make(chan error, 1)
err = cmd.Start()
if err != nil {
return respond, fmt.Errorf("Произошла ошибка запуска:\n\terr:%s\n\tПараметры: %v\n\t", err.Error(), cmd.Args)
}
go func() {
errch <- cmd.Wait()
}()
select {
case <-ctx.Done(): // timeout
return respond, ctx.Err()
case err := <-errch:
if err != nil {
stderr := cmd.Stderr.(*bytes.Buffer).Bytes()
errText := fmt.Sprintf("Произошла ошибка запуска:\n\terr:%s\n\tПараметры: %v\n\t", err.Error(), cmd.Args)
stdErrText, _ := decodeOutBytes(stderr)
if len(stderr) > 0 {
errText += fmt.Sprintf("StdErr:%s\n", stdErrText)
}
return respond, errors.New(errText)
} else {
in := cmd.Stdout.(*bytes.Buffer).Bytes()
respond, err = decodeOutBytes(in)
if err != nil {
return respond, err
}
return respond, nil
}
}
}