-
Notifications
You must be signed in to change notification settings - Fork 438
/
pod_exec.go
80 lines (72 loc) · 2.17 KB
/
pod_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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package util
import (
"bytes"
"io"
"net/url"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/klog"
)
type ExecOptions struct {
Command []string
Namespace string
PodName string
ContainerName string
Stdin io.Reader
CaptureStdout bool
CaptureStderr bool
PreserveWhitespace bool
}
func ExecuteCommandInContainer(client kubernetes.Interface, cfg *rest.Config, namespace string, podName string, containerName string, cmd ...string) (
string, string, error) {
return ExecuteWithOptions(client, cfg, ExecOptions{
Command: cmd,
Namespace: namespace,
PodName: podName,
ContainerName: containerName,
Stdin: nil,
CaptureStdout: true,
CaptureStderr: true,
PreserveWhitespace: false,
})
}
func ExecuteWithOptions(client kubernetes.Interface, cfg *rest.Config, options ExecOptions) (string, string, error) {
req := client.CoreV1().RESTClient().Post().
Resource("pods").
Name(options.PodName).
Namespace(options.Namespace).
SubResource("exec").
Param("container", options.ContainerName)
req.VersionedParams(&corev1.PodExecOptions{
Stdin: options.Stdin != nil,
Stdout: options.CaptureStdout,
Stderr: options.CaptureStderr,
TTY: false,
Container: options.ContainerName,
Command: options.Command,
}, scheme.ParameterCodec)
var stdout, stderr bytes.Buffer
err := execute("POST", req.URL(), cfg, options.Stdin, &stdout, &stderr, false)
if options.PreserveWhitespace {
return stdout.String(), stderr.String(), err
}
return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
}
func execute(method string, url *url.URL, cfg *rest.Config, stdin io.Reader, stdout, stderr io.Writer,
tty bool) error {
exec, err := remotecommand.NewSPDYExecutor(cfg, method, url)
if err != nil {
klog.Errorf("remotecommand.NewSPDYExecutor error: %v", err)
return err
}
return exec.Stream(remotecommand.StreamOptions{
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
Tty: tty,
})
}