root.go 8.79 KB
Newer Older
1
/*
2
Copyright 2016 The Kubernetes Authors All rights reserved.
3

4 5 6
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
7

8
    http://www.apache.org/licenses/LICENSE-2.0
9

10 11 12 13 14 15 16 17 18 19
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 cmd

import (
20
	goflag "flag"
Matt Rickard's avatar
Matt Rickard committed
21
	"fmt"
22
	"os"
Jose Donizetti's avatar
Jose Donizetti committed
23
	"runtime"
24
	"strings"
25

Matt Rickard's avatar
Matt Rickard committed
26
	"github.com/docker/machine/libmachine"
27
	"github.com/golang/glog"
Matt Rickard's avatar
Matt Rickard committed
28
	"github.com/pkg/errors"
29
	"github.com/spf13/cobra"
30
	"github.com/spf13/pflag"
31
	"github.com/spf13/viper"
32
	"k8s.io/kubectl/pkg/util/templates"
33
	configCmd "k8s.io/minikube/cmd/minikube/cmd/config"
Sharif Elgamal's avatar
Sharif Elgamal committed
34
	"k8s.io/minikube/cmd/minikube/cmd/node"
Matt Rickard's avatar
Matt Rickard committed
35
	"k8s.io/minikube/pkg/minikube/bootstrapper"
36
	"k8s.io/minikube/pkg/minikube/bootstrapper/kubeadm"
37
	"k8s.io/minikube/pkg/minikube/config"
38
	"k8s.io/minikube/pkg/minikube/constants"
39
	"k8s.io/minikube/pkg/minikube/exit"
40
	"k8s.io/minikube/pkg/minikube/localpath"
41
	"k8s.io/minikube/pkg/minikube/translate"
42 43
)

44
var dirs = [...]string{
45
	localpath.MiniPath(),
46 47 48 49 50 51 52 53
	localpath.MakeMiniPath("certs"),
	localpath.MakeMiniPath("machines"),
	localpath.MakeMiniPath("cache"),
	localpath.MakeMiniPath("cache", "iso"),
	localpath.MakeMiniPath("config"),
	localpath.MakeMiniPath("addons"),
	localpath.MakeMiniPath("files"),
	localpath.MakeMiniPath("logs"),
54
}
55

Matt Rickard's avatar
Matt Rickard committed
56 57 58
var viperWhiteList = []string{
	"alsologtostderr",
	"log_dir",
59
	"v",
Matt Rickard's avatar
Matt Rickard committed
60 61
}

62 63
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
64
	Use:   "minikube",
65
	Short: "Minikube is a tool for managing local Kubernetes clusters.",
Dan Lorenc's avatar
Dan Lorenc committed
66
	Long:  `Minikube is a CLI tool that provisions and manages single-node Kubernetes clusters optimized for development workflows.`,
67
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
Dan Lorenc's avatar
Dan Lorenc committed
68 69
		for _, path := range dirs {
			if err := os.MkdirAll(path, 0777); err != nil {
70
				exit.WithError("Error creating minikube directory", err)
Dan Lorenc's avatar
Dan Lorenc committed
71 72
			}
		}
73

dlorenc's avatar
dlorenc committed
74 75
		logDir := pflag.Lookup("log_dir")
		if !logDir.Changed {
76
			if err := logDir.Value.Set(localpath.MakeMiniPath("logs")); err != nil {
Thomas Stromberg's avatar
Thomas Stromberg committed
77 78
				exit.WithError("logdir set failed", err)
			}
dlorenc's avatar
dlorenc committed
79
		}
Dan Lorenc's avatar
Dan Lorenc committed
80
	},
81 82 83 84 85
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	for _, c := range RootCmd.Commands() {
		c.Short = translate.T(c.Short)
		c.Long = translate.T(c.Long)
		c.Flags().VisitAll(func(flag *pflag.Flag) {
			flag.Usage = translate.T(flag.Usage)
		})

		c.SetUsageTemplate(usageTemplate())
	}
	RootCmd.Short = translate.T(RootCmd.Short)
	RootCmd.Long = translate.T(RootCmd.Long)
	RootCmd.Flags().VisitAll(func(flag *pflag.Flag) {
		flag.Usage = translate.T(flag.Usage)
	})

101
	if runtime.GOOS != "windows" {
Jose Donizetti's avatar
Jose Donizetti committed
102
		// add minikube binaries to the path
103
		targetDir := localpath.MakeMiniPath("bin")
Jose Donizetti's avatar
Jose Donizetti committed
104 105 106
		addToPath(targetDir)
	}

107
	if err := RootCmd.Execute(); err != nil {
108 109
		// Cobra already outputs the error, typically because the user provided an unknown command.
		os.Exit(exit.BadUsage)
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
// usageTemplate just calls translate.T on the default usage template
// explicitly using the raw string instead of calling c.UsageTemplate()
// so the extractor can find this monstrosity of a string
func usageTemplate() string {
	return fmt.Sprintf(`%s:{{if .Runnable}}
  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}

%s:
  {{.NameAndAliases}}{{end}}{{if .HasExample}}

%s:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}

%s:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}

%s:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}

%s:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}

%s:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}

%s{{end}}
`, translate.T("Usage"), translate.T("Aliases"), translate.T("Examples"), translate.T("Available Commands"), translate.T("Flags"), translate.T("Global Flags"), translate.T("Additional help topics"), translate.T(`Use "{{.CommandPath}} [command] --help" for more information about a command.`))
}

143 144 145
// Handle config values for flags used in external packages (e.g. glog)
// by setting them directly, using values from viper when not passed in as args
func setFlagsUsingViper() {
Matt Rickard's avatar
Matt Rickard committed
146 147
	for _, config := range viperWhiteList {
		var a = pflag.Lookup(config)
148 149 150 151 152 153 154
		viper.SetDefault(a.Name, a.DefValue)
		// If the flag is set, override viper value
		if a.Changed {
			viper.Set(a.Name, a.Value.String())
		}
		// Viper will give precedence first to calls to the Set command,
		// then to values from the config.yml
Thomas Stromberg's avatar
Thomas Stromberg committed
155 156 157
		if err := a.Value.Set(viper.GetString(a.Name)); err != nil {
			exit.WithError(fmt.Sprintf("failed to set value for %q", a.Name), err)
		}
158
		a.Changed = true
159 160 161
	}
}

162
func init() {
163
	translate.DetermineLocale()
Jose Donizetti's avatar
Jose Donizetti committed
164
	RootCmd.PersistentFlags().StringP(config.MachineProfile, "p", constants.DefaultMachineName, `The name of the minikube VM being used. This can be set to allow having multiple instances of minikube independently.`)
165
	RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", "kubeadm", "The name of the cluster bootstrapper that will set up the kubernetes cluster.")
166 167 168

	groups := templates.CommandGroups{
		{
169
			Message: translate.T("Basic Commands:"),
170 171 172 173 174 175
			Commands: []*cobra.Command{
				startCmd,
				statusCmd,
				stopCmd,
				deleteCmd,
				dashboardCmd,
176 177
				pauseCmd,
				unpauseCmd,
178 179 180
			},
		},
		{
181
			Message: translate.T("Images Commands:"),
182 183 184 185 186 187
			Commands: []*cobra.Command{
				dockerEnvCmd,
				cacheCmd,
			},
		},
		{
188
			Message: translate.T("Configuration and Management Commands:"),
189 190 191 192 193 194 195 196
			Commands: []*cobra.Command{
				configCmd.AddonsCmd,
				configCmd.ConfigCmd,
				configCmd.ProfileCmd,
				updateContextCmd,
			},
		},
		{
197
			Message: translate.T("Networking and Connectivity Commands:"),
198 199 200 201 202 203
			Commands: []*cobra.Command{
				serviceCmd,
				tunnelCmd,
			},
		},
		{
204
			Message: translate.T("Advanced Commands:"),
205 206 207 208
			Commands: []*cobra.Command{
				mountCmd,
				sshCmd,
				kubectlCmd,
Sharif Elgamal's avatar
Sharif Elgamal committed
209
				node.NodeCmd,
210 211 212
			},
		},
		{
213
			Message: translate.T("Troubleshooting Commands:"),
214 215 216 217 218 219
			Commands: []*cobra.Command{
				sshKeyCmd,
				ipCmd,
				logsCmd,
				updateCheckCmd,
				versionCmd,
220
				optionsCmd,
221 222 223 224 225
			},
		},
	}
	groups.Add(RootCmd)

226
	// Ungrouped commands will show up in the "Other Commands" section
227 228 229
	RootCmd.AddCommand(completionCmd)
	templates.ActsAsRootCommand(RootCmd, []string{"options"}, groups...)

230
	pflag.CommandLine.AddGoFlagSet(goflag.CommandLine)
Thomas Stromberg's avatar
Thomas Stromberg committed
231 232 233
	if err := viper.BindPFlags(RootCmd.PersistentFlags()); err != nil {
		exit.WithError("Unable to bind flags", err)
	}
dlorenc's avatar
dlorenc committed
234
	cobra.OnInitialize(initConfig)
235

236 237 238 239
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
u5's avatar
u5 committed
240
	configPath := localpath.ConfigFile
241 242
	viper.SetConfigFile(configPath)
	viper.SetConfigType("json")
243 244 245 246 247
	if err := viper.ReadInConfig(); err != nil {
		// This config file is optional, so don't emit errors if missing
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			glog.Warningf("Error reading config file at %s: %v", configPath, err)
		}
248
	}
Matt Rickard's avatar
Matt Rickard committed
249 250 251 252
	setupViper()
}

func setupViper() {
253
	viper.SetEnvPrefix(minikubeEnvPrefix)
254
	// Replaces '-' in flags with '_' in env variables
255
	// e.g. iso-url => $ENVPREFIX_ISO_URL
256
	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
Matt Rickard's avatar
Matt Rickard committed
257 258
	viper.AutomaticEnv()

259
	viper.SetDefault(config.WantUpdateNotification, true)
260
	viper.SetDefault(config.ReminderWaitPeriodInHours, 24)
261
	viper.SetDefault(config.WantReportError, false)
262
	viper.SetDefault(config.WantReportErrorPrompt, true)
263
	viper.SetDefault(config.WantKubectlDownloadMsg, true)
264
	viper.SetDefault(config.WantNoneDriverWarning, true)
265
	viper.SetDefault(config.ShowDriverDeprecationNotification, true)
dlorenc's avatar
dlorenc committed
266
	viper.SetDefault(config.ShowBootstrapperDeprecationNotification, true)
Matt Rickard's avatar
Matt Rickard committed
267
	setFlagsUsingViper()
268
}
Matt Rickard's avatar
Matt Rickard committed
269

Medya Ghazizadeh's avatar
Medya Ghazizadeh committed
270 271
// getClusterBootstrapper returns a new bootstrapper for the cluster
func getClusterBootstrapper(api libmachine.API, bootstrapperName string) (bootstrapper.Bootstrapper, error) {
Matt Rickard's avatar
Matt Rickard committed
272 273 274
	var b bootstrapper.Bootstrapper
	var err error
	switch bootstrapperName {
Medya Ghazizadeh's avatar
Medya Ghazizadeh committed
275 276
	case bootstrapper.Kubeadm:
		b, err = kubeadm.NewBootstrapper(api)
277
		if err != nil {
Medya Ghazizadeh's avatar
Medya Ghazizadeh committed
278
			return nil, errors.Wrap(err, "getting a new kubeadm bootstrapper")
279
		}
Matt Rickard's avatar
Matt Rickard committed
280
	default:
Thomas Stromberg's avatar
Thomas Stromberg committed
281
		return nil, fmt.Errorf("unknown bootstrapper: %s", bootstrapperName)
Matt Rickard's avatar
Matt Rickard committed
282 283 284
	}
	return b, nil
}
Jose Donizetti's avatar
Jose Donizetti committed
285 286

func addToPath(dir string) {
287 288 289
	new := fmt.Sprintf("%s:%s", dir, os.Getenv("PATH"))
	glog.Infof("Updating PATH: %s", dir)
	os.Setenv("PATH", new)
Jose Donizetti's avatar
Jose Donizetti committed
290
}