-
Notifications
You must be signed in to change notification settings - Fork 734
Expand file tree
/
Copy pathipc.go
More file actions
292 lines (269 loc) · 7.35 KB
/
ipc.go
File metadata and controls
292 lines (269 loc) · 7.35 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
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
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"syscall"
"github.com/apache/incubator-devlake/core/errors"
)
// ProcessResponse wraps output of a process
type ProcessResponse struct {
stdout []byte
stderr []byte
fdOut []byte
err errors.Error
}
// ProcessStream wraps output of a process
type ProcessStream struct {
receiveChannel <-chan *ProcessResponse
process *os.Process
cancelled bool
}
// StreamProcessOptions options for streaming a process
type StreamProcessOptions struct {
OnStdout func(b []byte)
OnStderr func(b []byte)
// UseFdOut if true, it'll open this fd to be used by the child process. Useful to isolate stdout and custom outputs
UseFdOut bool
OnFdOut func(b []byte)
}
// RunProcessOptions options for running a process
type RunProcessOptions struct {
OnStdout func(b []byte)
OnStderr func(b []byte)
UseFdOut bool
OnFdOut func(b []byte)
}
type processPipes struct {
stdout io.ReadCloser
stderr io.ReadCloser
fdOut io.ReadCloser
}
func (p *processPipes) close() {
_ = p.stderr.Close()
_ = p.stdout.Close()
if p.fdOut != nil {
_ = p.fdOut.Close()
}
}
// Receive listens to the process retrieval channel
func (p *ProcessStream) Receive() <-chan *ProcessResponse {
return p.receiveChannel
}
// Cancel cancels the stream by sending a termination signal to the target.
func (p *ProcessStream) Cancel() errors.Error {
err := errors.Convert(p.process.Signal(syscall.SIGTERM))
if err != nil {
return err
}
p.cancelled = true
return nil
}
func (resp *ProcessResponse) GetStdout() []byte {
return resp.stdout
}
func (resp *ProcessResponse) GetStderr() []byte {
return resp.stderr
}
func (resp *ProcessResponse) GetFdOut() []byte {
return resp.fdOut
}
// GetError gets the error on the response
func (resp *ProcessResponse) GetError() errors.Error {
return resp.err
}
// RunProcess runs the cmd and blocks until its completion. All returned results will have type []byte.
func RunProcess(cmd *exec.Cmd, opts *RunProcessOptions) (*ProcessResponse, errors.Error) {
stream, err := StreamProcess(cmd, &StreamProcessOptions{
OnStdout: func(b []byte) {
if opts.OnStdout != nil {
opts.OnStdout(b)
}
},
OnStderr: func(b []byte) {
if opts.OnStderr != nil {
opts.OnStderr(b)
}
},
UseFdOut: opts.UseFdOut,
OnFdOut: func(b []byte) {
if opts.OnFdOut != nil {
opts.OnFdOut(b)
}
},
})
if err != nil {
return nil, err
}
var stdout []byte
var stderr []byte
var fdOut []byte
for result := range stream.Receive() {
if result.err != nil {
err = result.err
break
}
if result.stdout != nil {
stdout = append(stdout, result.stdout...)
}
if result.stderr != nil {
stderr = append(stderr, result.stderr...)
}
if result.fdOut != nil {
fdOut = append(fdOut, result.fdOut...)
}
}
return &ProcessResponse{
stdout: stdout,
stderr: stderr,
fdOut: fdOut,
err: err,
}, nil
}
// StreamProcess runs the cmd and returns its output on a line-by-line basis, on a channel. The converter functor will allow you
// to convert the incoming raw to your custom data type T. This is a nonblocking function.
func StreamProcess(cmd *exec.Cmd, opts *StreamProcessOptions) (*ProcessStream, errors.Error) {
if opts == nil {
opts = &StreamProcessOptions{}
}
cmd.Env = append(cmd.Env, os.Environ()...)
pipes, err := getPipes(cmd, opts)
if err != nil {
return nil, err
}
if err = errors.Convert(cmd.Start()); err != nil {
return nil, err
}
receiveStream := make(chan *ProcessResponse, 32)
wg := &sync.WaitGroup{}
stdScanner := scanOutputPipe(pipes.stdout, wg, opts.OnStdout, func(result []byte) *ProcessResponse {
return &ProcessResponse{stdout: result}
}, receiveStream)
errScanner, remoteErrorMsg := scanErrorPipe(pipes.stderr, opts.OnStderr, receiveStream)
fdOutScanner := scanOutputPipe(pipes.fdOut, wg, opts.OnFdOut, func(result []byte) *ProcessResponse {
return &ProcessResponse{fdOut: result}
}, receiveStream)
wg.Add(2)
if pipes.fdOut != nil {
wg.Add(1)
}
go stdScanner()
go errScanner()
if pipes.fdOut != nil {
go fdOutScanner()
}
processStream := &ProcessStream{
process: cmd.Process,
receiveChannel: receiveStream,
}
go func() {
defer pipes.close()
if err = errors.Convert(cmd.Wait()); err != nil {
if !processStream.cancelled {
receiveStream <- &ProcessResponse{err: errors.Default.Wrap(err, fmt.Sprintf("remote error response:\n%s", remoteErrorMsg))}
}
}
wg.Done()
}()
go func() {
defer close(receiveStream)
wg.Wait()
}()
return processStream, nil
}
func getPipes(cmd *exec.Cmd, opts *StreamProcessOptions) (*processPipes, errors.Error) {
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.Convert(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, errors.Convert(err)
}
var fdOut *os.File
if opts.UseFdOut {
fdReader, fdOutWriter, err := os.Pipe()
if err != nil {
return nil, errors.Convert(err)
}
cmd.ExtraFiles = []*os.File{fdOutWriter}
fdOut = fdReader
}
return &processPipes{
stdout: stdout,
stderr: stderr,
fdOut: fdOut,
}, nil
}
func scanOutputPipe(pipe io.ReadCloser, wg *sync.WaitGroup, onReceive func([]byte),
responseCreator func([]byte) *ProcessResponse, outboundChannel chan<- *ProcessResponse) func() {
return func() {
scanner := bufio.NewScanner(pipe)
scanner.Buffer(make([]byte, 5*1024*1024), 5*1024*1024)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
src := scanner.Bytes()
data := make([]byte, len(src))
copy(data, src)
if onReceive != nil {
onReceive(data)
}
outboundChannel <- responseCreator(data)
}
wg.Done()
}
}
func scanErrorPipe(pipe io.ReadCloser, onReceive func([]byte), outboundChannel chan<- *ProcessResponse) (func(), *strings.Builder) {
remoteErrorMsg := &strings.Builder{}
return func() {
scanner := bufio.NewScanner(pipe)
scanner.Buffer(make([]byte, 5*1024*1024), 5*1024*1024)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
src := scanner.Bytes()
data := make([]byte, len(src))
copy(data, src)
if onReceive != nil {
onReceive(data)
}
outboundChannel <- &ProcessResponse{stderr: data}
_, _ = remoteErrorMsg.Write(src)
_, _ = remoteErrorMsg.WriteString("\n")
}
}, remoteErrorMsg
}
// CreateCmd wraps the args in "sh -c" for shell-level execution
func CreateCmd(args ...string) *exec.Cmd {
if len(args) < 1 {
panic("no cmd given")
}
cmd := "sh"
cmdArgs := []string{"-c"}
cmdBuilder := &strings.Builder{}
for _, elem := range args {
if elem != "" {
_, _ = cmdBuilder.WriteString(elem)
_, _ = cmdBuilder.WriteString(" ")
}
}
cmdArgs = append(cmdArgs, cmdBuilder.String())
return exec.Command(cmd, cmdArgs...)
}