forked from zalando/postgres-operator
/
exec.go
76 lines (62 loc) · 1.88 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
66
67
68
69
70
71
72
73
74
75
76
package cluster
import (
"bytes"
"fmt"
"strings"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/remotecommand"
"github.com/zalando-incubator/postgres-operator/pkg/spec"
"github.com/zalando-incubator/postgres-operator/pkg/util/constants"
)
//ExecCommand executes arbitrary command inside the pod
func (c *Cluster) ExecCommand(podName *spec.NamespacedName, command ...string) (string, error) {
c.setProcessName("executing command %q", strings.Join(command, " "))
var (
execOut bytes.Buffer
execErr bytes.Buffer
)
pod, err := c.KubeClient.Pods(podName.Namespace).Get(podName.Name, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("could not get pod info: %v", err)
}
// iterate through all containers looking for the one running PostgreSQL.
targetContainer := -1
for i, cr := range pod.Spec.Containers {
if cr.Name == constants.PostgresContainerName {
targetContainer = i
break
}
}
if targetContainer < 0 {
return "", fmt.Errorf("could not find %s container to exec to", constants.PostgresContainerName)
}
req := c.KubeClient.RESTClient.Post().
Resource("pods").
Name(podName.Name).
Namespace(podName.Namespace).
SubResource("exec")
req.VersionedParams(&v1.PodExecOptions{
Container: pod.Spec.Containers[targetContainer].Name,
Command: command,
Stdout: true,
Stderr: true,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(c.RestConfig, "POST", req.URL())
if err != nil {
return "", fmt.Errorf("failed to init executor: %v", err)
}
err = exec.Stream(remotecommand.StreamOptions{
Stdout: &execOut,
Stderr: &execErr,
Tty: false,
})
if err != nil {
return "", fmt.Errorf("could not execute: %v", err)
}
if execErr.Len() > 0 {
return "", fmt.Errorf("stderr: %v", execErr.String())
}
return execOut.String(), nil
}