-
Notifications
You must be signed in to change notification settings - Fork 162
/
exec.go
41 lines (36 loc) · 1.04 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
package tools
import (
"bytes"
"io"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
)
// PodExec runs a command inside a container and returns stdout, stderr and error.
func PodExec(restClient restclient.Interface, config *restclient.Config, namespace, podName, containerName string, command []string, stdin io.Reader) (string, string, error) {
req := restClient.Post().
Resource("pods").
Name(podName).
Namespace(namespace).
SubResource("exec")
req.VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: command,
Stdin: stdin != nil,
Stdout: true,
Stderr: true,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
if err != nil {
return "", "", err
}
var stdout, stderr bytes.Buffer
err = exec.Stream(remotecommand.StreamOptions{
Stdin: stdin,
Stdout: &stdout,
Stderr: &stderr,
Tty: false,
})
return stdout.String(), stderr.String(), err
}