-
Notifications
You must be signed in to change notification settings - Fork 3
/
subprocess.go
189 lines (167 loc) · 4.66 KB
/
subprocess.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
package steps
import (
"bufio"
"bytes"
"fmt"
"os/exec"
"strings"
"sync"
"github.com/antongulenko/golib"
"github.com/bitflow-stream/go-bitflow/bitflow"
"github.com/bitflow-stream/go-bitflow/script/reg"
log "github.com/sirupsen/logrus"
)
type SubprocessRunner struct {
bitflow.NoopProcessor
Cmd string
Args []string
// Configurations for the input/output marshalling
Reader bitflow.SampleReader
Writer bitflow.SampleWriter
Marshaller bitflow.Marshaller
cmd *exec.Cmd
output *bitflow.WriterSink
input *bitflow.ReaderSource
stderr bytes.Buffer
}
func RegisterSubprocessRunner(b reg.ProcessorRegistry) {
create := func(p *bitflow.SamplePipeline, params map[string]interface{}) error {
cmd := SplitShellCommand(params["cmd"].(string))
format := params["format"].(string)
factory := bitflow.DefaultEndpointFactory
err := factory.ParseParameters(params["endpoint-config"].(map[string]string))
if err != nil {
return fmt.Errorf("Error parsing endpoint parameters: %v", err)
}
runner := &SubprocessRunner{
Cmd: cmd[0],
Args: cmd[1:],
}
if err = runner.Configure(format, &factory); err != nil {
return err
}
p.Add(runner)
return nil
}
b.RegisterStep("subprocess", create,
"Start a subprocess for processing samples. Samples will be sent/received over std in/out in the given format.").
Required("cmd", reg.String()).
Optional("format", reg.String(), "bin").
Optional("endpoint-config", reg.Map(reg.String()), map[string]string{})
}
func (r *SubprocessRunner) Configure(marshallingFormat string, f *bitflow.EndpointFactory) error {
format := bitflow.MarshallingFormat(marshallingFormat)
var err error
r.Marshaller, err = bitflow.DefaultEndpointFactory.CreateMarshaller(format)
if err != nil {
return err
}
if r.Marshaller == nil {
return fmt.Errorf("Unknown marshalling format: %v", marshallingFormat)
}
r.Reader = f.Reader(nil)
r.Writer = f.Writer()
return nil
}
func (r *SubprocessRunner) Start(wg *sync.WaitGroup) golib.StopChan {
if err := r.createProcess(); err != nil {
return golib.NewStoppedChan(err)
}
var tasks golib.TaskGroup
if r.input != nil {
// (Optionally) start the input first
tasks.Add(&bitflow.SourceTaskWrapper{SampleSource: r.input})
}
tasks.Add(&golib.NoopTask{
Description: "",
Chan: golib.WaitErrFunc(wg, r.runProcess),
}, &bitflow.ProcessorTaskWrapper{SampleProcessor: r.output})
channels := tasks.StartTasks(wg)
return golib.WaitErrFunc(wg, func() error {
golib.WaitForAny(channels)
// Try to stop everything
if r.input != nil {
r.input.Close()
}
r.Close()
err := tasks.CollectMultiError(channels)
// After everything is shut down: forward the close call
r.CloseSink()
return err.NilOrError()
})
}
func (r *SubprocessRunner) createProcess() error {
r.cmd = exec.Command(r.Cmd, r.Args...)
r.cmd.Stderr = &r.stderr
desc := r.String()
writePipe, err := r.cmd.StdinPipe()
if err != nil {
return err
}
r.output = &bitflow.WriterSink{
Output: writePipe,
Description: desc,
}
r.output.Writer = r.Writer
r.output.Marshaller = r.Marshaller
if _, isEmpty := r.GetSink().(*bitflow.DroppingSampleProcessor); r.GetSink() != nil && !isEmpty {
readPipe, err := r.cmd.StdoutPipe()
if err != nil {
return err
}
r.input = &bitflow.ReaderSource{
Input: readPipe,
Description: desc,
}
r.input.Reader = r.Reader
r.input.SetSink(r.GetSink())
} else {
log.Printf("%v: Not parsing subprocess output", r)
}
return nil
}
func (r *SubprocessRunner) runProcess() error {
err := r.cmd.Run()
if exitErr, ok := err.(*exec.ExitError); ok {
if exitErr.Success() {
err = nil
} else {
if r.stderr.Len() > 0 {
log.Warnf("Stderr output of %v:", r)
scanner := bufio.NewScanner(&r.stderr)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
log.Warnln(" > " + scanner.Text())
}
}
return fmt.Errorf("Subprocess '%v' exited abnormally (%v)", r.Cmd, exitErr.ProcessState.String())
}
}
return err
}
func (r *SubprocessRunner) String() string {
var args bytes.Buffer
for _, arg := range r.Args {
if !strings.ContainsRune(arg, ' ') {
args.WriteString(" ")
args.WriteString(arg)
} else if strings.ContainsRune(arg, '"') {
args.WriteString(" '")
args.WriteString(arg)
args.WriteString("'")
} else {
args.WriteString(" \"")
args.WriteString(arg)
args.WriteString("\"")
}
}
return fmt.Sprintf("Subprocess [%v%s]", r.Cmd, args.String())
}
func (r *SubprocessRunner) Sample(sample *bitflow.Sample, header *bitflow.Header) error {
return r.output.Sample(sample, header)
}
func (r *SubprocessRunner) Close() {
r.output.Close()
// TODO if the process won't close, try to kill it
// r.cmd.Process.Kill()
}