-
Notifications
You must be signed in to change notification settings - Fork 13
/
kubernetes.go
291 lines (268 loc) · 7.57 KB
/
kubernetes.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package setup
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
"github.com/pkg/errors"
"github.com/solo-io/go-utils/log"
)
const (
testrunner = "testrunner"
)
// Deprecated: This function is slower than it's go client counterpart, and
// changes the kube context which can have unintended consequences
func SetupKubeForTest(namespace string) error {
context := os.Getenv("KUBECTL_CONTEXT")
if context == "" {
current, err := KubectlOut("config", "current-context")
if err != nil {
return errors.Wrap(err, "getting currrent context")
}
context = strings.TrimSuffix(current, "\n")
}
// TODO(yuval-k): this changes the context for the user? can we do this less intrusive? maybe add it to
// each kubectl command?
if err := Kubectl("config", "set-context", context, "--namespace="+namespace); err != nil {
return errors.Wrap(err, "setting context")
}
return Kubectl("create", "namespace", namespace)
}
// Deprecated: This function is much slower than it's go client counterpart
// because it is blocking. If that is the intended behavior, go ahead and
// and use this function, but just no that it is quite slow.
func TeardownKube(namespace string) error {
return Kubectl("delete", "namespace", namespace)
}
func DeleteCrd(crd string) error {
return Kubectl("delete", "crd", crd)
}
func Kubectl(args ...string) error {
cmd := exec.Command("kubectl", args...)
log.Debugf("k command: %v", cmd.Args)
cmd.Env = os.Environ()
// disable DEBUG=1 from getting through to kube
for i, pair := range cmd.Env {
if strings.HasPrefix(pair, "DEBUG") {
cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...)
break
}
}
cmd.Stdout = ginkgo.GinkgoWriter
cmd.Stderr = ginkgo.GinkgoWriter
return cmd.Run()
}
func KubectlOut(args ...string) (string, error) {
cmd := exec.Command("kubectl", args...)
cmd.Env = os.Environ()
// disable DEBUG=1 from getting through to kube
for i, pair := range cmd.Env {
if strings.HasPrefix(pair, "DEBUG") {
cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...)
break
}
}
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("%s (%v)", out, err)
}
return string(out), err
}
func KubectlOutAsync(args ...string) (*bytes.Buffer, chan struct{}, error) {
cmd := exec.Command("kubectl", args...)
cmd.Env = os.Environ()
// disable DEBUG=1 from getting through to kube
for i, pair := range cmd.Env {
if strings.HasPrefix(pair, "DEBUG") {
cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...)
break
}
}
buf := &bytes.Buffer{}
cmd.Stdout = buf
cmd.Stderr = buf
err := cmd.Start()
if err != nil {
err = fmt.Errorf("%s (%v)", buf.Bytes(), err)
}
done := make(chan struct{})
go func() {
select {
case <-done:
cmd.Process.Kill()
}
}()
return buf, done, err
}
// WaitPodsRunning waits for all pods to be running
func WaitPodsRunning(podNames ...string) error {
finished := func(output string) bool {
return strings.Contains(output, "Running")
}
for _, pod := range podNames {
if err := WaitPodStatus(pod, "Running", finished); err != nil {
return err
}
}
return nil
}
// waitPodsTerminated waits for all pods to be terminated
func WaitPodsTerminated(podNames ...string) error {
for _, pod := range podNames {
finished := func(output string) bool {
return !strings.Contains(output, pod)
}
if err := WaitPodStatus(pod, "terminated", finished); err != nil {
return err
}
}
return nil
}
// TestRunner executes a command inside the TestRunner container
func TestRunner(namespace string, command ...string) (string, error) {
args := []string{"exec", "-i", testrunner}
if namespace != "" {
args = append(args, "-n", namespace)
}
args = append(args, "--")
args = append(args, command...)
return KubectlOut(args...)
}
// TestRunnerAsync executes a command inside the TestRunner container
// returning a buffer that can be read from as it executes
func TestRunnerAsync(args ...string) (*bytes.Buffer, chan struct{}, error) {
args = append([]string{"exec", "-i", testrunner, "--"}, args...)
return KubectlOutAsync(args...)
}
func WaitPodStatus(pod, status string, finished func(output string) bool) error {
timeout := time.Second * 20
interval := time.Millisecond * 1000
tick := time.Tick(interval)
log.Debugf("waiting %v for pod %v to be %v...", timeout, pod, status)
for {
select {
case <-time.After(timeout):
return fmt.Errorf("timed out waiting for %v to be %v", pod, status)
case <-tick:
out, err := KubectlOut("get", "pod", "-l", "gloo="+pod)
if err != nil {
return fmt.Errorf("failed getting pod: %v", err)
}
if strings.Contains(out, "CrashLoopBackOff") {
out = KubeLogs(pod)
return errors.Errorf("%v in crash loop with logs %v", pod, out)
}
if strings.Contains(out, "ErrImagePull") || strings.Contains(out, "ImagePullBackOff") {
out, _ = KubectlOut("describe", "pod", "-l", "gloo="+pod)
return errors.Errorf("%v in ErrImagePull with description %v", pod, out)
}
if finished(out) {
return nil
}
}
}
}
func KubeLogs(pod string) string {
out, err := KubectlOut("logs", "-l", "gloo="+pod)
if err != nil {
out = err.Error()
}
return out
}
func WaitNamespaceStatus(namespace, status string, finished func(output string) bool) error {
timeout := time.Second * 20
interval := time.Millisecond * 1000
tick := time.Tick(interval)
log.Debugf("waiting %v for namespace %v to be %v...", timeout, namespace, status)
for {
select {
case <-time.After(timeout):
return fmt.Errorf("timed out waiting for %v to be %v", namespace, status)
case <-tick:
out, err := KubectlOut("get", "namespace", namespace)
if err != nil {
return fmt.Errorf("failed getting pod: %v", err)
}
if finished(out) {
return nil
}
}
}
}
type CurlOpts struct {
Protocol string
Path string
Method string
Host string
Service string
CaFile string
Body string
Headers map[string]string
Port int
ReturnHeaders bool
}
func CurlEventuallyShouldRespond(opts CurlOpts, namespace, substr string, ginkgoOffset int, timeout ...time.Duration) {
t := time.Second * 20
if len(timeout) > 0 {
t = timeout[0]
}
// for some useful-ish output
tick := time.Tick(t / 8)
gomega.EventuallyWithOffset(ginkgoOffset, func() string {
res, err := Curl(opts, namespace)
if err != nil {
res = err.Error()
}
select {
default:
break
case <-tick:
log.GreyPrintf("running: %v\nwant %v\nhave: %s", opts, substr, res)
}
if strings.Contains(res, substr) {
log.GreyPrintf("success: %v", res)
}
return res
}, t, "5s").Should(gomega.ContainSubstring(substr))
}
func Curl(opts CurlOpts, namespace string) (string, error) {
args := []string{"curl", "-v", "--connect-timeout", "10", "--max-time", "10"}
if opts.ReturnHeaders {
args = append(args, "-I")
}
if opts.Method != "GET" && opts.Method != "" {
args = append(args, "-X"+opts.Method)
}
if opts.Host != "" {
args = append(args, "-H", "Host: "+opts.Host)
}
if opts.CaFile != "" {
args = append(args, "--cacert", opts.CaFile)
}
if opts.Body != "" {
args = append(args, "-H", "Content-Type: application/json")
args = append(args, "-d", opts.Body)
}
for h, v := range opts.Headers {
args = append(args, "-H", fmt.Sprintf("%v: %v", h, v))
}
port := opts.Port
if port == 0 {
port = 8080
}
protocol := opts.Protocol
if protocol == "" {
protocol = "http"
}
service := opts.Service
if service == "" {
service = "test-ingress"
}
args = append(args, fmt.Sprintf("%v://%s:%v%s", protocol, service, port, opts.Path))
log.Debugf("running: curl %v", strings.Join(args, " "))
return TestRunner(namespace, args...)
}