/
pod.go
161 lines (131 loc) · 4.2 KB
/
pod.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package globalhelper
import (
"bytes"
"context"
"fmt"
"os"
"time"
. "github.com/onsi/gomega"
"github.com/golang/glog"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/remotecommand"
)
// ExecCommand runs command in the pod and returns buffer output.
func ExecCommand(pod corev1.Pod, command []string) (bytes.Buffer, error) {
var buf bytes.Buffer
req := GetAPIClient().CoreV1Interface.RESTClient().
Post().
Namespace(pod.Namespace).
Resource("pods").
Name(pod.Name).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: pod.Spec.Containers[0].Name,
Command: command,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(GetAPIClient().Config, "POST", req.URL())
if err != nil {
return buf, err
}
err = exec.StreamWithContext(context.TODO(), remotecommand.StreamOptions{
Stdin: os.Stdin,
Stdout: &buf,
Stderr: os.Stderr,
Tty: true,
})
if err != nil {
return buf, err
}
return buf, nil
}
// GetListOfPodsInNamespace returns list of pods for given namespace.
func GetListOfPodsInNamespace(namespace string) (*corev1.PodList, error) {
runningPods, err := GetAPIClient().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, err
}
return runningPods, nil
}
// CreateAndWaitUntilPodIsReady creates a pod and waits until all it's containers are ready.
func CreateAndWaitUntilPodIsReady(pod *corev1.Pod, timeout time.Duration) error {
createdPod, err := GetAPIClient().Pods(pod.Namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
if k8serrors.IsAlreadyExists(err) {
glog.V(5).Info(fmt.Sprintf("pod %s already exists", pod.Name))
} else if err != nil {
return fmt.Errorf("failed to create pod %q (ns %s): %w", pod.Name, pod.Namespace, err)
}
Eventually(func() bool {
status, err := isPodReady(createdPod.Namespace, createdPod.Name)
if err != nil {
glog.V(5).Info(fmt.Sprintf(
"Pod %s is not ready, retry in %d seconds", createdPod.Name, retryInterval))
return false
}
return status
}, timeout, retryInterval*time.Second).Should(Equal(true), "Pod is not ready")
return nil
}
// isPodReady checks if a pod is ready.
func isPodReady(namespace string, podName string) (bool, error) {
podObject, err := GetAPIClient().Pods(namespace).Get(
context.TODO(),
podName,
metav1.GetOptions{},
)
if err != nil {
return false, err
}
numContainers := len(podObject.Spec.Containers)
if len(podObject.Status.ContainerStatuses) != numContainers {
return false, nil
}
for index := range podObject.Spec.Containers {
if !podObject.Status.ContainerStatuses[index].Ready {
return false, nil
}
}
return true, nil
}
// AppendContainersToPod appends containers to a pod.
func AppendContainersToPod(pod *corev1.Pod, containersNum int, image string) {
containerList := &pod.Spec.Containers
for i := 0; i < containersNum; i++ {
*containerList = append(
*containerList, corev1.Container{
Name: fmt.Sprintf("container%d", i+1),
Image: image,
Command: []string{"/bin/bash", "-c", "sleep INF"},
})
}
}
// AppendLabelsToPod appends labels to given pod manifest.
// from go documentation : "if you pass a map to a function that changes the contents of the map,
// the changes will be visible in the caller" - thats the reason for copying the map.
func AppendLabelsToPod(pod *corev1.Pod, labels map[string]string) {
newMap := make(map[string]string)
for k, v := range pod.Labels {
newMap[k] = v
}
for k, v := range labels {
newMap[k] = v
}
pod.Labels = newMap
}
func GetRunningPod(namespace, name string) (*corev1.Pod, error) {
return getRunningPod(GetAPIClient().K8sClient.CoreV1(), namespace, name)
}
func getRunningPod(client typedcorev1.CoreV1Interface, namespace, name string) (*corev1.Pod, error) {
pod, err := client.Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to get pod %q (ns %s): %w", name, namespace, err)
}
return pod, nil
}