-
Notifications
You must be signed in to change notification settings - Fork 787
/
step_verify_pod_ready.go
114 lines (97 loc) · 2.57 KB
/
step_verify_pod_ready.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
package cmd
import (
"bytes"
"fmt"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/pkg/errors"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"os"
"os/exec"
)
var (
stepStatusLong = templates.LongDesc(`
This step checks the status of all kubernetes pods
`)
stepStatusExample = templates.Examples(`
jx step verify pod
`)
)
// StepVerifyPodReadyOptions contains the command line flags
type StepVerifyPodReadyOptions struct {
StepOptions
Debug bool
}
// NewCmdStepVerifyPodReady creates the `jx step verify pod` command
func NewCmdStepVerifyPodReady(commonOpts *CommonOptions) *cobra.Command {
options := StepVerifyPodReadyOptions{
StepOptions: StepOptions{
CommonOptions: commonOpts,
},
}
cmd := &cobra.Command{
Use: "ready",
Short: "Returns the status of kubernetes pods",
Long: stepStatusLong,
Example: stepStatusExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
cmd.Flags().BoolVarP(&options.Debug, "debug", "", false, "Output logs of any failed pod")
return cmd
}
// Run the `jx step verify pod ready` command
func (o *StepVerifyPodReadyOptions) Run() error {
kubeClient, ns, err := o.KubeClientAndNamespace()
if err != nil {
return errors.Wrap(err, "failed to get the Kube client")
}
pods, err := kubeClient.CoreV1().Pods(ns).List(metav1.ListOptions{})
if err != nil {
return errors.Wrapf(err, "failed to list the PODs in namespace '%s'", ns)
}
fmt.Println("Checking pod statuses")
table := o.createTable()
table.AddRow("POD", "STATUS")
var f *os.File
if o.Debug {
fmt.Println("Creating verify-pod.log file")
f, err = os.Create("verify-pod.log")
if err != nil {
return errors.Wrap(err, "error creating log file")
}
defer f.Close()
}
for _, pod := range pods.Items {
podName := pod.ObjectMeta.Name
phase := pod.Status.Phase
if phase == corev1.PodFailed && o.Debug {
args := []string{"logs", podName}
name := "kubectl"
e := exec.Command(name, args...)
e.Stderr = o.Err
var out bytes.Buffer
e.Stdout = &out
err := e.Run()
if err != nil {
return errors.Wrap(err, "failed to get the Kube pod logs")
}
_, err = f.WriteString(fmt.Sprintf("Logs for pod %s:\n", podName))
if err != nil {
return errors.Wrap(err, "error writing log file")
}
_, err = f.Write(out.Bytes())
if err != nil {
return errors.Wrap(err, "error writing log file")
}
}
table.AddRow(podName, string(phase))
}
table.Render()
return nil
}