-
Notifications
You must be signed in to change notification settings - Fork 63
/
kubectl.go
423 lines (358 loc) · 11.2 KB
/
kubectl.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright DataStax, Inc.
// Please see the included license file for details.
package kubectl
import (
"fmt"
"os"
"os/user"
"regexp"
"strings"
"time"
"golang.org/x/term"
mageutil "github.com/k8ssandra/cass-operator/tests/util"
shutil "github.com/k8ssandra/cass-operator/tests/util/sh"
)
const (
// Credentials for creating an ImagePullSecret
EnvDockerUsername = "M_DOCKER_USERNAME"
EnvDockerPassword = "M_DOCKER_PASSWORD"
EnvDockerServer = "M_DOCKER_SERVER"
)
func GetKubeconfig(createDefault bool) string {
usr, err := user.Current()
if err != nil {
panic(err)
}
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig == "" {
defaultDir := fmt.Sprintf("%s/.kube/", usr.HomeDir)
kubeconfig = fmt.Sprintf("%s/config", defaultDir)
if _, err := os.Stat(kubeconfig); createDefault && os.IsNotExist(err) {
err := os.MkdirAll(defaultDir, 0755)
mageutil.PanicOnError(err)
file, err := os.Create(kubeconfig)
mageutil.PanicOnError(err)
file.Close()
}
}
return kubeconfig
}
func WatchPods() {
args := []string{"pods", "-w"}
kCmd := KCmd{Command: "get", Args: args, Flags: nil}
kCmd.ExecVPanic()
}
func WatchPodsInNs(namespace string) {
args := []string{"pods", "--namespace", namespace, "-w"}
kCmd := KCmd{Command: "watch", Args: args, Flags: nil}
kCmd.ExecVPanic()
}
// ==============================================
// KCmd represents an executable kubectl command
// ==============================================
type KCmd struct {
Command string
Args []string
Flags map[string]string
}
// ==============================================
// Execute KCmd by running kubectl
// ==============================================
func (k KCmd) ToCliArgs() []string {
var args []string
// Write out flags first because we don't know
// if the command args will have a -- in them or not
// and prevent our flags from working.
for k, v := range k.Flags {
args = append(args, fmt.Sprintf("--%s=%s", k, v))
}
args = append(args, k.Command)
args = append(args, k.Args...)
return args
}
// ExecV runs KCmd via `kubectl`, where KCmd is a struct holding the kubectl command to run (not including `kubectl` itself), the args, and any flags.
// Returns (stdout, stderr, error) and also logs logs output.
func (k KCmd) ExecVCapture() (string, string, error) {
return shutil.RunVCapture("kubectl", k.ToCliArgs()...)
}
// ExecV runs KCmd via `kubectl`, where KCmd is a struct holding the kubectl command to run (not including `kubectl` itself), the args, and any flags.
// Returns error only (no capture of results) and also logs logs output.
func (k KCmd) ExecV() error {
return shutil.RunV("kubectl", k.ToCliArgs()...)
}
func (k KCmd) ExecVPanic() {
shutil.RunVPanic("kubectl", k.ToCliArgs()...)
}
func (k KCmd) Output() (string, error) {
return shutil.Output("kubectl", k.ToCliArgs()...)
}
func (k KCmd) OutputPanic() string {
return shutil.OutputPanic("kubectl", k.ToCliArgs()...)
}
// ==============================================
// Helper functions to build up a KCmd object
// for common actions
// ==============================================
func (k KCmd) InNamespace(namespace string) KCmd {
return k.WithFlag("namespace", namespace)
}
func (k KCmd) FormatOutput(outputType string) KCmd {
return k.WithFlag("output", outputType)
}
func (k KCmd) WithFlag(name string, value string) KCmd {
if k.Flags == nil {
k.Flags = make(map[string]string)
}
k.Flags[name] = value
return k
}
func (k KCmd) WithLabel(label string) KCmd {
k.Args = append(k.Args, "-l", label)
return k
}
func ClusterInfoForContext(ctxt string) KCmd {
args := []string{"--context", ctxt}
return KCmd{Command: "cluster-info", Args: args}
}
func CreateNamespace(namespace string) KCmd {
args := []string{"namespace", namespace}
return KCmd{Command: "create", Args: args}
}
func DeleteNamespace(namespace string) KCmd {
args := []string{"namespace", namespace}
return KCmd{Command: "delete", Args: args}
}
func CreateSecretLiteral(name string, user string, pw string) KCmd {
args := []string{"secret", "generic", name}
flags := map[string]string{
"from-literal=username": user,
"from-literal=password": pw,
}
return KCmd{Command: "create", Args: args, Flags: flags}
}
func Label(nodes string, key string, value string) KCmd {
tokens := strings.Split(nodes, " ")
args := []string{}
for _, t := range tokens {
if t != "" {
args = append(args, "nodes/"+t)
}
}
label := fmt.Sprintf("%s=%s", key, value)
args = append(args, label)
args = append(args, "--overwrite")
return KCmd{Command: "label", Args: args}
}
func Taint(node string, key string, value string, effect string) KCmd {
var args []string
if value != "" {
args = []string{"nodes", node, fmt.Sprintf("%s=%s:%s", key, value, effect)}
} else {
args = []string{"nodes", node, fmt.Sprintf("%s:%s", key, effect)}
}
return KCmd{Command: "taint", Args: args}
}
func Annotate(resource string, name string, key string, value string) KCmd {
args := []string{resource, name, fmt.Sprintf("%s=%s", key, value)}
return KCmd{Command: "annotate", Args: args}
}
func CreateFromFiles(paths ...string) KCmd {
var args []string
for _, p := range paths {
args = append(args, "-f", p)
}
return KCmd{Command: "create", Args: args}
}
func Logs(args ...string) KCmd {
return KCmd{Command: "logs", Args: args}
}
func Get(args ...string) KCmd {
return KCmd{Command: "get", Args: args}
}
func Describe(args ...string) KCmd {
return KCmd{Command: "describe", Args: args}
}
func GetByTypeAndName(resourceType string, names ...string) KCmd {
var args []string
for _, n := range names {
args = append(args, fmt.Sprintf("%s/%s", resourceType, n))
}
return KCmd{Command: "get", Args: args}
}
func GetByFiles(paths ...string) KCmd {
var args []string
for _, path := range paths {
args = append(args, "-f", path)
}
return KCmd{Command: "get", Args: args}
}
func DeleteFromFiles(paths ...string) KCmd {
var args []string
for _, path := range paths {
args = append(args, "-f", path)
}
return KCmd{Command: "delete", Args: args}
}
func Delete(args ...string) KCmd {
return KCmd{Command: "delete", Args: args}
}
func DeleteByTypeAndName(resourceType string, names ...string) KCmd {
var args []string
for _, n := range names {
args = append(args, fmt.Sprintf("%s/%s", resourceType, n))
}
return KCmd{Command: "delete", Args: args}
}
func ApplyFiles(paths ...string) KCmd {
var args []string
for _, path := range paths {
args = append(args, "-f", path)
}
return KCmd{Command: "apply", Args: args}
}
func PatchMerge(resource string, data string) KCmd {
args := []string{resource, "--patch", data, "--type", "merge"}
return KCmd{Command: "patch", Args: args}
}
func PatchJson(resource string, data string) KCmd {
args := []string{resource, "--patch", data, "--type", "json"}
return KCmd{Command: "patch", Args: args}
}
func Patch(resource string, data string) KCmd {
args := []string{resource, "-p", data}
return KCmd{Command: "patch", Args: args}
}
func erasePreviousLine() {
//cursor up one line
fmt.Print("\033[A")
//erase line
fmt.Print("\033[K")
}
func waitForOutputPattern(k KCmd, pattern string, seconds int) error {
re := regexp.MustCompile(pattern)
c := make(chan string)
timer := time.NewTimer(time.Duration(seconds) * time.Second)
cquit := make(chan bool)
defer close(cquit)
counter := 0
outputIsTerminal := term.IsTerminal(int(os.Stdout.Fd()))
var actual string
var err error
go func() {
printedRerunMsg := false
for !re.MatchString(actual) {
select {
case <-cquit:
fmt.Println("")
return
default:
actual, err = k.Output()
if outputIsTerminal && counter > 0 {
erasePreviousLine()
if printedRerunMsg {
// We need to erase both the new exec output,
// as well as our previous "rerunning" line now
erasePreviousLine()
}
fmt.Printf("Rerunning previous command (%v)\n", counter)
printedRerunMsg = true
}
counter++
// Execute at most once every two seconds
time.Sleep(time.Second * 2)
}
}
c <- actual
}()
select {
case <-timer.C:
var expectedPhrase string
expectedPhrase = "Expected output to match regex: "
msg := fmt.Sprintf("Timed out waiting for value. %s '%s', but '%s' did not match", expectedPhrase, pattern, actual)
if err != nil {
msg = fmt.Sprintf("%s\nThe following error occurred while querying k8s: %v", msg, err)
}
e := fmt.Errorf(msg)
return e
case <-c:
return nil
}
}
func WaitForOutputPattern(k KCmd, pattern string, seconds int) error {
return waitForOutputPattern(k, pattern, seconds)
}
func WaitForOutput(k KCmd, expected string, seconds int) error {
return waitForOutputPattern(k, fmt.Sprintf("^%s$", regexp.QuoteMeta(expected)), seconds)
}
func WaitForOutputContains(k KCmd, expected string, seconds int) error {
return waitForOutputPattern(k, regexp.QuoteMeta(expected), seconds)
}
func DumpAllLogs(path string) KCmd {
//Make dir if doesn't exist
_ = os.MkdirAll(path, os.ModePerm)
args := []string{"dump", "-A"}
flags := map[string]string{"output-directory": path}
return KCmd{Command: "cluster-info", Args: args, Flags: flags}
}
func DumpLogs(path string, namespace string) KCmd {
//Make dir if doesn't exist
_ = os.MkdirAll(path, os.ModePerm)
args := []string{"dump", "-n", namespace}
flags := map[string]string{"output-directory": path}
return KCmd{Command: "cluster-info", Args: args, Flags: flags}
}
// DumpClusterInfo Executes `kubectl cluster-info dump -o yaml` on each cluster. The output
// is stored under <project-root>/build/test.
func DumpClusterInfo(path string, namespace string) {
_ = os.MkdirAll(path, os.ModePerm)
dumpCmd := DumpLogs(path, namespace)
dumpCmd.ExecVPanic()
// Store the list of pods in an easy to read format.
podWide := Get("pods", "-o", "wide", "-n", namespace).OutputPanic()
storeOutput(path, "pods", "out", podWide)
describePods := Describe("pods", "-n", namespace).OutputPanic()
storeOutput(path, "pods-describe", "out", describePods)
// Dump all objects that we need to investigate failures as a flat list and as yaml manifests
for _, objectType := range []string{"CassandraDatacenter", "CassandraTask"} {
// Get the list of objects
output, _ := Get(objectType, "-o", "wide", "-n", namespace).Output()
storeOutput(path, objectType, "out", output)
// Get the yamls for each object
output, _ = Get(objectType, "-o", "yaml", "-n", namespace).Output()
storeOutput(path, objectType, "yaml", output)
}
}
func storeOutput(path, objectType, ext, output string) {
filePath := fmt.Sprintf("%s/%s.%s", path, objectType, ext)
outputFile, err := os.Create(filePath)
if err != nil {
panic("Failed to create log file")
}
defer outputFile.Close()
_, err = outputFile.WriteString(output)
if err != nil {
panic(err)
}
err = outputFile.Sync()
if err != nil {
panic(err)
}
}
func ExecOnPod(podName string, args ...string) KCmd {
execArgs := []string{podName}
execArgs = append(execArgs, args...)
return KCmd{Command: "exec", Args: execArgs}
}
func GetNodes() KCmd {
json := "jsonpath={range .items[*]}{@.metadata.name} {end}"
args := []string{"nodes", "-o", json}
return KCmd{Command: "get", Args: args}
}
func GetNodeNameForPod(podName string) KCmd {
json := "jsonpath={.spec.nodeName}"
return Get(fmt.Sprintf("pod/%s", podName)).FormatOutput(json)
}
func DockerCredentialsDefined() bool {
_, ok := os.LookupEnv(EnvDockerUsername)
return ok
}