/
cmd.go
294 lines (250 loc) · 5.87 KB
/
cmd.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
package x
import (
"bufio"
"bytes"
"fmt"
"io"
"os/exec"
"strings"
"sync"
"time"
"text/template"
"github.com/MasteryConnect/pipe/message"
)
// Cmd will execute a system command
type Cmd struct {
Name string
Args []string
NoStdin bool // don't send the msg.String() to stdin of the command
}
// Command wraps the os/exec Command func
func Command(name string, arg ...string) *Cmd {
return &Cmd{Name: name, Args: arg}
//return &Cmd{Cmd: exec.Command(name, arg...)}
}
// P is the producer function for the pipe/line
func (e Cmd) P(out chan<- interface{}, errs chan<- error) {
var errwg, readwg sync.WaitGroup
// stdout
c := exec.Command(e.Name, e.Args...)
stdout, err := c.StdoutPipe()
if err != nil {
errs <- err
return
}
reader := bufio.NewReader(stdout)
// stderr
stderr, err := c.StderrPipe()
if err != nil {
errs <- err
return
}
errScanner := bufio.NewScanner(stderr)
// start the command
if err := c.Start(); err != nil {
errs <- err
return
}
// read all the lines and send down stream
errwg.Add(1)
go func() {
defer errwg.Done()
for errScanner.Scan() {
errs <- fmt.Errorf(errScanner.Text()) // Println will add back the final '\n'
}
}()
// read all the lines and send down stream
readwg.Add(1)
go func() {
defer readwg.Done()
readAndSend(reader, out, errs)
}()
// wait for read to finish before calling c.Wait()
readwg.Wait()
// wait for close
if err := c.Wait(); err != nil {
errs <- err
}
// wait for the errors to all be processed
errwg.Wait()
}
// TStream is the transform function for the pipe/line
// It will run the shell command once, and keep piping the messages
// in to stdin of the command.
func (e Cmd) TStream(in <-chan interface{}, out chan<- interface{}, errs chan<- error) {
var errwg, readwg sync.WaitGroup
c := exec.Command(e.Name, e.Args...)
// stdin
stdin, err := c.StdinPipe()
if err != nil {
errs <- err
return
}
// stdout
stdout, err := c.StdoutPipe()
if err != nil {
errs <- err
return
}
reader := bufio.NewReader(stdout)
// stderr
stderr, err := c.StderrPipe()
if err != nil {
errs <- err
return
}
errScanner := bufio.NewScanner(stderr)
// start the command
if err := c.Start(); err != nil {
errs <- err
return
}
// read all the lines and send down stream
errwg.Add(1)
go func() {
defer errwg.Done()
for errScanner.Scan() {
errs <- fmt.Errorf(errScanner.Text()) // Println will add back the final '\n'
}
}()
// read all the lines and send down stream
readwg.Add(1)
go func() {
defer readwg.Done()
readAndSend(reader, out, errs)
}()
// read all the messages and write to stdin
for msg := range in {
fmt.Fprintf(stdin, "%s\n", msg.(fmt.Stringer).String())
}
// let the stdin drain before closing
// There could be more do to here after some research instead of sleep.
// Since this only happens once in a streaming case, it shouldn't be that bad.
time.Sleep(100 * time.Millisecond)
stdin.Close()
// wait for the reads before calling c.Wait()
readwg.Wait()
// wait for close
if err := c.Wait(); err != nil {
errs <- err
}
// wait for the errors to finish
errwg.Wait()
}
// T is the transform function for the pipe/line.
// It will run the shell command for each message.
func (e Cmd) T(in <-chan interface{}, out chan<- interface{}, errs chan<- error) {
var errwg, readwg sync.WaitGroup
var cmdTmpl *template.Template
argTmpls := []*template.Template{}
cmdTmpl = template.Must(template.New("x.cmd.name").Parse(e.Name))
for i, arg := range e.Args {
argTmpls = append(argTmpls, template.Must(
template.New(fmt.Sprintf("x.cmd.args.%d", i)).Parse(arg),
))
}
for msg := range in {
name := e.Name
args := append([]string{}, e.Args...)
if cmd, ok := msg.(Commander); ok { // use the message as the command if it is a Commander
name = cmd.Command()
args = cmd.Arguments()
} else { // otherwise, use the static name and arg templates
var b strings.Builder
// Name
err := cmdTmpl.Execute(&b, msg)
if err != nil {
errs <- err
} else {
name = b.String()
}
// Args
for i, argTmpl := range argTmpls {
b.Reset()
err := argTmpl.Execute(&b, msg)
if err != nil {
errs <- err
} else {
args[i] = b.String()
}
}
}
c := exec.Command(name, args...)
// stdin
stdin, err := c.StdinPipe()
if err != nil {
errs <- err
return
}
// stdout
stdout, err := c.StdoutPipe()
if err != nil {
errs <- err
return
}
reader := bufio.NewReader(stdout)
// stderr
stderr, err := c.StderrPipe()
if err != nil {
errs <- err
return
}
errScanner := bufio.NewScanner(stderr)
// start the command
if err := c.Start(); err != nil {
errs <- err
return
}
// read all the errs and send them on
errwg.Add(1)
go func() {
defer errwg.Done()
for errScanner.Scan() {
errs <- fmt.Errorf(errScanner.Text()) // Println will add back the final '\n'
}
}()
// read all the lines and send down stream
readwg.Add(1)
go func() {
defer readwg.Done()
readAndSend(reader, out, errs)
}()
// read all the messages and write to stdin
if !e.NoStdin {
fmt.Fprintf(stdin, "%s\n", message.String(msg))
}
stdin.Close()
// wait for the reads to finish before calling c.Wait()
readwg.Wait()
// wait for close
if err := c.Wait(); err != nil {
errs <- err
}
}
// wait for the errors to finish
errwg.Wait()
}
// Commander defines what it takes to be a command
type Commander interface {
Command() string
Arguments() []string
}
func readAndSend(reader *bufio.Reader, out chan<- interface{}, errs chan<- error) {
msg := []byte("")
line, prefix, err := reader.ReadLine()
for line != nil && err == nil {
msg = append(msg, line...)
if prefix {
line, prefix, err = reader.ReadLine()
continue
}
out <- bytes.NewBuffer(msg)
msg = []byte("")
line, prefix, err = reader.ReadLine()
}
if err != nil {
if err != io.EOF {
errs <- err
}
}
}