-
Notifications
You must be signed in to change notification settings - Fork 288
/
kubectl_runner.go
56 lines (44 loc) · 1.42 KB
/
kubectl_runner.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
package k8s
import (
"bytes"
"context"
"io"
"os/exec"
)
type kubectlRunner interface {
exec(ctx context.Context, argv []string) (stdout string, stderr string, err error)
execWithStdin(ctx context.Context, argv []string, stdin io.Reader) (stdout string, stderr string, err error)
}
type realKubectlRunner struct {
kubeContext KubeContext
}
var _ kubectlRunner = realKubectlRunner{}
func (k realKubectlRunner) prependGlobalArgs(args []string) []string {
return append([]string{"--context", string(k.kubeContext)}, args...)
}
func (k realKubectlRunner) exec(ctx context.Context, args []string) (stdout string, stderr string, err error) {
args = k.prependGlobalArgs(args)
c := exec.CommandContext(ctx, "kubectl", args...)
stdoutBuf := &bytes.Buffer{}
stderrBuf := &bytes.Buffer{}
c.Stdout = stdoutBuf
c.Stderr = stderrBuf
err = c.Run()
return stdoutBuf.String(), stderrBuf.String(), err
}
func (k realKubectlRunner) execWithStdin(ctx context.Context, args []string, stdin io.Reader) (stdout string, stderr string, err error) {
args = k.prependGlobalArgs(args)
c := exec.CommandContext(ctx, "kubectl", args...)
c.Stdin = stdin
stdoutBuf := &bytes.Buffer{}
stderrBuf := &bytes.Buffer{}
c.Stdout = stdoutBuf
c.Stderr = stderrBuf
err = c.Run()
return stdoutBuf.String(), stderrBuf.String(), err
}
func ProvideKubectlRunner(kubeContext KubeContext) kubectlRunner {
return realKubectlRunner{
kubeContext: kubeContext,
}
}