/
root.go
339 lines (275 loc) · 9.05 KB
/
root.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
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
goflag "flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"k8s.io/kops/cmd/kops/util"
kopsapi "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/client/simple"
"k8s.io/kops/pkg/kubeconfig"
"k8s.io/kops/upup/pkg/kutil"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
const (
validResources = `
* cluster
* instancegroup
* secret
`
)
var (
rootLong = templates.LongDesc(i18n.T(`
kops is Kubernetes ops.
kops is the easiest way to get a production grade Kubernetes cluster up and running.
We like to think of it as kubectl for clusters.
kops helps you create, destroy, upgrade and maintain production-grade, highly available,
Kubernetes clusters from the command line. AWS (Amazon Web Services) is currently
officially supported, with GCE and VMware vSphere in alpha support.
`))
rootShort = i18n.T(`kops is Kubernetes ops.`)
)
type Factory interface {
Clientset() (simple.Clientset, error)
}
type RootCmd struct {
util.FactoryOptions
factory *util.Factory
configFile string
clusterName string
cobraCommand *cobra.Command
}
var _ Factory = &RootCmd{}
var rootCommand = RootCmd{
cobraCommand: &cobra.Command{
Use: "kops",
Short: rootShort,
Long: rootLong,
},
}
func Execute() {
goflag.Set("logtostderr", "true")
goflag.CommandLine.Parse([]string{})
if err := rootCommand.cobraCommand.Execute(); err != nil {
exitWithError(err)
}
}
func init() {
cobra.OnInitialize(initConfig)
factory := util.NewFactory(&rootCommand.FactoryOptions)
rootCommand.factory = factory
NewCmdRoot(factory, os.Stdout)
}
func NewCmdRoot(f *util.Factory, out io.Writer) *cobra.Command {
cmd := rootCommand.cobraCommand
//cmd.PersistentFlags().AddGoFlagSet(goflag.CommandLine)
goflag.CommandLine.VisitAll(func(goflag *goflag.Flag) {
switch goflag.Name {
case "cloud-provider-gce-lb-src-cidrs":
// Skip; this is dragged in by the google cloudprovider dependency
default:
cmd.PersistentFlags().AddGoFlag(goflag)
}
})
cmd.PersistentFlags().StringVar(&rootCommand.configFile, "config", "", "yaml config file (default is $HOME/.kops.yaml)")
viper.BindPFlag("config", cmd.PersistentFlags().Lookup("config"))
viper.SetDefault("config", "$HOME/.kops.yaml")
cmd.PersistentFlags().StringVar(&rootCommand.RegistryPath, "state", "", "Location of state storage (kops 'config' file). Overrides KOPS_STATE_STORE environment variable")
viper.BindPFlag("KOPS_STATE_STORE", cmd.PersistentFlags().Lookup("state"))
viper.BindEnv("KOPS_STATE_STORE")
defaultClusterName := os.Getenv("KOPS_CLUSTER_NAME")
cmd.PersistentFlags().StringVarP(&rootCommand.clusterName, "name", "", defaultClusterName, "Name of cluster. Overrides KOPS_CLUSTER_NAME environment variable")
// create subcommands
cmd.AddCommand(NewCmdCompletion(f, out))
cmd.AddCommand(NewCmdCreate(f, out))
cmd.AddCommand(NewCmdDelete(f, out))
cmd.AddCommand(NewCmdEdit(f, out))
cmd.AddCommand(NewCmdExport(f, out))
cmd.AddCommand(NewCmdGet(f, out))
cmd.AddCommand(NewCmdUpdate(f, out))
cmd.AddCommand(NewCmdReplace(f, out))
cmd.AddCommand(NewCmdRollingUpdate(f, out))
cmd.AddCommand(NewCmdSet(f, out))
cmd.AddCommand(NewCmdToolbox(f, out))
cmd.AddCommand(NewCmdValidate(f, out))
return cmd
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
// Config file precedence: --config flag, ${HOME}/.kops.yaml ${HOME}/.kops/config
configFile := rootCommand.configFile
if configFile == "" {
home := homedir.HomeDir()
configPaths := []string{
filepath.Join(home, ".kops.yaml"),
filepath.Join(home, ".kops", "config"),
}
for _, p := range configPaths {
_, err := os.Stat(p)
if err == nil {
configFile = p
break
} else if !os.IsNotExist(err) {
glog.V(2).Infof("error checking for file %s: %v", p, err)
}
}
}
if configFile != "" {
viper.SetConfigFile(configFile)
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
glog.Warningf("error reading config: %v", err)
}
}
rootCommand.RegistryPath = viper.GetString("KOPS_STATE_STORE")
// Tolerate multiple slashes at end
rootCommand.RegistryPath = strings.TrimSuffix(rootCommand.RegistryPath, "/")
}
func (c *RootCmd) AddCommand(cmd *cobra.Command) {
c.cobraCommand.AddCommand(cmd)
}
// ProcessArgs will parse the positional args. It assumes one of these formats:
// * <no arguments at all>
// * <clustername> (and --name not specified)
// Everything else is an error.
func (c *RootCmd) ProcessArgs(args []string) error {
if len(args) == 0 {
return nil
}
if len(args) == 1 {
// Assume <clustername>
if c.clusterName == "" {
c.clusterName = args[0]
return nil
}
}
fmt.Printf("\nFound multiple arguments which look like a cluster name\n")
if c.clusterName != "" {
fmt.Printf("\t%q (via flag)\n", c.clusterName)
}
for _, arg := range args {
fmt.Printf("\t%q (as argument)\n", arg)
}
fmt.Printf("\n")
fmt.Printf("This often happens if you specify an argument to a boolean flag without using =\n")
fmt.Printf("For example: use `--bastion=true` or `--bastion`, not `--bastion true`\n\n")
if len(args) == 1 {
return fmt.Errorf("Cannot specify cluster via --name and positional argument")
}
return fmt.Errorf("expected a single <clustername> to be passed as an argument")
}
func (c *RootCmd) ClusterName() string {
if c.clusterName != "" {
return c.clusterName
}
c.clusterName = ClusterNameFromKubecfg()
return c.clusterName
}
func ClusterNameFromKubecfg() string {
// Read from kubeconfig
pathOptions := clientcmd.NewDefaultPathOptions()
clusterName := ""
config, err := pathOptions.GetStartingConfig()
if err != nil {
glog.Warningf("error reading kubecfg: %v", err)
} else if config.CurrentContext == "" {
glog.Warningf("no context set in kubecfg")
} else {
context := config.Contexts[config.CurrentContext]
if context == nil {
glog.Warningf("context %q in kubecfg not found", config.CurrentContext)
} else if context.Cluster == "" {
glog.Warningf("context %q in kubecfg did not have a cluster", config.CurrentContext)
} else {
fmt.Fprintf(os.Stderr, "Using cluster from kubectl context: %s\n\n", context.Cluster)
clusterName = context.Cluster
}
}
//config, err := readKubectlClusterConfig()
//if err != nil {
// glog.Warningf("error reading kubecfg: %v", err)
//} else if config != nil && config.Name != "" {
// fmt.Fprintf(os.Stderr, "Using cluster from kubectl context: %s\n\n", config.Name)
// c.clusterName = config.Name
//}
return clusterName
}
func readKubectlClusterConfig() (*kubeconfig.KubectlClusterWithName, error) {
kubectl := &kutil.Kubectl{}
context, err := kubectl.GetCurrentContext()
if err != nil {
return nil, fmt.Errorf("error getting current context from kubectl: %v", err)
}
glog.V(4).Infof("context = %q", context)
config, err := kubectl.GetConfig(true)
if err != nil {
return nil, fmt.Errorf("error getting current config from kubectl: %v", err)
}
// Minify should have done this
if len(config.Clusters) != 1 {
return nil, fmt.Errorf("expected exactly one cluster in kubectl config, found %d", len(config.Clusters))
}
return config.Clusters[0], nil
}
func (c *RootCmd) Clientset() (simple.Clientset, error) {
return c.factory.Clientset()
}
func (c *RootCmd) Cluster() (*kopsapi.Cluster, error) {
clusterName := c.ClusterName()
if clusterName == "" {
return nil, fmt.Errorf("--name is required")
}
return GetCluster(c.factory, clusterName)
}
func GetCluster(factory Factory, clusterName string) (*kopsapi.Cluster, error) {
if clusterName == "" {
return nil, field.Required(field.NewPath("ClusterName"), "Cluster name is required")
}
clientset, err := factory.Clientset()
if err != nil {
return nil, err
}
cluster, err := clientset.GetCluster(clusterName)
if err != nil {
return nil, fmt.Errorf("error reading cluster configuration: %v", err)
}
if cluster == nil {
return nil, fmt.Errorf("cluster %q not found", clusterName)
}
if clusterName != cluster.ObjectMeta.Name {
return nil, fmt.Errorf("cluster name did not match expected name: %v vs %v", clusterName, cluster.ObjectMeta.Name)
}
return cluster, nil
}
// ConsumeStdin reads all the bytes available from stdin
func ConsumeStdin() ([]byte, error) {
file := os.Stdin
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(file)
if err != nil {
return nil, fmt.Errorf("error reading stdin: %v", err)
}
return buf.Bytes(), nil
}