-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
263 lines (221 loc) · 5.58 KB
/
cli.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
package cli
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
gcmd "github.com/enrichman/gocoverkube/internal/cmd"
)
var Version = "0.0.0-dev"
type RootCfg struct {
kubeconfig string
namespace string
deployment string
pod string
client *kubernetes.Clientset
config *rest.Config
}
func NewRootCmd() *cobra.Command {
rootCfg := &RootCfg{
kubeconfig: filepath.Join(os.Getenv("HOME"), ".kube", "config"),
namespace: v1.NamespaceDefault,
}
rootCmd := &cobra.Command{
Use: "gocoverkube",
Short: "gocoverkube",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
err := initializeConfig(cmd)
if err != nil {
return err
}
err = validateConfig(rootCfg)
if err != nil {
return err
}
clientset, config, err := newKubernetesClient(rootCfg.kubeconfig)
if err != nil {
return err
}
rootCfg.client = clientset
rootCfg.config = config
_, err = gcmd.ServerVersion(clientset)
if err != nil {
return errors.New("error connecting to cluster")
}
return nil
},
}
rootCmd.AddCommand(
NewInitCmd(rootCfg),
NewCollectCmd(rootCfg),
NewClearCmd(rootCfg),
NewVersionCmd(),
)
rootCmd.PersistentFlags().StringVar(&rootCfg.kubeconfig, "kubeconfig", rootCfg.kubeconfig, "kubeconfig [KUBECONFIG]")
rootCmd.PersistentFlags().StringVarP(&rootCfg.namespace, "namespace", "n", rootCfg.namespace, "namespace [NAMESPACE]")
rootCmd.PersistentFlags().StringVarP(&rootCfg.deployment, "deployment", "d", rootCfg.deployment, "deployment (DEPLOYMENT)")
rootCmd.PersistentFlags().StringVarP(&rootCfg.pod, "pod", "p", rootCfg.pod, "pod (POD)")
return rootCmd
}
func NewInitCmd(rootCfg *RootCfg) *cobra.Command {
return &cobra.Command{
Use: "init",
Short: "init",
SilenceErrors: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
if rootCfg.pod != "" {
return gcmd.InitPod(
cmd.Context(),
rootCfg.client,
rootCfg.namespace,
rootCfg.pod,
)
}
return gcmd.InitDeployment(
cmd.Context(),
rootCfg.client,
rootCfg.namespace,
rootCfg.deployment,
)
},
}
}
func NewCollectCmd(rootCfg *RootCfg) *cobra.Command {
return &cobra.Command{
Use: "collect",
Short: "collect",
SilenceErrors: true,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
outDir := args[0]
err := validateOutputDir(outDir)
if err != nil {
return err
}
if rootCfg.pod != "" {
return gcmd.CollectPod(
cmd.Context(),
rootCfg.client,
rootCfg.config,
rootCfg.namespace,
rootCfg.pod,
outDir,
)
}
return gcmd.Collect(
cmd.Context(),
rootCfg.client,
rootCfg.config,
rootCfg.namespace,
rootCfg.deployment,
outDir,
)
},
}
}
func validateOutputDir(outDir string) error {
info, err := os.Stat(outDir)
// file exists
if err == nil {
// if it's not a dir return error
if !info.IsDir() {
return fmt.Errorf("output destination '%s' is not a directory", outDir)
}
return nil
}
// err was not nil, something happened
// if the dir didn't exists try to create it
if os.IsNotExist(err) {
return os.MkdirAll(outDir, os.ModePerm)
}
// something else happened
return err
}
func NewClearCmd(rootCfg *RootCfg) *cobra.Command {
return &cobra.Command{
Use: "clear",
Short: "clear",
SilenceErrors: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
if rootCfg.pod != "" {
return gcmd.ClearPod(
cmd.Context(),
rootCfg.client,
rootCfg.namespace,
rootCfg.pod,
)
}
return gcmd.ClearDeployment(
cmd.Context(),
rootCfg.client,
rootCfg.namespace,
rootCfg.deployment,
)
},
}
}
func NewVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "version",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(Version)
},
}
}
func newKubernetesClient(kubeconfig string) (*kubernetes.Clientset, *rest.Config, error) {
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, nil, err
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, nil, err
}
return clientset, config, nil
}
func initializeConfig(cmd *cobra.Command) error {
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()
return bindFlags(cmd, v)
}
// Bind each cobra flag to its associated viper configuration (config file and environment variable)
func bindFlags(cmd *cobra.Command, v *viper.Viper) error {
var err error
cmd.Flags().VisitAll(func(f *pflag.Flag) {
configName := f.Name
// Apply the viper config value to the flag when the flag is not set and viper has a value
if !f.Changed && v.IsSet(configName) {
val := v.Get(configName)
setErr := cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val))
if setErr != nil && err == nil {
err = setErr
}
}
})
return err
}
func validateConfig(cfg *RootCfg) error {
if cfg.pod == "" && cfg.deployment == "" {
return errors.New("one of '--deployment/-d' or '--pod/-p' flag needs to be specified")
}
if cfg.pod == "" && cfg.deployment == "" {
return errors.New("only one of '--deployment/-d' or '--pod/-p' flag needs to be specified")
}
return nil
}