Skip to content

Commit

Permalink
WIP: Remove all single-package constants from constants package #5375
Browse files Browse the repository at this point in the history
  • Loading branch information
u5surf committed Sep 26, 2019
1 parent d24b337 commit 878c3ca
Show file tree
Hide file tree
Showing 20 changed files with 149 additions and 189 deletions.
8 changes: 5 additions & 3 deletions cmd/minikube/cmd/cache.go
Expand Up @@ -25,6 +25,8 @@ import (
"k8s.io/minikube/pkg/minikube/machine"
)

const cache = "cache"

// cacheCmd represents the cache command
var cacheCmd = &cobra.Command{
Use: "cache",
Expand All @@ -43,7 +45,7 @@ var addCacheCmd = &cobra.Command{
exit.WithError("Failed to cache and load images", err)
}
// Add images to config file
if err := cmdConfig.AddToConfigMap(constants.Cache, args); err != nil {
if err := cmdConfig.AddToConfigMap(cache, args); err != nil {
exit.WithError("Failed to update config", err)
}
},
Expand All @@ -56,7 +58,7 @@ var deleteCacheCmd = &cobra.Command{
Long: "Delete an image from the local cache.",
Run: func(cmd *cobra.Command, args []string) {
// Delete images from config file
if err := cmdConfig.DeleteFromConfigMap(constants.Cache, args); err != nil {
if err := cmdConfig.DeleteFromConfigMap(cache, args); err != nil {
exit.WithError("Failed to delete images from config", err)
}
// Delete images from cache/images directory
Expand All @@ -71,7 +73,7 @@ func imagesInConfigFile() ([]string, error) {
if err != nil {
return nil, err
}
if values, ok := configFile[constants.Cache]; ok {
if values, ok := configFile[cache]; ok {
var images []string
for key := range values.(map[string]interface{}) {
images = append(images, key)
Expand Down
7 changes: 4 additions & 3 deletions cmd/minikube/cmd/cache_list.go
Expand Up @@ -22,10 +22,11 @@ import (

"github.com/spf13/cobra"
cmdConfig "k8s.io/minikube/cmd/minikube/cmd/config"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit"
)

const defaultCacheListFormat = "{{.CacheImage}}\n"

var cacheListFormat string

// CacheListTemplate represents the cache list template
Expand All @@ -39,7 +40,7 @@ var listCacheCmd = &cobra.Command{
Short: "List all available images from the local cache.",
Long: "List all available images from the local cache.",
Run: func(cmd *cobra.Command, args []string) {
images, err := cmdConfig.ListConfigMap(constants.Cache)
images, err := cmdConfig.ListConfigMap(cache)
if err != nil {
exit.WithError("Failed to get image map", err)
}
Expand All @@ -50,7 +51,7 @@ var listCacheCmd = &cobra.Command{
}

func init() {
listCacheCmd.Flags().StringVar(&cacheListFormat, "format", constants.DefaultCacheListFormat,
listCacheCmd.Flags().StringVar(&cacheListFormat, "format", defaultCacheListFormat,
`Go template format string for the cache list output. The format for Go templates can be found here: https://golang.org/pkg/text/template/
For the list of accessible variables for the template, see the struct values here: https://godoc.org/k8s.io/minikube/cmd/minikube/cmd#CacheListTemplate`)
cacheCmd.AddCommand(listCacheCmd)
Expand Down
5 changes: 3 additions & 2 deletions cmd/minikube/cmd/config/addons_list.go
Expand Up @@ -23,10 +23,11 @@ import (

"github.com/spf13/cobra"
"k8s.io/minikube/pkg/minikube/assets"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit"
)

const defaultAddonListFormat = "- {{.AddonName}}: {{.AddonStatus}}\n"

var addonListFormat string

// AddonListTemplate represents the addon list template
Expand All @@ -51,7 +52,7 @@ var addonsListCmd = &cobra.Command{
}

func init() {
AddonsCmd.Flags().StringVar(&addonListFormat, "format", constants.DefaultAddonListFormat,
AddonsCmd.Flags().StringVar(&addonListFormat, "format", defaultAddonListFormat,
`Go template format string for the addon list output. The format for Go templates can be found here: https://golang.org/pkg/text/template/
For the list of accessible variables for the template, see the struct values here: https://godoc.org/k8s.io/minikube/cmd/minikube/cmd/config#AddonListTemplate`)
AddonsCmd.AddCommand(addonsListCmd)
Expand Down
6 changes: 4 additions & 2 deletions cmd/minikube/cmd/config/util.go
Expand Up @@ -27,13 +27,15 @@ import (
"k8s.io/minikube/pkg/minikube/cluster"
"k8s.io/minikube/pkg/minikube/command"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/minikube/storageclass"
)

// defaultStorageClassProvisioner is the name of the default storage class provisioner
const defaultStorageClassProvisioner = "standard"

// Runs all the validation or callback functions and collects errors
func run(name string, value string, fns []setFn) error {
var errors []error
Expand Down Expand Up @@ -205,7 +207,7 @@ func EnableOrDisableStorageClasses(name, val string) error {
return errors.Wrap(err, "Error parsing boolean")
}

class := constants.DefaultStorageClassProvisioner
class := defaultStorageClassProvisioner
if name == "storage-provisioner-gluster" {
class = "glusterfile"
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/minikube/cmd/config/view.go
Expand Up @@ -26,6 +26,8 @@ import (
"k8s.io/minikube/pkg/minikube/exit"
)

const defaultConfigViewFormat = "- {{.ConfigKey}}: {{.ConfigValue}}\n"

var viewFormat string

// ViewTemplate represents the view template
Expand All @@ -47,7 +49,7 @@ var configViewCmd = &cobra.Command{
}

func init() {
configViewCmd.Flags().StringVar(&viewFormat, "format", constants.DefaultConfigViewFormat,
configViewCmd.Flags().StringVar(&viewFormat, "format", defaultConfigViewFormat,
`Go template format string for the config view output. The format for Go templates can be found here: https://golang.org/pkg/text/template/
For the list of accessible variables for the template, see the struct values here: https://godoc.org/k8s.io/minikube/cmd/minikube/cmd/config#ConfigViewTemplate`)
ConfigCmd.AddCommand(configViewCmd)
Expand Down
12 changes: 8 additions & 4 deletions cmd/minikube/cmd/mount.go
Expand Up @@ -38,8 +38,12 @@ import (
"k8s.io/minikube/third_party/go9p/ufs"
)

// nineP is the value of --type used for the 9p filesystem.
const nineP = "9p"
const (
// nineP is the value of --type used for the 9p filesystem.
nineP = "9p"
defaultMountVersion = "9p2000.L"
defaultMsize = 262144
)

// placeholders for flag values
var mountIP string
Expand Down Expand Up @@ -202,13 +206,13 @@ var mountCmd = &cobra.Command{
func init() {
mountCmd.Flags().StringVar(&mountIP, "ip", "", "Specify the ip that the mount should be setup on")
mountCmd.Flags().StringVar(&mountType, "type", nineP, "Specify the mount filesystem type (supported types: 9p)")
mountCmd.Flags().StringVar(&mountVersion, "9p-version", constants.DefaultMountVersion, "Specify the 9p version that the mount should use")
mountCmd.Flags().StringVar(&mountVersion, "9p-version", defaultMountVersion, "Specify the 9p version that the mount should use")
mountCmd.Flags().BoolVar(&isKill, "kill", false, "Kill the mount process spawned by minikube start")
mountCmd.Flags().StringVar(&uid, "uid", "docker", "Default user id used for the mount")
mountCmd.Flags().StringVar(&gid, "gid", "docker", "Default group id used for the mount")
mountCmd.Flags().UintVar(&mode, "mode", 0755, "File permissions used for the mount")
mountCmd.Flags().StringSliceVar(&options, "options", []string{}, "Additional mount options, such as cache=fscache")
mountCmd.Flags().IntVar(&mSize, "msize", constants.DefaultMsize, "The number of bytes to use for 9p packet payload")
mountCmd.Flags().IntVar(&mSize, "msize", defaultMsize, "The number of bytes to use for 9p packet payload")
}

// getPort asks the kernel for a free open port that is ready to use
Expand Down
6 changes: 4 additions & 2 deletions cmd/minikube/cmd/root.go
Expand Up @@ -40,6 +40,8 @@ import (
"k8s.io/minikube/pkg/minikube/translate"
)

const defaultClusterBootstrapper = "kubeadm"

var dirs = [...]string{
localpath.MiniPath(),
localpath.MakeMiniPath("certs"),
Expand Down Expand Up @@ -161,7 +163,7 @@ func setFlagsUsingViper() {
func init() {
translate.DetermineLocale()
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.`)
RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", constants.DefaultClusterBootstrapper, "The name of the cluster bootstrapper that will set up the kubernetes cluster.")
RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", defaultClusterBootstrapper, "The name of the cluster bootstrapper that will set up the kubernetes cluster.")

groups := templates.CommandGroups{
{
Expand Down Expand Up @@ -243,7 +245,7 @@ func initConfig() {
}

func setupViper() {
viper.SetEnvPrefix(constants.MinikubeEnvPrefix)
viper.SetEnvPrefix(minikubeEnvPrefix)
// Replaces '-' in flags with '_' in env variables
// e.g. iso-url => $ENVPREFIX_ISO_URL
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
Expand Down
5 changes: 2 additions & 3 deletions cmd/minikube/cmd/root_test.go
Expand Up @@ -26,7 +26,6 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/tests"
)

Expand Down Expand Up @@ -97,7 +96,7 @@ func runCommand(f func(*cobra.Command, []string)) {
func hideEnv(t *testing.T) func(t *testing.T) {
envs := make(map[string]string)
for _, env := range os.Environ() {
if strings.HasPrefix(env, constants.MinikubeEnvPrefix) {
if strings.HasPrefix(env, minikubeEnvPrefix) {
line := strings.Split(env, "=")
key, val := line[0], line[1]
envs[key] = val
Expand Down Expand Up @@ -143,7 +142,7 @@ func TestViperConfig(t *testing.T) {
}

func getEnvVarName(name string) string {
return constants.MinikubeEnvPrefix + "_" + strings.ToUpper(name)
return minikubeEnvPrefix + "_" + strings.ToUpper(name)
}

func setValues(tt configTest) error {
Expand Down
43 changes: 27 additions & 16 deletions cmd/minikube/cmd/start.go
Expand Up @@ -85,6 +85,11 @@ const (
kvmQemuURI = "kvm-qemu-uri"
kvmGPU = "kvm-gpu"
kvmHidden = "kvm-hidden"
minikubeEnvPrefix = "MINIKUBE"
defaultEmbedCerts = false
defaultKeepContext = false
defaultMemorySize = "2000mb"
defaultDiskSize = "20000mb"
keepContext = "keep-context"
createMount = "mount"
featureGates = "feature-gates"
Expand All @@ -110,6 +115,12 @@ const (
interactive = "interactive"
waitTimeout = "wait-timeout"
nativeSSH = "native-ssh"
minimumMemorySize = "1024mb"
defaultCPUS = 2
minimumCPUS = 2
minimumDiskSize = "2000mb"
defaultVMDriver = constants.DriverVirtualbox
defaultMountEndpoint = "/minikube-host"
)

var (
Expand All @@ -136,7 +147,7 @@ func init() {

// initMinikubeFlags includes commandline flags for minikube.
func initMinikubeFlags() {
viper.SetEnvPrefix(constants.MinikubeEnvPrefix)
viper.SetEnvPrefix(minikubeEnvPrefix)
// Replaces '-' in flags with '_' in env variables
// e.g. iso-url => $ENVPREFIX_ISO_URL
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
Expand All @@ -145,17 +156,17 @@ func initMinikubeFlags() {
startCmd.Flags().Bool(force, false, "Force minikube to perform possibly dangerous operations")
startCmd.Flags().Bool(interactive, true, "Allow user prompts for more information")

startCmd.Flags().Int(cpus, constants.DefaultCPUS, "Number of CPUs allocated to the minikube VM.")
startCmd.Flags().String(memory, constants.DefaultMemorySize, "Amount of RAM allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).")
startCmd.Flags().String(humanReadableDiskSize, constants.DefaultDiskSize, "Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).")
startCmd.Flags().Int(cpus, defaultCPUS, "Number of CPUs allocated to the minikube VM.")
startCmd.Flags().String(memory, defaultMemorySize, "Amount of RAM allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).")
startCmd.Flags().String(humanReadableDiskSize, defaultDiskSize, "Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).")
startCmd.Flags().Bool(downloadOnly, false, "If true, only download and cache files for later use - don't install or start anything.")
startCmd.Flags().Bool(cacheImages, true, "If true, cache docker images for the current bootstrapper and load them into the machine. Always false with --vm-driver=none.")
startCmd.Flags().String(isoURL, constants.DefaultISOURL, "Location of the minikube iso.")
startCmd.Flags().Bool(keepContext, constants.DefaultKeepContext, "This will keep the existing kubectl context and will create a minikube context.")
startCmd.Flags().Bool(embedCerts, constants.DefaultEmbedCerts, "if true, will embed the certs in kubeconfig.")
startCmd.Flags().Bool(keepContext, defaultKeepContext, "This will keep the existing kubectl context and will create a minikube context.")
startCmd.Flags().Bool(embedCerts, defaultEmbedCerts, "if true, will embed the certs in kubeconfig.")
startCmd.Flags().String(containerRuntime, "docker", "The container runtime to be used (docker, crio, containerd).")
startCmd.Flags().Bool(createMount, false, "This will start the mount daemon and automatically mount files into minikube.")
startCmd.Flags().String(mountString, constants.DefaultMountDir+":"+constants.DefaultMountEndpoint, "The argument to pass the minikube mount command on start.")
startCmd.Flags().String(mountString, constants.DefaultMountDir+":"+defaultMountEndpoint, "The argument to pass the minikube mount command on start.")
startCmd.Flags().String(criSocket, "", "The cri socket path to be used.")
startCmd.Flags().String(networkPlugin, "", "The name of the network plugin.")
startCmd.Flags().Bool(enableDefaultCNI, false, "Enable the default CNI plugin (/etc/cni/net.d/k8s.conf). Used in conjunction with \"--network-plugin=cni\".")
Expand Down Expand Up @@ -476,7 +487,7 @@ func selectDriver(oldConfig *cfg.Config) string {
driver := viper.GetString("vm-driver")
// By default, the driver is whatever we used last time
if driver == "" {
driver = constants.DefaultVMDriver
driver = defaultVMDriver
if oldConfig != nil {
driver = oldConfig.MachineConfig.VMDriver
}
Expand Down Expand Up @@ -619,17 +630,17 @@ func validateUser(driver string) {
// validateFlags validates the supplied flags against known bad combinations
func validateFlags(driver string) {
diskSizeMB := pkgutil.CalculateSizeInMB(viper.GetString(humanReadableDiskSize))
if diskSizeMB < pkgutil.CalculateSizeInMB(constants.MinimumDiskSize) && !viper.GetBool(force) {
exit.WithCodeT(exit.Config, "Requested disk size {{.requested_size}} is less than minimum of {{.minimum_size}}", out.V{"requested_size": diskSizeMB, "minimum_size": pkgutil.CalculateSizeInMB(constants.MinimumDiskSize)})
if diskSizeMB < pkgutil.CalculateSizeInMB(minimumDiskSize) && !viper.GetBool(force) {
exit.WithCodeT(exit.Config, "Requested disk size {{.requested_size}} is less than minimum of {{.minimum_size}}", out.V{"requested_size": diskSizeMB, "minimum_size": pkgutil.CalculateSizeInMB(minimumDiskSize)})
}

memorySizeMB := pkgutil.CalculateSizeInMB(viper.GetString(memory))
if memorySizeMB < pkgutil.CalculateSizeInMB(constants.MinimumMemorySize) && !viper.GetBool(force) {
exit.UsageT("Requested memory allocation {{.requested_size}} is less than the minimum allowed of {{.minimum_size}}", out.V{"requested_size": memorySizeMB, "minimum_size": pkgutil.CalculateSizeInMB(constants.MinimumMemorySize)})
if memorySizeMB < pkgutil.CalculateSizeInMB(minimumMemorySize) && !viper.GetBool(force) {
exit.UsageT("Requested memory allocation {{.requested_size}} is less than the minimum allowed of {{.minimum_size}}", out.V{"requested_size": memorySizeMB, "minimum_size": pkgutil.CalculateSizeInMB(minimumMemorySize)})
}
if memorySizeMB < pkgutil.CalculateSizeInMB(constants.DefaultMemorySize) && !viper.GetBool(force) {
if memorySizeMB < pkgutil.CalculateSizeInMB(defaultMemorySize) && !viper.GetBool(force) {
out.T(out.Notice, "Requested memory allocation ({{.memory}}MB) is less than the default memory allocation of {{.default_memorysize}}MB. Beware that minikube might not work correctly or crash unexpectedly.",
out.V{"memory": memorySizeMB, "default_memorysize": pkgutil.CalculateSizeInMB(constants.DefaultMemorySize)})
out.V{"memory": memorySizeMB, "default_memorysize": pkgutil.CalculateSizeInMB(defaultMemorySize)})
}

var cpuCount int
Expand All @@ -648,8 +659,8 @@ func validateFlags(driver string) {
} else {
cpuCount = viper.GetInt(cpus)
}
if cpuCount < constants.MinimumCPUS {
exit.UsageT("Requested CPU count {{.requested_cpus}} is less than the minimum allowed of {{.minimum_cpus}}", out.V{"requested_cpus": cpuCount, "minimum_cpus": constants.MinimumCPUS})
if cpuCount < minimumCPUS {
exit.UsageT("Requested cpu count {{.requested_cpus}} is less than the minimum allowed of {{.minimum_cpus}}", out.V{"requested_cpus": cpuCount, "minimum_cpus": minimumCPUS})
}

// check that kubeadm extra args contain only whitelisted parameters
Expand Down
4 changes: 2 additions & 2 deletions cmd/minikube/cmd/start_test.go
Expand Up @@ -26,8 +26,8 @@ import (
)

func TestGenerateCfgFromFlagsHTTPProxyHandling(t *testing.T) {
viper.SetDefault(memory, constants.DefaultMemorySize)
viper.SetDefault(humanReadableDiskSize, constants.DefaultDiskSize)
viper.SetDefault(memory, defaultMemorySize)
viper.SetDefault(humanReadableDiskSize, defaultDiskSize)
originalEnv := os.Getenv("HTTP_PROXY")
defer func() {
err := os.Setenv("HTTP_PROXY", originalEnv)
Expand Down
7 changes: 6 additions & 1 deletion cmd/minikube/cmd/status.go
Expand Up @@ -48,6 +48,11 @@ const (
minikubeNotRunningStatusFlag = 1 << 0
clusterNotRunningStatusFlag = 1 << 1
k8sNotRunningStatusFlag = 1 << 2
defaultStatusFormat = `host: {{.Host}}
kubelet: {{.Kubelet}}
apiserver: {{.APIServer}}
kubectl: {{.Kubeconfig}}
`
)

// statusCmd represents the status command
Expand Down Expand Up @@ -140,7 +145,7 @@ var statusCmd = &cobra.Command{
}

func init() {
statusCmd.Flags().StringVar(&statusFormat, "format", constants.DefaultStatusFormat,
statusCmd.Flags().StringVar(&statusFormat, "format", defaultStatusFormat,
`Go template format string for the status output. The format for Go templates can be found here: https://golang.org/pkg/text/template/
For the list accessible variables for the template, see the struct values here: https://godoc.org/k8s.io/minikube/cmd/minikube/cmd#Status`)
}
9 changes: 4 additions & 5 deletions pkg/gvisor/disable.go
Expand Up @@ -23,17 +23,16 @@ import (

"github.com/docker/machine/libmachine/mcnutils"
"github.com/pkg/errors"
"k8s.io/minikube/pkg/minikube/constants"
)

// Disable reverts containerd config files and restarts containerd
func Disable() error {
log.Print("Disabling gvisor...")
if err := os.Remove(filepath.Join(nodeDir, constants.ContainerdConfigTomlPath)); err != nil {
return errors.Wrapf(err, "removing %s", constants.ContainerdConfigTomlPath)
if err := os.Remove(filepath.Join(nodeDir, containerdConfigTomlPath)); err != nil {
return errors.Wrapf(err, "removing %s", containerdConfigTomlPath)
}
log.Printf("Restoring default config.toml at %s", constants.ContainerdConfigTomlPath)
if err := mcnutils.CopyFile(filepath.Join(nodeDir, constants.StoredContainerdConfigTomlPath), filepath.Join(nodeDir, constants.ContainerdConfigTomlPath)); err != nil {
log.Printf("Restoring default config.toml at %s", containerdConfigTomlPath)
if err := mcnutils.CopyFile(filepath.Join(nodeDir, storedContainerdConfigTomlPath), filepath.Join(nodeDir, containerdConfigTomlPath)); err != nil {
return errors.Wrap(err, "reverting back to default config.toml")
}
// restart containerd
Expand Down

0 comments on commit 878c3ca

Please sign in to comment.