-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
65 lines (53 loc) · 1.15 KB
/
exec.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
package main
import (
"bytes"
"fmt"
"io"
"os/exec"
"sync"
"github.com/rs/zerolog/log"
)
func execCmd(name string, args ...string) (stdout []byte, stderr []byte, err error) {
cmd := exec.Command(name, args...)
outPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, err
}
errPipe, err := cmd.StderrPipe()
if err != nil {
return nil, nil, err
}
var wg sync.WaitGroup
var bufOut bytes.Buffer
var bufErr bytes.Buffer
var outOk bool
var errOk bool
wg.Add(2)
go execPipe(outPipe, &bufOut, &outOk, &wg)
go execPipe(errPipe, &bufErr, &errOk, &wg)
err = cmd.Start()
if err != nil {
return nil, nil, fmt.Errorf("failed to start 'kubectl': %w", err)
}
wg.Wait()
err = cmd.Wait()
if err != nil {
return bufOut.Bytes(), bufErr.Bytes(), fmt.Errorf("'kubectl' failed: %w", err)
}
return bufOut.Bytes(), bufErr.Bytes(), nil
}
func execPipe(pipe io.Reader, buffer *bytes.Buffer, ok *bool, wg *sync.WaitGroup) {
defer wg.Done()
b := make([]byte, 1024)
for {
n, err := pipe.Read(b)
buffer.Write(b[:n])
if err != nil {
*ok = err == io.EOF
if !*ok {
log.Warn().Msgf("execPipe error: %v", err)
}
return
}
}
}