diff --git a/cmd/minikube/cmd/cache.go b/cmd/minikube/cmd/cache.go index 9d0a79dcc478..58ed5f66e673 100644 --- a/cmd/minikube/cmd/cache.go +++ b/cmd/minikube/cmd/cache.go @@ -29,6 +29,7 @@ import ( "k8s.io/minikube/pkg/minikube/node" "k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/reason" + "k8s.io/minikube/pkg/minikube/run" ) // cacheImageConfigKey is the config field name used to store which images we have previously cached @@ -52,7 +53,7 @@ var addCacheCmd = &cobra.Command{ out.WarningT("\"minikube cache\" will be deprecated in upcoming versions, please switch to \"minikube image load\"") options := flags.CommandOptions() // Cache and load images into docker daemon - if err := machine.CacheAndLoadImages(args, cacheAddProfiles(), false, options); err != nil { + if err := machine.CacheAndLoadImages(args, cacheAddProfiles(options), false, options); err != nil { exit.Error(reason.InternalCacheLoad, "Failed to cache and load images", err) } // Add images to config file @@ -66,18 +67,18 @@ func addCacheCmdFlags() { addCacheCmd.Flags().Bool(allFlag, false, "Add image to cache for all running minikube clusters") } -func cacheAddProfiles() []*config.Profile { +func cacheAddProfiles(options *run.CommandOptions) []*config.Profile { if viper.GetBool(allFlag) { - validProfiles, _, err := config.ListProfiles() // need to load image to all profiles + validProfiles, _, err := config.ListProfiles(options) // need to load image to all profiles if err != nil { klog.Warningf("error listing profiles: %v", err) } return validProfiles } - profile := viper.GetString(config.ProfileName) - p, err := config.LoadProfile(profile) + p, err := config.LoadProfile(options.ProfileName) if err != nil { - exit.Message(reason.Usage, "{{.profile}} profile is not valid: {{.err}}", out.V{"profile": profile, "err": err}) + exit.Message(reason.Usage, "{{.profile}} profile is not valid: {{.err}}", + out.V{"profile": options.ProfileName, "err": err}) } return []*config.Profile{p} } @@ -106,7 +107,7 @@ var reloadCacheCmd = &cobra.Command{ Long: "reloads images previously added using the 'cache add' subcommand", Run: func(_ *cobra.Command, _ []string) { options := flags.CommandOptions() - err := node.CacheAndLoadImagesInConfig(cacheAddProfiles(), options) + err := node.CacheAndLoadImagesInConfig(cacheAddProfiles(options), options) if err != nil { exit.Error(reason.GuestCacheLoad, "Failed to reload cached images", err) } diff --git a/cmd/minikube/cmd/config/addons_list.go b/cmd/minikube/cmd/config/addons_list.go index c373cb0c6fd4..c0ab31033f02 100644 --- a/cmd/minikube/cmd/config/addons_list.go +++ b/cmd/minikube/cmd/config/addons_list.go @@ -35,6 +35,7 @@ import ( "k8s.io/minikube/pkg/minikube/mustload" "k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/reason" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/minikube/style" ) @@ -63,7 +64,7 @@ var addonsListCmd = &cobra.Command{ } switch strings.ToLower(addonListOutput) { case "list": - printAddonsList(cc, addonPrintDocs) + printAddonsList(cc, addonPrintDocs, options) case "json": printAddonsJSON(cc) default: @@ -92,7 +93,7 @@ var stringFromStatus = func(addonStatus bool) string { return "disabled" } -var printAddonsList = func(cc *config.ClusterConfig, printDocs bool) { +var printAddonsList = func(cc *config.ClusterConfig, printDocs bool, options *run.CommandOptions) { addonNames := slices.Sorted(maps.Keys(assets.Addons)) table := tablewriter.NewWriter(os.Stdout) @@ -142,7 +143,7 @@ var printAddonsList = func(cc *config.ClusterConfig, printDocs bool) { if err := table.Render(); err != nil { klog.Error("Error rendering table", err) } - v, _, err := config.ListProfiles() + v, _, err := config.ListProfiles(options) if err != nil { klog.Errorf("list profiles returned error: %v", err) } diff --git a/cmd/minikube/cmd/config/addons_list_test.go b/cmd/minikube/cmd/config/addons_list_test.go index eadf74d1b88f..29f0ea3b7fb9 100644 --- a/cmd/minikube/cmd/config/addons_list_test.go +++ b/cmd/minikube/cmd/config/addons_list_test.go @@ -23,10 +23,14 @@ import ( "strings" "testing" + "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/out" + "k8s.io/minikube/pkg/minikube/run" ) func TestAddonsList(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} + tests := []struct { name string printDocs bool @@ -45,7 +49,7 @@ func TestAddonsList(t *testing.T) { old := os.Stdout defer func() { os.Stdout = old }() os.Stdout = w - printAddonsList(nil, tt.printDocs) + printAddonsList(nil, tt.printDocs, options) if err := w.Close(); err != nil { t.Fatalf("failed to close pipe: %v", err) } diff --git a/cmd/minikube/cmd/config/profile.go b/cmd/minikube/cmd/config/profile.go index aa569f596148..3a780bde368e 100644 --- a/cmd/minikube/cmd/config/profile.go +++ b/cmd/minikube/cmd/config/profile.go @@ -20,6 +20,7 @@ import ( "os" "github.com/spf13/cobra" + "k8s.io/minikube/cmd/minikube/cmd/flags" "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/kubeconfig" @@ -45,6 +46,7 @@ var ProfileCmd = &cobra.Command{ exit.Message(reason.Usage, "usage: minikube profile [MINIKUBE_PROFILE_NAME]") } + options := flags.CommandOptions() profile := args[0] // Check whether the profile name is container friendly if !config.ProfileNameValid(profile) { @@ -63,7 +65,7 @@ var ProfileCmd = &cobra.Command{ profile = "minikube" } else { // not validating when it is default profile - errProfile, ok := ValidateProfile(profile) + errProfile, ok := ValidateProfile(profile, options) if !ok && errProfile != nil { out.FailureT(errProfile.Msg) } diff --git a/cmd/minikube/cmd/config/profile_list.go b/cmd/minikube/cmd/config/profile_list.go index 36fb8294726e..fb51542b7b06 100644 --- a/cmd/minikube/cmd/config/profile_list.go +++ b/cmd/minikube/cmd/config/profile_list.go @@ -70,18 +70,18 @@ var profileListCmd = &cobra.Command{ }, } -func listProfiles() (validProfiles, invalidProfiles []*config.Profile, err error) { +func listProfiles(options *run.CommandOptions) (validProfiles, invalidProfiles []*config.Profile, err error) { if isLight { - validProfiles, err = config.ListValidProfiles() + validProfiles, err = config.ListValidProfiles(options) } else { - validProfiles, invalidProfiles, err = config.ListProfiles() + validProfiles, invalidProfiles, err = config.ListProfiles(options) } return validProfiles, invalidProfiles, err } func printProfilesTable(options *run.CommandOptions) { - validProfiles, invalidProfiles, err := listProfiles() + validProfiles, invalidProfiles, err := listProfiles(options) if err != nil { klog.Warningf("error loading profiles: %v", err) @@ -209,7 +209,7 @@ func warnInvalidProfiles(invalidProfiles []*config.Profile) { } func printProfilesJSON(options *run.CommandOptions) { - validProfiles, invalidProfiles, err := listProfiles() + validProfiles, invalidProfiles, err := listProfiles(options) updateProfilesStatus(validProfiles, options) var body = map[string]interface{}{} diff --git a/cmd/minikube/cmd/config/util.go b/cmd/minikube/cmd/config/util.go index 14a4a67f4450..e9fe7505673c 100644 --- a/cmd/minikube/cmd/config/util.go +++ b/cmd/minikube/cmd/config/util.go @@ -23,6 +23,7 @@ import ( "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/out" + "k8s.io/minikube/pkg/minikube/run" ) // Invoke all the validation or callback functions and collects errors @@ -105,9 +106,9 @@ func (e ErrValidateProfile) Error() string { } // ValidateProfile checks if the profile user is trying to switch exists, else throws error -func ValidateProfile(profile string) (*ErrValidateProfile, bool) { +func ValidateProfile(profile string, options *run.CommandOptions) (*ErrValidateProfile, bool) { - validProfiles, invalidProfiles, err := config.ListProfiles() + validProfiles, invalidProfiles, err := config.ListProfiles(options) if err != nil { out.FailureT(err.Error()) } diff --git a/cmd/minikube/cmd/config/util_test.go b/cmd/minikube/cmd/config/util_test.go index 4347cb407393..0b6004163571 100644 --- a/cmd/minikube/cmd/config/util_test.go +++ b/cmd/minikube/cmd/config/util_test.go @@ -21,7 +21,9 @@ import ( "testing" config "k8s.io/minikube/pkg/minikube/config" + "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/driver" + "k8s.io/minikube/pkg/minikube/run" ) var minikubeConfig = config.MinikubeConfig{ @@ -83,10 +85,11 @@ func TestSetBool(t *testing.T) { } func TestValidateProfile(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} testCases := []string{"82374328742_2974224498", "validate_test"} for _, name := range testCases { expected := fmt.Sprintf("profile %q not found", name) - err, ok := ValidateProfile(name) + err, ok := ValidateProfile(name, options) if !ok && err.Error() != expected { t.Errorf("got error %q, expected %q", err, expected) } diff --git a/cmd/minikube/cmd/delete.go b/cmd/minikube/cmd/delete.go index 2f59daf4a06f..c383ddeb7a1b 100644 --- a/cmd/minikube/cmd/delete.go +++ b/cmd/minikube/cmd/delete.go @@ -218,7 +218,7 @@ func runDelete(_ *cobra.Command, args []string) { out.SetJSON(outputFormat == "json") register.Reg.SetStep(register.Deleting) download.CleanUpOlderPreloads() - validProfiles, invalidProfiles, err := config.ListProfiles() + validProfiles, invalidProfiles, err := config.ListProfiles(options) if err != nil { klog.Warningf("'error loading profiles in minikube home %q: %v", localpath.MiniPath(), err) } @@ -333,7 +333,6 @@ func deleteProfile(ctx context.Context, profile *config.Profile, options *run.Co klog.Infof("Deleting %s", profile.Name) register.Reg.SetStep(register.Deleting) - viper.Set(config.ProfileName, profile.Name) if profile.Config != nil { klog.Infof("%s configuration: %+v", profile.Name, profile.Config) diff --git a/cmd/minikube/cmd/delete_test.go b/cmd/minikube/cmd/delete_test.go index 360258ae080c..e5eededb02ae 100644 --- a/cmd/minikube/cmd/delete_test.go +++ b/cmd/minikube/cmd/delete_test.go @@ -27,10 +27,10 @@ import ( "github.com/docker/machine/libmachine" "github.com/google/go-cmp/cmp" "github.com/otiai10/copy" - "github.com/spf13/viper" cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config" "k8s.io/minikube/pkg/minikube/config" + "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/localpath" "k8s.io/minikube/pkg/minikube/run" ) @@ -87,7 +87,6 @@ func TestDeleteProfile(t *testing.T) { {"partial-mach", "p8_partial_machine_config", []string{"p8_partial_machine_config"}}, } - options := &run.CommandOptions{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Setenv(localpath.MinikubeHome, td) @@ -107,6 +106,10 @@ func TestDeleteProfile(t *testing.T) { } hostAndDirsDeleter = hostAndDirsDeleterMock + + // Simulate minikube delete --profile PROFILE_NAME + options := &run.CommandOptions{ProfileName: profile.Name} + errs := DeleteProfiles([]*config.Profile{profile}, options) if len(errs) > 0 { HandleDeletionErrors(errs) @@ -141,8 +144,6 @@ func TestDeleteProfile(t *testing.T) { if diff := cmp.Diff(expectedMachines, afterMachines); diff != "" { t.Errorf("machines mismatch (-want +got):\n%s", diff) } - - viper.Set(config.ProfileName, "") }) } } @@ -157,6 +158,8 @@ func deleteContextTest() error { } func TestDeleteAllProfiles(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} + td := t.TempDir() if err := copy.Copy("../../../pkg/minikube/config/testdata/delete-all", td); err != nil { @@ -186,7 +189,7 @@ func TestDeleteAllProfiles(t *testing.T) { config.DockerContainers = func() ([]string, error) { return []string{}, nil } - validProfiles, inValidProfiles, err := config.ListProfiles() + validProfiles, inValidProfiles, err := config.ListProfiles(options) if err != nil { t.Error(err) } @@ -198,7 +201,7 @@ func TestDeleteAllProfiles(t *testing.T) { profiles := validProfiles profiles = append(profiles, inValidProfiles...) hostAndDirsDeleter = hostAndDirsDeleterMock - errs := DeleteProfiles(profiles, &run.CommandOptions{}) + errs := DeleteProfiles(profiles, options) if errs != nil { t.Errorf("errors while deleting all profiles: %v", errs) @@ -219,8 +222,6 @@ func TestDeleteAllProfiles(t *testing.T) { if len(afterMachines) != 0 { t.Errorf("Did not delete all machines, remaining: %v", afterMachines) } - - viper.Set(config.ProfileName, "") } // TestTryKillOne spawns a go child process that waits to be SIGKILLed, diff --git a/cmd/minikube/cmd/flags/flags.go b/cmd/minikube/cmd/flags/flags.go index e6d928a2305b..acd84f951764 100644 --- a/cmd/minikube/cmd/flags/flags.go +++ b/cmd/minikube/cmd/flags/flags.go @@ -18,6 +18,7 @@ package flags import ( "github.com/spf13/viper" + "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/run" ) @@ -25,6 +26,7 @@ import ( const ( Interactive = "interactive" DownloadOnly = "download-only" + Force = "force" ) // CommandOptions returns minikube runtime options from command line flags. @@ -34,5 +36,7 @@ func CommandOptions() *run.CommandOptions { return &run.CommandOptions{ NonInteractive: !viper.GetBool(Interactive), DownloadOnly: viper.GetBool(DownloadOnly), + ProfileName: viper.GetString(config.ProfileName), + Force: viper.GetBool(Force), } } diff --git a/cmd/minikube/cmd/mount.go b/cmd/minikube/cmd/mount.go index a04f7fc09aeb..e637c908d71e 100644 --- a/cmd/minikube/cmd/mount.go +++ b/cmd/minikube/cmd/mount.go @@ -246,7 +246,7 @@ var mountCmd = &cobra.Command{ } }() - err = cluster.Mount(co.CP.Runner, ip.String(), vmPath, cfg, pid) + err = cluster.Mount(co.CP.Runner, ip.String(), vmPath, cfg, pid, options) if err != nil { if rtErr, ok := err.(*cluster.MountError); ok && rtErr.ErrorType == cluster.MountErrorConnect { exit.Error(reason.GuestMountCouldNotConnect, "mount could not connect", rtErr) diff --git a/cmd/minikube/cmd/root.go b/cmd/minikube/cmd/root.go index 0d35165d5d2b..126fe263fb87 100644 --- a/cmd/minikube/cmd/root.go +++ b/cmd/minikube/cmd/root.go @@ -30,6 +30,7 @@ import ( "k8s.io/klog/v2" "k8s.io/kubectl/pkg/util/templates" configCmd "k8s.io/minikube/cmd/minikube/cmd/config" + "k8s.io/minikube/cmd/minikube/cmd/flags" "k8s.io/minikube/pkg/drivers/kic/oci" "k8s.io/minikube/pkg/minikube/audit" "k8s.io/minikube/pkg/minikube/config" @@ -64,6 +65,7 @@ var RootCmd = &cobra.Command{ Short: "minikube quickly sets up a local Kubernetes cluster", Long: `minikube provisions and manages local Kubernetes clusters optimized for development workflows.`, PersistentPreRun: func(_ *cobra.Command, _ []string) { + options := flags.CommandOptions() for _, path := range dirs { if err := os.MkdirAll(path, 0777); err != nil { exit.Error(reason.HostHomeMkdir, "Error creating minikube directory", err) @@ -75,7 +77,7 @@ var RootCmd = &cobra.Command{ exit.Message(reason.Usage, "User name must be 60 chars or less.") } var err error - auditID, err = audit.LogCommandStart() + auditID, err = audit.LogCommandStart(options) if err != nil { klog.Warningf("failed to log command start to audit: %v", err) } diff --git a/cmd/minikube/cmd/start.go b/cmd/minikube/cmd/start.go index 4aaa307d564b..4ff0d2cf6759 100644 --- a/cmd/minikube/cmd/start.go +++ b/cmd/minikube/cmd/start.go @@ -173,7 +173,7 @@ func runStart(cmd *cobra.Command, _ []string) { go notify.MaybePrintUpdateTextFromGithub(options) displayEnviron(os.Environ()) - if viper.GetBool(force) { + if options.Force { out.WarningT("minikube skips various validations when --force is supplied; this may lead to unexpected behavior") } @@ -202,13 +202,13 @@ func runStart(cmd *cobra.Command, _ []string) { } if existing != nil { - upgradeExistingConfig(cmd, existing) + upgradeExistingConfig(cmd, existing, options) } else { - validateProfileName() + validateProfileName(options) } validateSpecifiedDriver(existing, options) - validateKubernetesVersion(existing) + validateKubernetesVersion(existing, options) validateContainerRuntime(existing) ds, alts, specified := selectDriver(existing, options) @@ -228,11 +228,9 @@ func runStart(cmd *cobra.Command, _ []string) { } } - useForce := viper.GetBool(force) - starter, err := provisionWithDriver(cmd, ds, existing, options) if err != nil { - node.ExitIfFatal(err, useForce) + node.ExitIfFatal(err, options.Force) machine.MaybeDisplayAdvice(err, ds.Name) if specified { // If the user specified a driver, don't fallback to anything else @@ -289,7 +287,7 @@ func runStart(cmd *cobra.Command, _ []string) { configInfo, err := startWithDriver(cmd, starter, existing, options) if err != nil { - node.ExitIfFatal(err, useForce) + node.ExitIfFatal(err, options.Force) exit.Error(reason.GuestStart, "failed to start node", err) } @@ -307,7 +305,7 @@ func runStart(cmd *cobra.Command, _ []string) { func provisionWithDriver(cmd *cobra.Command, ds registry.DriverState, existing *config.ClusterConfig, options *run.CommandOptions) (node.Starter, error) { driverName := ds.Name klog.Infof("selected driver: %s", driverName) - validateDriver(ds, existing) + validateDriver(ds, existing, options) err := autoSetDriverOptions(cmd, driverName) if err != nil { klog.Errorf("Error autoSetOptions : %v", err) @@ -315,8 +313,8 @@ func provisionWithDriver(cmd *cobra.Command, ds registry.DriverState, existing * virtualBoxMacOS13PlusWarning(driverName) hyperkitDeprecationWarning(driverName) - validateFlags(cmd, driverName) - validateUser(driverName) + validateFlags(cmd, driverName, options) + validateUser(driverName, options) if driverName == oci.Docker { validateDockerStorageDriver(driverName) } @@ -651,7 +649,7 @@ func maybeDeleteAndRetry(cmd *cobra.Command, existing config.ClusterConfig, n co } // Re-generate the cluster config, just in case the failure was related to an old config format - cc := updateExistingConfigFromFlags(cmd, &existing) + cc := updateExistingConfigFromFlags(cmd, &existing, options) var configInfo *kubeconfig.Settings for _, n := range cc.Nodes { @@ -846,8 +844,8 @@ func hostDriver(existing *config.ClusterConfig, options *run.CommandOptions) str } // validateProfileName makes sure that new profile name not duplicated with any of machine names in existing multi-node clusters. -func validateProfileName() { - profiles, err := config.ListValidProfiles() +func validateProfileName(options *run.CommandOptions) { + profiles, err := config.ListValidProfiles(options) if err != nil { exit.Message(reason.InternalListConfig, "Unable to list profiles: {{.error}}", out.V{"error": err}) } @@ -923,7 +921,7 @@ func validateSpecifiedDriver(existing *config.ClusterConfig, options *run.Comman } // validateDriver validates that the selected driver appears sane, exits if not -func validateDriver(ds registry.DriverState, existing *config.ClusterConfig) { +func validateDriver(ds registry.DriverState, existing *config.ClusterConfig, options *run.CommandOptions) { driverName := ds.Name osName := detect.RuntimeOS() arch := detect.RuntimeArch() @@ -960,7 +958,7 @@ func validateDriver(ds registry.DriverState, existing *config.ClusterConfig) { r := reason.MatchKnownIssue(reason.Kind{}, st.Error, runtime.GOOS) if r != nil && r.ID != "" { - exitIfNotForced(*r, st.Error.Error()) + exitIfNotForced(options, *r, st.Error.Error()) } if !st.Installed { @@ -985,13 +983,14 @@ func validateDriver(ds registry.DriverState, existing *config.ClusterConfig) { code = reason.ExProviderNotRunning } - exitIfNotForced(reason.Kind{ - ID: id, - Advice: translate.T(st.Fix), - ExitCode: code, - URL: st.Doc, - Style: style.Fatal, - }, st.Error.Error()) + exitIfNotForced(options, + reason.Kind{ + ID: id, + Advice: translate.T(st.Fix), + ExitCode: code, + URL: st.Doc, + Style: style.Fatal, + }, st.Error.Error()) } func selectImageRepository(mirrorCountry string, v semver.Version) (bool, string, error) { @@ -1046,18 +1045,16 @@ var checkRepository = func(v semver.Version, repo string) error { } // validateUser validates minikube is run by the recommended user (privileged or regular) -func validateUser(drvName string) { +func validateUser(drvName string, options *run.CommandOptions) { u, err := user.Current() if err != nil { klog.Errorf("Error getting the current user: %v", err) return } - useForce := viper.GetBool(force) - // None driver works with root and without root on Linux if runtime.GOOS == "linux" && drvName == driver.None { - if !viper.GetBool(flags.Interactive) { + if options.NonInteractive { test := exec.Command("sudo", "-n", "echo", "-n") if err := test.Run(); err != nil { exit.Message(reason.DrvNeedsRoot, `sudo requires a password, and --interactive=false`) @@ -1081,7 +1078,7 @@ func validateUser(drvName string) { out.ErrT(style.Tip, "Tip: To remove this root owned cluster, run: sudo {{.cmd}}", out.V{"cmd": mustload.ExampleCmd(cname, "delete")}) } - if !useForce { + if !options.Force { exit.Message(reason.DrvAsRoot, `The "{{.driver_name}}" driver should not be used with root privileges.`, out.V{"driver_name": drvName}) } } @@ -1154,7 +1151,7 @@ func suggestMemoryAllocation(sysLimit, containerLimit, nodes int) int { } // validateRequestedMemorySize validates the memory size matches the minimum recommended -func validateRequestedMemorySize(req int, drvName string) { +func validateRequestedMemorySize(req int, drvName string, options *run.CommandOptions) { // TODO: Fix MB vs MiB confusion sysLimit, containerLimit, err := memoryLimits(drvName) if err != nil { @@ -1165,16 +1162,16 @@ func validateRequestedMemorySize(req int, drvName string) { if driver.IsKIC(drvName) && containerLimit < minUsableMem { if driver.IsDockerDesktop(drvName) { if runtime.GOOS == "darwin" { - exitIfNotForced(reason.RsrcInsufficientDarwinDockerMemory, "Docker Desktop only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": containerLimit, "req": minUsableMem, "recommend": "2.25 GB"}) + exitIfNotForced(options, reason.RsrcInsufficientDarwinDockerMemory, "Docker Desktop only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": containerLimit, "req": minUsableMem, "recommend": "2.25 GB"}) } else { - exitIfNotForced(reason.RsrcInsufficientWindowsDockerMemory, "Docker Desktop only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": containerLimit, "req": minUsableMem, "recommend": "2.25 GB"}) + exitIfNotForced(options, reason.RsrcInsufficientWindowsDockerMemory, "Docker Desktop only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": containerLimit, "req": minUsableMem, "recommend": "2.25 GB"}) } } - exitIfNotForced(reason.RsrcInsufficientContainerMemory, "{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": containerLimit, "driver": drvName, "req": minUsableMem}) + exitIfNotForced(options, reason.RsrcInsufficientContainerMemory, "{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": containerLimit, "driver": drvName, "req": minUsableMem}) } if sysLimit < minUsableMem { - exitIfNotForced(reason.RsrcInsufficientSysMemory, "System only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": sysLimit, "req": minUsableMem}) + exitIfNotForced(options, reason.RsrcInsufficientSysMemory, "System only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes", out.V{"size": sysLimit, "req": minUsableMem}) } // if --memory=no-limit, ignore remaining checks @@ -1183,7 +1180,7 @@ func validateRequestedMemorySize(req int, drvName string) { } if req < minUsableMem { - exitIfNotForced(reason.RsrcInsufficientReqMemory, "Requested memory allocation {{.requested}}MiB is less than the usable minimum of {{.minimum_memory}}MB", out.V{"requested": req, "minimum_memory": minUsableMem}) + exitIfNotForced(options, reason.RsrcInsufficientReqMemory, "Requested memory allocation {{.requested}}MiB is less than the usable minimum of {{.minimum_memory}}MB", out.V{"requested": req, "minimum_memory": minUsableMem}) } if req < minRecommendedMem { if driver.IsDockerDesktop(drvName) { @@ -1199,7 +1196,7 @@ func validateRequestedMemorySize(req int, drvName string) { advised := suggestMemoryAllocation(sysLimit, containerLimit, viper.GetInt(nodes)) if req > sysLimit { - exitIfNotForced(reason.Kind{ID: "RSRC_OVER_ALLOC_MEM", Advice: "Start minikube with less memory allocated: 'minikube start --memory={{.advised}}mb'"}, + exitIfNotForced(options, reason.Kind{ID: "RSRC_OVER_ALLOC_MEM", Advice: "Start minikube with less memory allocated: 'minikube start --memory={{.advised}}mb'"}, `Requested memory allocation {{.requested}}MB is more than your system limit {{.system_limit}}MB.`, out.V{"requested": req, "system_limit": sysLimit, "advised": advised}) } @@ -1213,12 +1210,12 @@ func validateRequestedMemorySize(req int, drvName string) { } if driver.IsHyperV(drvName) && req%2 == 1 { - exitIfNotForced(reason.RsrcInvalidHyperVMemory, "Hyper-V requires that memory MB be an even number, {{.memory}}MB was specified, try passing `--memory {{.suggestMemory}}`", out.V{"memory": req, "suggestMemory": req - 1}) + exitIfNotForced(options, reason.RsrcInvalidHyperVMemory, "Hyper-V requires that memory MB be an even number, {{.memory}}MB was specified, try passing `--memory {{.suggestMemory}}`", out.V{"memory": req, "suggestMemory": req - 1}) } } // validateCPUCount validates the cpu count matches the minimum recommended & not exceeding the available cpu count -func validateCPUCount(drvName string) { +func validateCPUCount(drvName string, options *run.CommandOptions) { var availableCPUs int cpuCount := getCPUCount(drvName) @@ -1243,11 +1240,11 @@ func validateCPUCount(drvName string) { if availableCPUs < 2 { if drvName == oci.Docker && runtime.GOOS == "darwin" { - exitIfNotForced(reason.RsrcInsufficientDarwinDockerCores, "Docker Desktop has less than 2 CPUs configured, but Kubernetes requires at least 2 to be available") + exitIfNotForced(options, reason.RsrcInsufficientDarwinDockerCores, "Docker Desktop has less than 2 CPUs configured, but Kubernetes requires at least 2 to be available") } else if drvName == oci.Docker && runtime.GOOS == "windows" { - exitIfNotForced(reason.RsrcInsufficientWindowsDockerCores, "Docker Desktop has less than 2 CPUs configured, but Kubernetes requires at least 2 to be available") + exitIfNotForced(options, reason.RsrcInsufficientWindowsDockerCores, "Docker Desktop has less than 2 CPUs configured, but Kubernetes requires at least 2 to be available") } else { - exitIfNotForced(reason.RsrcInsufficientCores, "{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available", out.V{"driver_name": driver.FullName(viper.GetString("driver"))}) + exitIfNotForced(options, reason.RsrcInsufficientCores, "{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available", out.V{"driver_name": driver.FullName(viper.GetString("driver"))}) } } @@ -1257,7 +1254,7 @@ func validateCPUCount(drvName string) { } if cpuCount < minimumCPUS { - exitIfNotForced(reason.RsrcInsufficientCores, "Requested cpu count {{.requested_cpus}} is less than the minimum allowed of {{.minimum_cpus}}", out.V{"requested_cpus": cpuCount, "minimum_cpus": minimumCPUS}) + exitIfNotForced(options, reason.RsrcInsufficientCores, "Requested cpu count {{.requested_cpus}} is less than the minimum allowed of {{.minimum_cpus}}", out.V{"requested_cpus": cpuCount, "minimum_cpus": minimumCPUS}) } if availableCPUs < cpuCount { @@ -1272,16 +1269,16 @@ func validateCPUCount(drvName string) { } } - exitIfNotForced(reason.RsrcInsufficientCores, "Requested cpu count {{.requested_cpus}} is greater than the available cpus of {{.avail_cpus}}", out.V{"requested_cpus": cpuCount, "avail_cpus": availableCPUs}) + exitIfNotForced(options, reason.RsrcInsufficientCores, "Requested cpu count {{.requested_cpus}} is greater than the available cpus of {{.avail_cpus}}", out.V{"requested_cpus": cpuCount, "avail_cpus": availableCPUs}) } } // validateFlags validates the supplied flags against known bad combinations -func validateFlags(cmd *cobra.Command, drvName string) { //nolint:gocyclo +func validateFlags(cmd *cobra.Command, drvName string, options *run.CommandOptions) { //nolint:gocyclo if cmd.Flags().Changed(humanReadableDiskSize) { err := validateDiskSize(viper.GetString(humanReadableDiskSize)) if err != nil { - exitIfNotForced(reason.Usage, "{{.err}}", out.V{"err": err}) + exitIfNotForced(options, reason.Usage, "{{.err}}", out.V{"err": err}) } } @@ -1291,14 +1288,14 @@ func validateFlags(cmd *cobra.Command, drvName string) { //nolint:gocyclo } } - validateCPUCount(drvName) + validateCPUCount(drvName, options) if drvName == driver.None && viper.GetBool(noKubernetes) { exit.Message(reason.Usage, "Cannot use the option --no-kubernetes on the {{.name}} driver", out.V{"name": drvName}) } if cmd.Flags().Changed(memory) { - validateChangedMemoryFlags(drvName) + validateChangedMemoryFlags(drvName, options) } if cmd.Flags().Changed(listenAddress) { @@ -1329,7 +1326,7 @@ func validateFlags(cmd *cobra.Command, drvName string) { //nolint:gocyclo if err != nil { exit.Message(reason.Usage, "{{.err}}", out.V{"err": err}) } - validateCNI(cmd, viper.GetString(containerRuntime)) + validateCNI(cmd, viper.GetString(containerRuntime), options) } if cmd.Flags().Changed(staticIP) { @@ -1537,12 +1534,12 @@ func defaultRuntime() string { } // if container runtime is not docker, check that cni is not disabled -func validateCNI(cmd *cobra.Command, runtimeName string) { +func validateCNI(cmd *cobra.Command, runtimeName string, options *run.CommandOptions) { if runtimeName == constants.Docker { return } if cmd.Flags().Changed(cniFlag) && strings.ToLower(viper.GetString(cniFlag)) == "false" { - if viper.GetBool(force) { + if options.Force { out.WarnReason(reason.Usage, "You have chosen to disable the CNI but the \"{{.name}}\" container runtime requires CNI", out.V{"name": runtimeName}) } else { exit.Message(reason.Usage, "The \"{{.name}}\" container runtime requires CNI", out.V{"name": runtimeName}) @@ -1551,7 +1548,7 @@ func validateCNI(cmd *cobra.Command, runtimeName string) { } // validateChangedMemoryFlags validates memory related flags. -func validateChangedMemoryFlags(drvName string) { +func validateChangedMemoryFlags(drvName string, options *run.CommandOptions) { if driver.IsKIC(drvName) && !oci.HasMemoryCgroup() { out.WarningT("Your cgroup does not allow setting memory.") out.Infof("More information: https://docs.docker.com/engine/install/linux-postinstall/#your-kernel-does-not-support-cgroup-swap-limit-capabilities") @@ -1576,10 +1573,10 @@ func validateChangedMemoryFlags(drvName string) { } req, err = util.CalculateSizeInMB(memString) if err != nil { - exitIfNotForced(reason.Usage, "Unable to parse memory '{{.memory}}': {{.error}}", out.V{"memory": memString, "error": err}) + exitIfNotForced(options, reason.Usage, "Unable to parse memory '{{.memory}}': {{.error}}", out.V{"memory": memString, "error": err}) } } - validateRequestedMemorySize(req, drvName) + validateRequestedMemorySize(req, drvName, options) } func noLimitMemory(sysLimit, containerLimit int, drvName string) int { @@ -1783,7 +1780,7 @@ func autoSetDriverOptions(cmd *cobra.Command, drvName string) (err error) { } // validateKubernetesVersion ensures that the requested version is reasonable -func validateKubernetesVersion(old *config.ClusterConfig) { +func validateKubernetesVersion(old *config.ClusterConfig, options *run.CommandOptions) { paramVersion := viper.GetString(kubernetesVersion) paramVersion = strings.TrimPrefix(strings.ToLower(paramVersion), version.VersionPrefix) kubernetesVer, err := getKubernetesVersion(old) @@ -1811,10 +1808,10 @@ func validateKubernetesVersion(old *config.ClusterConfig) { } if nvs.Major > newestVersion.Major { out.WarningT("Specified Major version of Kubernetes {{.specifiedMajor}} is newer than the newest supported Major version: {{.newestMajor}}", out.V{"specifiedMajor": nvs.Major, "newestMajor": newestVersion.Major}) - if !viper.GetBool(force) { + if !options.Force { out.WarningT("You can force an unsupported Kubernetes version via the --force flag") } - exitIfNotForced(reason.KubernetesTooNew, "Kubernetes {{.version}} is not supported by this release of minikube", out.V{"version": nvs}) + exitIfNotForced(options, reason.KubernetesTooNew, "Kubernetes {{.version}} is not supported by this release of minikube", out.V{"version": nvs}) } if nvs.GT(newestVersion) { out.WarningT("Specified Kubernetes version {{.specified}} is newer than the newest supported version: {{.newest}}. Use `minikube config defaults kubernetes-version` for details.", out.V{"specified": nvs, "newest": constants.NewestKubernetesVersion}) @@ -1824,23 +1821,23 @@ func validateKubernetesVersion(old *config.ClusterConfig) { out.WarningT("Specified Kubernetes version {{.specified}} not found in Kubernetes version list", out.V{"specified": nvs}) out.Styled(style.Verifying, "Searching the internet for Kubernetes version...") found, err := cmdcfg.IsInGitHubKubernetesVersions(kubernetesVer) - if err != nil && !viper.GetBool(force) { + if err != nil && !options.Force { exit.Error(reason.KubernetesNotConnect, "error fetching Kubernetes version list from GitHub", err) } if found { out.Styled(style.Check, "Kubernetes version {{.specified}} found in GitHub version list", out.V{"specified": nvs}) - } else if !viper.GetBool(force) { + } else if !options.Force { out.WarningT("Kubernetes version not found in GitHub version list. You can force a Kubernetes version via the --force flag") - exitIfNotForced(reason.KubernetesTooNew, "Kubernetes version {{.version}} is not supported by this release of minikube", out.V{"version": nvs}) + exitIfNotForced(options, reason.KubernetesTooNew, "Kubernetes version {{.version}} is not supported by this release of minikube", out.V{"version": nvs}) } } } if nvs.LT(oldestVersion) { out.WarningT("Specified Kubernetes version {{.specified}} is less than the oldest supported version: {{.oldest}}. Use `minikube config defaults kubernetes-version` for details.", out.V{"specified": nvs, "oldest": constants.OldestKubernetesVersion}) - if !viper.GetBool(force) { + if !options.Force { out.WarningT("You can force an unsupported Kubernetes version via the --force flag") } - exitIfNotForced(reason.KubernetesTooOld, "Kubernetes {{.version}} is not supported by this release of minikube", out.V{"version": nvs}) + exitIfNotForced(options, reason.KubernetesTooOld, "Kubernetes {{.version}} is not supported by this release of minikube", out.V{"version": nvs}) } // If the version of Kubernetes has a known issue, print a warning out to the screen @@ -2040,8 +2037,8 @@ func validateBareMetal(drvName string) { } } -func exitIfNotForced(r reason.Kind, message string, v ...out.V) { - if !viper.GetBool(force) { +func exitIfNotForced(options *run.CommandOptions, r reason.Kind, message string, v ...out.V) { + if !options.Force { exit.Message(r, message, v...) } out.Error(r, message, v...) diff --git a/cmd/minikube/cmd/start_flags.go b/cmd/minikube/cmd/start_flags.go index c7627f0468da..d5bb910b0ef6 100644 --- a/cmd/minikube/cmd/start_flags.go +++ b/cmd/minikube/cmd/start_flags.go @@ -105,7 +105,6 @@ const ( dnsProxy = "dns-proxy" hostDNSResolver = "host-dns-resolver" waitComponents = "wait" - force = "force" dryRun = "dry-run" waitTimeout = "wait-timeout" nativeSSH = "native-ssh" @@ -159,7 +158,7 @@ func initMinikubeFlags() { // e.g. iso-url => $ENVPREFIX_ISO_URL viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.AutomaticEnv() - startCmd.Flags().Bool(force, false, "Force minikube to perform possibly dangerous operations") + startCmd.Flags().Bool(flags.Force, false, "Force minikube to perform possibly dangerous operations") startCmd.Flags().Bool(flags.Interactive, true, "Allow user prompts for more information") startCmd.Flags().Bool(dryRun, false, "dry-run mode. Validates configuration, but does not mutate system state") @@ -317,7 +316,7 @@ func ClusterFlagValue() string { func generateClusterConfig(cmd *cobra.Command, existing *config.ClusterConfig, k8sVersion string, rtime string, drvName string, options *run.CommandOptions) (config.ClusterConfig, config.Node, error) { var cc config.ClusterConfig if existing != nil { - cc = updateExistingConfigFromFlags(cmd, existing) + cc = updateExistingConfigFromFlags(cmd, existing, options) // identify appropriate cni then configure cruntime accordingly if _, err := cni.New(&cc); err != nil { @@ -382,7 +381,7 @@ func getCPUCount(drvName string) int { return si.CPUs } -func getMemorySize(cmd *cobra.Command, drvName string) int { +func getMemorySize(cmd *cobra.Command, drvName string, options *run.CommandOptions) int { sysLimit, containerLimit, err := memoryLimits(drvName) if err != nil { klog.Warningf("Unable to query memory limits: %+v", err) @@ -406,7 +405,7 @@ func getMemorySize(cmd *cobra.Command, drvName string) int { exit.Message(reason.Usage, "{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB", out.V{"container_limit": containerLimit, "specified_memory": mem, "driver_name": driver.FullName(drvName)}) } } else { - validateRequestedMemorySize(mem, drvName) + validateRequestedMemorySize(mem, drvName, options) klog.Infof("Using suggested %dMB memory alloc based on sys=%dMB, container=%dMB", mem, sysLimit, containerLimit) } @@ -576,7 +575,7 @@ func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime str KicBaseImage: viper.GetString(kicBaseImage), Network: getNetwork(drvName, options), Subnet: viper.GetString(subnet), - Memory: getMemorySize(cmd, drvName), + Memory: getMemorySize(cmd, drvName, options), CPUs: getCPUCount(drvName), DiskSize: getDiskSize(), Driver: drvName, @@ -749,7 +748,7 @@ func checkNumaCount(k8sVersion string) { } // upgradeExistingConfig upgrades legacy configuration files -func upgradeExistingConfig(cmd *cobra.Command, cc *config.ClusterConfig) { +func upgradeExistingConfig(cmd *cobra.Command, cc *config.ClusterConfig, options *run.CommandOptions) { if cc == nil { return } @@ -772,7 +771,7 @@ func upgradeExistingConfig(cmd *cobra.Command, cc *config.ClusterConfig) { if cc.Memory == 0 && !driver.IsKIC(cc.Driver) { klog.Info("Existing config file was missing memory. (could be an old minikube config), will use the default value") - memInMB := getMemorySize(cmd, cc.Driver) + memInMB := getMemorySize(cmd, cc.Driver, options) cc.Memory = memInMB } @@ -783,8 +782,8 @@ func upgradeExistingConfig(cmd *cobra.Command, cc *config.ClusterConfig) { // updateExistingConfigFromFlags will update the existing config from the flags - used on a second start // skipping updating existing docker env, docker opt, InsecureRegistry, registryMirror, extra-config, apiserver-ips -func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterConfig) config.ClusterConfig { //nolint to suppress cyclomatic complexity 45 of func `updateExistingConfigFromFlags` is high (> 30) - validateFlags(cmd, existing.Driver) +func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterConfig, options *run.CommandOptions) config.ClusterConfig { //nolint to suppress cyclomatic complexity 45 of func `updateExistingConfigFromFlags` is high (> 30) + validateFlags(cmd, existing.Driver, options) cc := *existing @@ -802,7 +801,7 @@ func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterC updateIntFromFlag(cmd, &cc.APIServerPort, apiServerPort) } - if cmd.Flags().Changed(memory) && getMemorySize(cmd, cc.Driver) != cc.Memory { + if cmd.Flags().Changed(memory) && getMemorySize(cmd, cc.Driver, options) != cc.Memory { out.WarningT("You cannot change the memory size for an existing minikube cluster. Please first delete the cluster.") } @@ -811,7 +810,7 @@ func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterC } // validate the memory size in case user changed their system memory limits (example change docker desktop or upgraded memory.) - validateRequestedMemorySize(cc.Memory, cc.Driver) + validateRequestedMemorySize(cc.Memory, cc.Driver, options) if cmd.Flags().Changed(humanReadableDiskSize) && getDiskSize() != existing.DiskSize { out.WarningT("You cannot change the disk size for an existing minikube cluster. Please first delete the cluster.") diff --git a/cmd/minikube/cmd/stop.go b/cmd/minikube/cmd/stop.go index 789570197c26..23a45f9bb003 100644 --- a/cmd/minikube/cmd/stop.go +++ b/cmd/minikube/cmd/stop.go @@ -84,7 +84,7 @@ func runStop(_ *cobra.Command, _ []string) { // new code var profilesToStop []string if stopAll { - validProfiles, _, err := config.ListProfiles() + validProfiles, _, err := config.ListProfiles(options) if err != nil { klog.Warningf("'error loading profiles in minikube home %q: %v", localpath.MiniPath(), err) } diff --git a/pkg/addons/addons.go b/pkg/addons/addons.go index cc34641b6aaf..e42d25f2f461 100644 --- a/pkg/addons/addons.go +++ b/pkg/addons/addons.go @@ -31,7 +31,6 @@ import ( "github.com/blang/semver/v4" "github.com/docker/machine/libmachine/state" "github.com/pkg/errors" - "github.com/spf13/viper" "k8s.io/klog/v2" "k8s.io/minikube/pkg/drivers/kic/oci" @@ -270,7 +269,7 @@ func EnableOrDisableAddon(cc *config.ClusterConfig, name string, val string, opt } // Persist images even if the machine is running so starting gets the correct images. - images, customRegistries, err := assets.SelectAndPersistImages(addon, cc) + images, customRegistries, err := assets.SelectAndPersistImages(addon, cc, options) if err != nil { exit.Error(reason.HostSaveProfile, "Failed to persist images", err) } @@ -476,7 +475,7 @@ func verifyAddonStatus(cc *config.ClusterConfig, name string, val string, option return verifyAddonStatusInternal(cc, name, val, ns, options) } -func verifyAddonStatusInternal(cc *config.ClusterConfig, name string, val string, ns string, _ *run.CommandOptions) error { +func verifyAddonStatusInternal(cc *config.ClusterConfig, name string, val string, ns string, options *run.CommandOptions) error { klog.Infof("Verifying addon %s=%s in %q", name, val, cc.Name) enable, err := strconv.ParseBool(val) if err != nil { @@ -486,7 +485,7 @@ func verifyAddonStatusInternal(cc *config.ClusterConfig, name string, val string label, ok := addonPodLabels[name] if ok && enable { out.Step(style.HealthCheck, "Verifying {{.addon_name}} addon...", out.V{"addon_name": name}) - client, err := kapi.Client(viper.GetString(config.ProfileName)) + client, err := kapi.Client(options.ProfileName) if err != nil { return errors.Wrapf(err, "get kube-client to validate %s addon: %v", name, err) } diff --git a/pkg/minikube/assets/addons.go b/pkg/minikube/assets/addons.go index ca4755311fd0..538369fffd04 100644 --- a/pkg/minikube/assets/addons.go +++ b/pkg/minikube/assets/addons.go @@ -29,6 +29,7 @@ import ( "k8s.io/minikube/deploy/addons" "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/out" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/minikube/vmpath" "k8s.io/minikube/pkg/util" "k8s.io/minikube/pkg/version" @@ -831,7 +832,7 @@ func overrideDefaults(def, override map[string]string) map[string]string { } // SelectAndPersistImages selects which images to use based on addon default images, previously persisted images, and newly requested images - which are then persisted for future enables. -func SelectAndPersistImages(addon *Addon, cc *config.ClusterConfig) (images, customRegistries map[string]string, _ error) { +func SelectAndPersistImages(addon *Addon, cc *config.ClusterConfig, options *run.CommandOptions) (images, customRegistries map[string]string, _ error) { addonDefaultImages := addon.Images if addonDefaultImages == nil { addonDefaultImages = make(map[string]string) @@ -880,7 +881,7 @@ func SelectAndPersistImages(addon *Addon, cc *config.ClusterConfig) (images, cus if viper.IsSet(config.AddonImages) || viper.IsSet(config.AddonRegistries) { // Since these values are only set when a user enables an addon, it is safe to refer to the profile name. // Whether err is nil or not we still return here. - return images, customRegistries, config.Write(viper.GetString(config.ProfileName), cc) + return images, customRegistries, config.Write(options.ProfileName, cc) } return images, customRegistries, nil } diff --git a/pkg/minikube/assets/addons_test.go b/pkg/minikube/assets/addons_test.go index de5c995ab1a5..85dc99af826d 100644 --- a/pkg/minikube/assets/addons_test.go +++ b/pkg/minikube/assets/addons_test.go @@ -24,6 +24,8 @@ import ( "github.com/spf13/viper" "k8s.io/minikube/pkg/minikube/config" + "k8s.io/minikube/pkg/minikube/constants" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/minikube/tests" ) @@ -45,7 +47,7 @@ func mapsEqual(a, b map[string]string) bool { func TestParseMapString(t *testing.T) { cases := map[string]map[string]string{ - "Aardvark=1,B=2,Cantaloupe=3": {"Aardvark": "1", "B": "2", "Cantaloupe": "3"}, + "Aardvark=1,B=2,Cantaloupe=3": {"Aardvark": "1", "B": "2", "Cantaloupe": "3"}, "A=,B=2,C=": {"A": "", "B": "2", "C": ""}, "": {}, "malformed,good=howdy,manyequals==,": {"good": "howdy"}, @@ -156,9 +158,10 @@ func TestSelectAndPersistImages(t *testing.T) { gcpAuth := Addons["gcp-auth"] gcpAuthImages := gcpAuth.Images + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} // this test will write to ~/.minikube/profiles/minikube/config.json so need to create the file home := tests.MakeTempDir(t) - profilePath := filepath.Join(home, "profiles", "minikube") + profilePath := filepath.Join(home, "profiles", options.ProfileName) if err := os.MkdirAll(profilePath, 0777); err != nil { t.Fatalf("failed to create profile directory: %v", err) } @@ -176,7 +179,7 @@ func TestSelectAndPersistImages(t *testing.T) { } test := func(t *testing.T, cc *config.ClusterConfig, e expected) (images, registries map[string]string) { - images, registries, err := SelectAndPersistImages(gcpAuth, cc) + images, registries, err := SelectAndPersistImages(gcpAuth, cc, options) if err != nil { t.Fatal(err) } diff --git a/pkg/minikube/audit/audit.go b/pkg/minikube/audit/audit.go index 939fbdf39a88..d327253aa93d 100644 --- a/pkg/minikube/audit/audit.go +++ b/pkg/minikube/audit/audit.go @@ -30,6 +30,7 @@ import ( "github.com/spf13/viper" "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/constants" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/version" ) @@ -56,12 +57,12 @@ func args() string { } // Log details about the executed command. -func LogCommandStart() (string, error) { +func LogCommandStart(options *run.CommandOptions) (string, error) { if !shouldLog() { return "", nil } id := uuid.New().String() - r := newRow(pflag.Arg(0), args(), userName(), version.GetVersion(), time.Now(), id) + r := newRow(pflag.Arg(0), args(), userName(), version.GetVersion(), time.Now(), id, options) if err := appendToLog(r); err != nil { return "", err } diff --git a/pkg/minikube/audit/audit_test.go b/pkg/minikube/audit/audit_test.go index b5d1773e193c..43ef3ab99b41 100644 --- a/pkg/minikube/audit/audit_test.go +++ b/pkg/minikube/audit/audit_test.go @@ -26,6 +26,8 @@ import ( "github.com/spf13/pflag" "github.com/spf13/viper" "k8s.io/minikube/pkg/minikube/config" + "k8s.io/minikube/pkg/minikube/constants" + "k8s.io/minikube/pkg/minikube/run" ) func TestAudit(t *testing.T) { @@ -202,6 +204,7 @@ func TestAudit(t *testing.T) { // Check if logging with limited args causes a panic t.Run("LogCommandStart", func(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} oldArgs := os.Args defer func() { os.Args = oldArgs }() os.Args = []string{"minikube", "start"} @@ -212,7 +215,7 @@ func TestAudit(t *testing.T) { pflag.Parse() }() mockArgs(t, os.Args) - auditID, err := LogCommandStart() + auditID, err := LogCommandStart(options) if err != nil { t.Fatal(err) } @@ -222,6 +225,7 @@ func TestAudit(t *testing.T) { }) t.Run("LogCommandEnd", func(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} oldArgs := os.Args defer func() { os.Args = oldArgs }() os.Args = []string{"minikube", "start"} @@ -233,7 +237,7 @@ func TestAudit(t *testing.T) { pflag.Parse() }() mockArgs(t, os.Args) - auditID, err := LogCommandStart() + auditID, err := LogCommandStart(options) if err != nil { t.Fatalf("start failed: %v", err) } diff --git a/pkg/minikube/audit/logFile_test.go b/pkg/minikube/audit/logFile_test.go index a7ea9751fff4..1d81013b1837 100644 --- a/pkg/minikube/audit/logFile_test.go +++ b/pkg/minikube/audit/logFile_test.go @@ -24,7 +24,9 @@ import ( "time" "github.com/google/uuid" + "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/localpath" + "k8s.io/minikube/pkg/minikube/run" ) func TestLogFile(t *testing.T) { @@ -40,6 +42,7 @@ func TestLogFile(t *testing.T) { }) t.Run("AppendToLog", func(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} f, err := os.CreateTemp("", "audit.json") if err != nil { t.Fatalf("Error creating temporary file: %v", err) @@ -49,7 +52,7 @@ func TestLogFile(t *testing.T) { currentLogFile = f defer closeAuditLog() - r := newRow("start", "-v", "user1", "v0.17.1", time.Now(), uuid.New().String()) + r := newRow("start", "-v", "user1", "v0.17.1", time.Now(), uuid.New().String(), options) if err := appendToLog(r); err != nil { t.Fatalf("Error appendingToLog: %v", err) } diff --git a/pkg/minikube/audit/row.go b/pkg/minikube/audit/row.go index 454f75bc69e2..7a86fc3e3f84 100644 --- a/pkg/minikube/audit/row.go +++ b/pkg/minikube/audit/row.go @@ -24,9 +24,8 @@ import ( "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" - "github.com/spf13/viper" - "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/constants" + "k8s.io/minikube/pkg/minikube/run" ) // row is the log of a single command. @@ -81,15 +80,11 @@ func (e *row) toMap() map[string]string { } // newRow creates a new audit row. -func newRow(command string, args string, user string, version string, startTime time.Time, id string, profile ...string) *row { - p := viper.GetString(config.ProfileName) - if len(profile) > 0 { - p = profile[0] - } +func newRow(command string, args string, user string, version string, startTime time.Time, id string, options *run.CommandOptions) *row { return &row{ args: args, command: command, - profile: p, + profile: options.ProfileName, startTime: startTime.Format(constants.TimeFormat), user: user, version: version, diff --git a/pkg/minikube/audit/row_test.go b/pkg/minikube/audit/row_test.go index a9512348582e..ca53f72876ea 100644 --- a/pkg/minikube/audit/row_test.go +++ b/pkg/minikube/audit/row_test.go @@ -25,12 +25,14 @@ import ( "github.com/google/uuid" "k8s.io/minikube/pkg/minikube/constants" + "k8s.io/minikube/pkg/minikube/run" ) func TestRow(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} + c := "start" a := "--alsologtostderr" - p := "profile1" u := "user1" v := "v0.17.1" st := time.Now() @@ -39,7 +41,7 @@ func TestRow(t *testing.T) { etFormatted := et.Format(constants.TimeFormat) id := uuid.New().String() - r := newRow(c, a, u, v, st, id, p) + r := newRow(c, a, u, v, st, id, options) r.endTime = etFormatted t.Run("NewRow", func(t *testing.T) { @@ -50,7 +52,7 @@ func TestRow(t *testing.T) { }{ {"command", r.command, c}, {"args", r.args, a}, - {"profile", r.profile, p}, + {"profile", r.profile, options.ProfileName}, {"user", r.user, u}, {"version", r.version, v}, {"startTime", r.startTime, stFormatted}, @@ -82,7 +84,7 @@ func TestRow(t *testing.T) { }{ {"command", c}, {"args", a}, - {"profile", p}, + {"profile", options.ProfileName}, {"user", u}, {"version", v}, {"startTime", stFormatted}, @@ -100,7 +102,7 @@ func TestRow(t *testing.T) { t.Run("toFields", func(t *testing.T) { got := r.toFields() gotString := strings.Join(got, ",") - want := []string{c, a, p, u, v, stFormatted, etFormatted} + want := []string{c, a, options.ProfileName, u, v, stFormatted, etFormatted} wantString := strings.Join(want, ",") if gotString != wantString { @@ -109,7 +111,9 @@ func TestRow(t *testing.T) { }) t.Run("assignFields", func(t *testing.T) { - l := fmt.Sprintf(`{"data":{"args":"%s","command":"%s","id":"%s","profile":"%s","startTime":"%s","user":"%s","version":"v0.17.1"},"datacontenttype":"application/json","id":"bc6ec9d4-0d08-4b57-ac3b-db8d67774768","source":"https://minikube.sigs.k8s.io/","specversion":"1.0","type":"io.k8s.sigs.minikube.audit"}`, a, c, id, p, stFormatted, u) + l := fmt.Sprintf( + `{"data":{"args":"%s","command":"%s","id":"%s","profile":"%s","startTime":"%s","user":"%s","version":"v0.17.1"},"datacontenttype":"application/json","id":"bc6ec9d4-0d08-4b57-ac3b-db8d67774768","source":"https://minikube.sigs.k8s.io/","specversion":"1.0","type":"io.k8s.sigs.minikube.audit"}`, + a, c, id, options.ProfileName, stFormatted, u) r := &row{} if err := json.Unmarshal([]byte(l), r); err != nil { @@ -125,7 +129,7 @@ func TestRow(t *testing.T) { }{ {"command", r.command, c}, {"args", r.args, a}, - {"profile", r.profile, p}, + {"profile", r.profile, options.ProfileName}, {"user", r.user, u}, {"version", r.version, v}, {"startTime", r.startTime, stFormatted}, diff --git a/pkg/minikube/cluster/mount.go b/pkg/minikube/cluster/mount.go index 1670fbdaff52..c389688682d5 100644 --- a/pkg/minikube/cluster/mount.go +++ b/pkg/minikube/cluster/mount.go @@ -25,13 +25,13 @@ import ( "strings" "github.com/pkg/errors" - "github.com/spf13/viper" "k8s.io/klog/v2" "k8s.io/minikube/pkg/minikube/command" "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/localpath" "k8s.io/minikube/pkg/minikube/reason" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/util/lock" ) @@ -80,7 +80,7 @@ func (m *MountError) Error() string { } // Mount runs the mount command from the 9p client on the VM to the 9p server on the host -func Mount(r mountRunner, source string, target string, c *MountConfig, pid int) error { +func Mount(r mountRunner, source string, target string, c *MountConfig, pid int, options *run.CommandOptions) error { if err := Unmount(r, target); err != nil { return &MountError{ErrorType: MountErrorUnknown, UnderlyingError: errors.Wrap(err, "umount")} } @@ -97,8 +97,7 @@ func Mount(r mountRunner, source string, target string, c *MountConfig, pid int) return &MountError{ErrorType: MountErrorUnknown, UnderlyingError: errors.Wrapf(err, "mount with cmd %s ", rr.Command())} } - profile := viper.GetString("profile") - if err := lock.AppendToFile(filepath.Join(localpath.Profile(profile), constants.MountProcessFileName), []byte(fmt.Sprintf(" %s", strconv.Itoa(pid))), 0o644); err != nil { + if err := lock.AppendToFile(filepath.Join(localpath.Profile(options.ProfileName), constants.MountProcessFileName), []byte(fmt.Sprintf(" %s", strconv.Itoa(pid))), 0o644); err != nil { exit.Error(reason.HostMountPid, "Error writing mount pid", err) } diff --git a/pkg/minikube/config/profile.go b/pkg/minikube/config/profile.go index b9f7ea9da82f..8c682458dee0 100644 --- a/pkg/minikube/config/profile.go +++ b/pkg/minikube/config/profile.go @@ -24,11 +24,11 @@ import ( "regexp" "strings" - "github.com/spf13/viper" "k8s.io/klog/v2" "k8s.io/minikube/pkg/drivers/kic/oci" "k8s.io/minikube/pkg/minikube/kubeconfig" "k8s.io/minikube/pkg/minikube/localpath" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/util/lock" ) @@ -116,7 +116,7 @@ func CreateEmptyProfile(name string, miniHome ...string) error { } // SaveNode saves a node to a cluster -func SaveNode(cfg *ClusterConfig, node *Node) error { +func SaveNode(cfg *ClusterConfig, node *Node, options *run.CommandOptions) error { update := false for i, n := range cfg.Nodes { if n.Name == node.Name { @@ -130,7 +130,7 @@ func SaveNode(cfg *ClusterConfig, node *Node) error { cfg.Nodes = append(cfg.Nodes, *node) } - return SaveProfile(viper.GetString(ProfileName), cfg) + return SaveProfile(options.ProfileName, cfg) } // SaveProfile creates an profile out of the cfg and stores in $MINIKUBE_HOME/profiles//config.json @@ -188,8 +188,8 @@ var DockerContainers = func() ([]string, error) { // ListProfiles returns all valid and invalid (if any) minikube profiles // invalidPs are the profiles that have a directory or config file but not usable // invalidPs would be suggested to be deleted -func ListProfiles(miniHome ...string) (validPs []*Profile, inValidPs []*Profile, err error) { - activeP := viper.GetString(ProfileName) +func ListProfiles(options *run.CommandOptions, miniHome ...string) (validPs []*Profile, inValidPs []*Profile, err error) { + activeP := options.ProfileName // try to get profiles list based on left over evidences such as directory pDirs, err := profileDirs(miniHome...) if err != nil { @@ -234,13 +234,13 @@ func ListProfiles(miniHome ...string) (validPs []*Profile, inValidPs []*Profile, // ListValidProfiles returns profiles in minikube home dir // Unlike `ListProfiles` this function doesn't try to get profile from container -func ListValidProfiles(miniHome ...string) (ps []*Profile, err error) { +func ListValidProfiles(options *run.CommandOptions, miniHome ...string) (ps []*Profile, err error) { // try to get profiles list based on left over evidences such as directory pDirs, err := profileDirs(miniHome...) if err != nil { return nil, err } - activeP := viper.GetString(ProfileName) + activeP := options.ProfileName for _, n := range pDirs { p, err := LoadProfile(n, miniHome...) if err == nil && p.IsValid() { diff --git a/pkg/minikube/config/profile_test.go b/pkg/minikube/config/profile_test.go index 27bc32929a07..b5ecf20425e4 100644 --- a/pkg/minikube/config/profile_test.go +++ b/pkg/minikube/config/profile_test.go @@ -20,11 +20,14 @@ import ( "path/filepath" "testing" - "github.com/spf13/viper" + "k8s.io/minikube/pkg/minikube/constants" + "k8s.io/minikube/pkg/minikube/run" ) // TestListProfiles uses a different MINIKUBE_HOME with rest of tests since it relies on file list index func TestListProfiles(t *testing.T) { + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} + miniDir, err := filepath.Abs("./testdata/profile/.minikube") if err != nil { t.Errorf("error getting dir path for ./testdata/.minikube : %v", err) @@ -53,7 +56,7 @@ func TestListProfiles(t *testing.T) { DockerContainers = func() ([]string, error) { return []string{}, nil } - val, inv, err := ListProfiles(miniDir) + val, inv, err := ListProfiles(options, miniDir) num := len(testCasesValidProfs) + len(testCasesInValidProfs) if num != len(val)+len(inv) { @@ -288,8 +291,6 @@ func TestGetPrimaryControlPlane(t *testing.T) { t.Fatalf("Failed to load config for %s", tc.description) } - // get control-plane node - viper.Set(ProfileName, tc.profile) n, err := ControlPlane(*cc) if err != nil { t.Fatalf("Unexpected error getting primary control plane: %v", err) diff --git a/pkg/minikube/machine/cluster_test.go b/pkg/minikube/machine/cluster_test.go index 546d2ec95da7..1ec8bed21eb8 100644 --- a/pkg/minikube/machine/cluster_test.go +++ b/pkg/minikube/machine/cluster_test.go @@ -25,6 +25,7 @@ import ( // Driver used by testdata "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/download" + "k8s.io/minikube/pkg/minikube/localpath" _ "k8s.io/minikube/pkg/minikube/registry/drvs/virtualbox" "k8s.io/minikube/pkg/minikube/run" @@ -32,15 +33,20 @@ import ( "github.com/docker/machine/libmachine/host" "github.com/docker/machine/libmachine/provision" "github.com/docker/machine/libmachine/state" - "github.com/spf13/viper" "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/driver" "k8s.io/minikube/pkg/minikube/registry" "k8s.io/minikube/pkg/minikube/tests" ) -func createMockDriverHost(_ config.ClusterConfig, _ config.Node) (interface{}, error) { - return nil, nil +func createMockDriverHost(cfg config.ClusterConfig, n config.Node) (interface{}, error) { + return &tests.MockDriver{ + BaseDriver: drivers.BaseDriver{ + MachineName: config.MachineName(cfg, n), + StorePath: localpath.MiniPath(), + SSHUser: "docker", + }, + }, nil } func RegisterMockDriver(t *testing.T) { @@ -66,38 +72,39 @@ func RegisterMockDriver(t *testing.T) { } var defaultClusterConfig = config.ClusterConfig{ - Name: viper.GetString("profile"), + Name: constants.DefaultClusterName, Driver: driver.Mock, DockerEnv: []string{"MOCK_MAKE_IT_PROVISION=true"}, - Nodes: []config.Node{{Name: "minikube"}}, + Nodes: []config.Node{{Name: constants.DefaultClusterName}}, } func TestCreateHost(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} download.DownloadMock = download.CreateDstDownloadMock RegisterMockDriver(t) api := tests.NewMockAPI(t) - exists, _ := api.Exists(viper.GetString("profile")) + exists, _ := api.Exists(options.ProfileName) if exists { t.Fatal("Machine already exists.") } - _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Fatalf("Error creating host: %v", err) } - exists, err = api.Exists(viper.GetString("profile")) + exists, err = api.Exists(options.ProfileName) if err != nil { - t.Fatalf("exists failed for %q: %v", viper.GetString("profile"), err) + t.Fatalf("exists failed for %q: %v", options.ProfileName, err) } if !exists { - t.Fatalf("%q does not exist, but should.", viper.GetString("profile")) + t.Fatalf("%q does not exist, but should.", options.ProfileName) } - h, err := api.Load(viper.GetString("profile")) + h, err := api.Load(options.ProfileName) if err != nil { t.Fatalf("Error loading machine: %v", err) } @@ -122,13 +129,14 @@ func TestCreateHost(t *testing.T) { func TestStartHostExists(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} download.DownloadMock = download.CreateDstDownloadMock RegisterMockDriver(t) api := tests.NewMockAPI(t) // Create an initial host. - ih, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + ih, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Fatalf("Error creating host: %v", err) } @@ -146,12 +154,12 @@ func TestStartHostExists(t *testing.T) { mc.Name = ih.Name // This should pass without calling Create because the host exists already. - h, _, err := StartHost(api, &mc, &(mc.Nodes[0])) + h, _, err := StartHost(api, &mc, &(mc.Nodes[0]), options) if err != nil { t.Fatalf("Error starting host: %v", err) } - if h.Name != viper.GetString("profile") { - t.Fatalf("GetMachineName()=%q, want %q", viper.GetString("profile"), h.Name) + if h.Name != options.ProfileName { + t.Fatalf("GetMachineName()=%q, want %q", options.ProfileName, h.Name) } if s, _ := h.Driver.GetState(); s != state.Running { t.Fatalf("Machine not started.") @@ -161,13 +169,14 @@ func TestStartHostExists(t *testing.T) { func TestStartHostErrMachineNotExist(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} download.DownloadMock = download.CreateDstDownloadMock RegisterMockDriver(t) api := tests.NewMockAPI(t) // Create an incomplete host with machine does not exist error(i.e. User Interrupt Cancel) api.NotExistError = true - h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}, options) if err != nil { t.Fatalf("Error creating host: %v", err) } @@ -181,7 +190,7 @@ func TestStartHostErrMachineNotExist(t *testing.T) { n := config.Node{Name: h.Name} // This should pass with creating host, while machine does not exist. - h, _, err = StartHost(api, &mc, &n) + h, _, err = StartHost(api, &mc, &n, options) if err != nil { if err != constants.ErrMachineMissing { t.Fatalf("Error starting host: %v", err) @@ -194,13 +203,13 @@ func TestStartHostErrMachineNotExist(t *testing.T) { n.Name = h.Name // Second call. This should pass without calling Create because the host exists already. - h, _, err = StartHost(api, &mc, &n) + h, _, err = StartHost(api, &mc, &n, options) if err != nil { t.Fatalf("Error starting host: %v", err) } - if h.Name != viper.GetString("profile") { - t.Fatalf("GetMachineName()=%q, want %q", viper.GetString("profile"), h.Name) + if h.Name != options.ProfileName { + t.Fatalf("GetMachineName()=%q, want %q", options.ProfileName, h.Name) } if s, _ := h.Driver.GetState(); s != state.Running { t.Fatalf("Machine not started.") @@ -210,12 +219,13 @@ func TestStartHostErrMachineNotExist(t *testing.T) { func TestStartStoppedHost(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} download.DownloadMock = download.CreateDstDownloadMock RegisterMockDriver(t) api := tests.NewMockAPI(t) // Create an initial host. - h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Fatalf("Error creating host: %v", err) } @@ -228,11 +238,11 @@ func TestStartStoppedHost(t *testing.T) { mc := defaultClusterConfig mc.Name = h.Name n := config.Node{Name: h.Name} - h, _, err = StartHost(api, &mc, &n) + h, _, err = StartHost(api, &mc, &n, options) if err != nil { t.Fatal("Error starting host.") } - if h.Name != viper.GetString("profile") { + if h.Name != options.ProfileName { t.Fatalf("Machine created with incorrect name: %s", h.Name) } @@ -249,6 +259,7 @@ func TestStartStoppedHost(t *testing.T) { func TestStartHost(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} download.DownloadMock = download.CreateDstDownloadMock RegisterMockDriver(t) @@ -257,12 +268,12 @@ func TestStartHost(t *testing.T) { md := &tests.MockDetector{Provisioner: &tests.MockProvisioner{}} provision.SetDetector(md) - h, _, err := StartHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + h, _, err := StartHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Fatal("Error starting host.") } - if h.Name != viper.GetString("profile") { - t.Fatalf("GetMachineName()=%q, want %q", viper.GetString("profile"), h.Name) + if h.Name != options.ProfileName { + t.Fatalf("GetMachineName()=%q, want %q", options.ProfileName, h.Name) } if exists, _ := api.Exists(h.Name); !exists { t.Fatal("Machine not saved.") @@ -281,6 +292,7 @@ func TestStartHost(t *testing.T) { func TestStartHostConfig(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} download.DownloadMock = download.CreateDstDownloadMock RegisterMockDriver(t) @@ -295,7 +307,7 @@ func TestStartHostConfig(t *testing.T) { DockerOpt: []string{"param=value"}, } - h, _, err := StartHost(api, &cfg, &config.Node{Name: "minikube"}) + h, _, err := StartHost(api, &cfg, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Fatal("Error starting host.") } @@ -317,7 +329,7 @@ func TestStartHostConfig(t *testing.T) { func TestStopHostError(t *testing.T) { RegisterMockDriver(t) api := tests.NewMockAPI(t) - if err := StopHost(api, viper.GetString("profile")); err == nil { + if err := StopHost(api, constants.DefaultClusterName); err == nil { t.Fatal("An error should be thrown when stopping non-existing machine.") } } @@ -325,16 +337,17 @@ func TestStopHostError(t *testing.T) { func TestStopHost(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} RegisterMockDriver(t) api := tests.NewMockAPI(t) - h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Errorf("createHost failed: %v", err) } cc := defaultClusterConfig - cc.Name = viper.GetString("profile") - m := config.MachineName(cc, config.Node{Name: "minikube"}) + cc.Name = options.ProfileName + m := config.MachineName(cc, config.Node{Name: options.ProfileName}) if err := StopHost(api, m); err != nil { t.Fatalf("Unexpected error stopping machine: %v", err) } @@ -346,16 +359,17 @@ func TestStopHost(t *testing.T) { func TestDeleteHost(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} RegisterMockDriver(t) api := tests.NewMockAPI(t) - if _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}); err != nil { + if _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options); err != nil { t.Errorf("createHost failed: %v", err) } cc := defaultClusterConfig - cc.Name = viper.GetString("profile") + cc.Name = options.ProfileName - if err := DeleteHost(api, config.MachineName(cc, config.Node{Name: "minikube"}), false); err != nil { + if err := DeleteHost(api, config.MachineName(cc, config.Node{Name: options.ProfileName}), false); err != nil { t.Fatalf("Unexpected error deleting host: %v", err) } } @@ -363,9 +377,10 @@ func TestDeleteHost(t *testing.T) { func TestDeleteHostErrorDeletingVM(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} RegisterMockDriver(t) api := tests.NewMockAPI(t) - h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + h, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Errorf("createHost failed: %v", err) } @@ -373,7 +388,7 @@ func TestDeleteHostErrorDeletingVM(t *testing.T) { d := &tests.MockDriver{RemoveError: true, T: t} h.Driver = d - if err := DeleteHost(api, config.MachineName(defaultClusterConfig, config.Node{Name: "minikube"}), false); err == nil { + if err := DeleteHost(api, config.MachineName(defaultClusterConfig, config.Node{Name: options.ProfileName}), false); err == nil { t.Fatal("Expected error deleting host.") } } @@ -381,14 +396,15 @@ func TestDeleteHostErrorDeletingVM(t *testing.T) { func TestDeleteHostErrorDeletingFiles(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} RegisterMockDriver(t) api := tests.NewMockAPI(t) api.RemoveError = true - if _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}); err != nil { + if _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options); err != nil { t.Errorf("createHost failed: %v", err) } - if err := DeleteHost(api, config.MachineName(defaultClusterConfig, config.Node{Name: "minikube"}), false); err == nil { + if err := DeleteHost(api, config.MachineName(defaultClusterConfig, config.Node{Name: options.ProfileName}), false); err == nil { t.Fatal("Expected error deleting host.") } } @@ -396,30 +412,32 @@ func TestDeleteHostErrorDeletingFiles(t *testing.T) { func TestDeleteHostErrMachineNotExist(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} RegisterMockDriver(t) api := tests.NewMockAPI(t) // Create an incomplete host with machine does not exist error(i.e. User Interrupt Cancel) api.NotExistError = true - _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: "minikube"}) + _, err := createHost(api, &defaultClusterConfig, &config.Node{Name: options.ProfileName}, options) if err != nil { t.Errorf("createHost failed: %v", err) } - if err := DeleteHost(api, config.MachineName(defaultClusterConfig, config.Node{Name: "minikube"}), false); err == nil { - t.Fatal("Expected error deleting host.") + if err := DeleteHost(api, config.MachineName(defaultClusterConfig, config.Node{Name: options.ProfileName}), false); err != nil { + t.Fatal("Deleting host with missing machine should not fail") } } func TestStatus(t *testing.T) { tests.MakeTempDir(t) + options := &run.CommandOptions{ProfileName: constants.DefaultClusterName} RegisterMockDriver(t) api := tests.NewMockAPI(t) cc := defaultClusterConfig - cc.Name = viper.GetString("profile") + cc.Name = options.ProfileName - m := config.MachineName(cc, config.Node{Name: "minikube"}) + m := config.MachineName(cc, config.Node{Name: options.ProfileName}) checkState := func(expected string, machineName string) { s, err := Status(api, machineName) @@ -433,13 +451,13 @@ func TestStatus(t *testing.T) { checkState(state.None.String(), m) - if _, err := createHost(api, &cc, &config.Node{Name: "minikube"}); err != nil { + if _, err := createHost(api, &cc, &config.Node{Name: options.ProfileName}, options); err != nil { t.Errorf("createHost failed: %v", err) } - cc.Name = viper.GetString("profile") + cc.Name = options.ProfileName - m = config.MachineName(cc, config.Node{Name: "minikube"}) + m = config.MachineName(cc, config.Node{Name: options.ProfileName}) checkState(state.Running.String(), m) diff --git a/pkg/minikube/machine/fix.go b/pkg/minikube/machine/fix.go index 082e624d422c..8ed800495a89 100644 --- a/pkg/minikube/machine/fix.go +++ b/pkg/minikube/machine/fix.go @@ -34,6 +34,7 @@ import ( "k8s.io/minikube/pkg/minikube/driver" "k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out/register" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/minikube/style" ) @@ -49,7 +50,7 @@ const ( ) // fixHost fixes up a previously configured VM so that it is ready to run Kubernetes -func fixHost(api libmachine.API, cc *config.ClusterConfig, n *config.Node) (*host.Host, error) { +func fixHost(api libmachine.API, cc *config.ClusterConfig, n *config.Node, options *run.CommandOptions) (*host.Host, error) { start := time.Now() klog.Infof("fixHost starting: %s", n.Name) defer func() { @@ -60,14 +61,14 @@ func fixHost(api libmachine.API, cc *config.ClusterConfig, n *config.Node) (*hos if err != nil { return h, errors.Wrap(err, "error loading existing host. Please try running [minikube delete], then run [minikube start] again") } - defer postStartValidations(h, cc.Driver) + defer postStartValidations(h, cc.Driver, options) driverName := h.Driver.DriverName() // check if need to re-run docker-env maybeWarnAboutEvalEnv(driverName, cc.Name) - h, err = recreateIfNeeded(api, cc, n, h) + h, err = recreateIfNeeded(api, cc, n, h, options) if err != nil { return h, err } @@ -103,7 +104,7 @@ func fixHost(api libmachine.API, cc *config.ClusterConfig, n *config.Node) (*hos return h, nil } -func recreateIfNeeded(api libmachine.API, cc *config.ClusterConfig, n *config.Node, h *host.Host) (*host.Host, error) { +func recreateIfNeeded(api libmachine.API, cc *config.ClusterConfig, n *config.Node, h *host.Host, options *run.CommandOptions) (*host.Host, error) { machineName := config.MachineName(*cc, *n) machineType := driver.MachineType(cc.Driver) recreated := false @@ -124,7 +125,7 @@ func recreateIfNeeded(api libmachine.API, cc *config.ClusterConfig, n *config.No klog.Infof("Sleeping 1 second for extra luck!") time.Sleep(1 * time.Second) - h, err = createHost(api, cc, n) + h, err = createHost(api, cc, n, options) if err != nil { return nil, errors.Wrap(err, "recreate") } @@ -153,7 +154,7 @@ func recreateIfNeeded(api libmachine.API, cc *config.ClusterConfig, n *config.No MaybeDisplayAdvice(err, h.DriverName) return h, errors.Wrap(err, "driver start") } - if err := saveHost(api, h, cc, n); err != nil { + if err := saveHost(api, h, cc, n, options); err != nil { return h, err } diff --git a/pkg/minikube/machine/machine.go b/pkg/minikube/machine/machine.go index 5142ad67ace6..c025d5c5049a 100644 --- a/pkg/minikube/machine/machine.go +++ b/pkg/minikube/machine/machine.go @@ -133,7 +133,7 @@ func fastDetectProvisioner(h *host.Host) (libprovision.Provisioner, error) { } // saveHost is a wrapper around libmachine's Save function to proactively update the node's IP whenever a host is saved -func saveHost(api libmachine.API, h *host.Host, cfg *config.ClusterConfig, n *config.Node) error { +func saveHost(api libmachine.API, h *host.Host, cfg *config.ClusterConfig, n *config.Node, options *run.CommandOptions) error { if err := api.Save(h); err != nil { return errors.Wrap(err, "save") } @@ -147,7 +147,7 @@ func saveHost(api libmachine.API, h *host.Host, cfg *config.ClusterConfig, n *co ip = "10.0.2.15" } n.IP = ip - return config.SaveNode(cfg, n) + return config.SaveNode(cfg, n, options) } // backup copies critical ephemeral vm config files from tmpfs to persistent storage under /var/lib/minikube/backup, diff --git a/pkg/minikube/machine/start.go b/pkg/minikube/machine/start.go index 12ca77f21c9c..118fe97fd365 100644 --- a/pkg/minikube/machine/start.go +++ b/pkg/minikube/machine/start.go @@ -35,7 +35,6 @@ import ( "github.com/docker/machine/libmachine/host" "github.com/juju/mutex/v2" "github.com/pkg/errors" - "github.com/spf13/viper" "k8s.io/klog/v2" "k8s.io/minikube/pkg/drivers/kic/oci" "k8s.io/minikube/pkg/minikube/command" @@ -49,6 +48,7 @@ import ( "k8s.io/minikube/pkg/minikube/proxy" "k8s.io/minikube/pkg/minikube/reason" "k8s.io/minikube/pkg/minikube/registry" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/minikube/style" "k8s.io/minikube/pkg/minikube/vmpath" "k8s.io/minikube/pkg/util" @@ -70,7 +70,7 @@ var requiredDirectories = []string{ } // StartHost starts a host VM. -func StartHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node) (*host.Host, bool, error) { +func StartHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node, options *run.CommandOptions) (*host.Host, bool, error) { machineName := config.MachineName(*cfg, *n) // Prevent machine-driver boot races, as well as our own certificate race @@ -91,10 +91,10 @@ func StartHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node) (* var h *host.Host if !exists { klog.Infof("Provisioning new machine with config: %+v %+v", cfg, n) - h, err = createHost(api, cfg, n) + h, err = createHost(api, cfg, n, options) } else { klog.Infoln("Skipping create...Using existing machine configuration") - h, err = fixHost(api, cfg, n) + h, err = fixHost(api, cfg, n, options) } if err != nil { return h, exists, err @@ -121,7 +121,7 @@ func engineOptions(cfg config.ClusterConfig) *engine.Options { return &o } -func createHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node) (*host.Host, error) { +func createHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node, options *run.CommandOptions) (*host.Host, error) { klog.Infof("createHost starting for %q (driver=%q)", n.Name, cfg.Driver) start := time.Now() defer func() { @@ -149,7 +149,7 @@ func createHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node) ( if err != nil { return nil, errors.Wrap(err, "new host") } - defer postStartValidations(h, cfg.Driver) + defer postStartValidations(h, cfg.Driver, options) h.HostOptions.AuthOptions.CertDir = localpath.MiniPath() h.HostOptions.AuthOptions.StorePath = localpath.MiniPath() @@ -173,7 +173,7 @@ func createHost(api libmachine.API, cfg *config.ClusterConfig, n *config.Node) ( return h, errors.Wrap(err, "post-start") } - if err := saveHost(api, h, cfg, n); err != nil { + if err := saveHost(api, h, cfg, n, options); err != nil { return h, err } return h, nil @@ -201,7 +201,7 @@ func timedCreateHost(h *host.Host, api libmachine.API, t time.Duration) error { // postStartValidations are validations against the host after it is created // TODO: Add validations for VM drivers as well, see issue #9035 -func postStartValidations(h *host.Host, drvName string) { +func postStartValidations(h *host.Host, drvName string, options *run.CommandOptions) { if !driver.IsKIC(drvName) { return } @@ -225,7 +225,7 @@ func postStartValidations(h *host.Host, drvName string) { return } - if viper.GetBool("force") { + if options.Force { return } diff --git a/pkg/minikube/node/config.go b/pkg/minikube/node/config.go index 91821dfda02b..7ed2a2b1fea6 100644 --- a/pkg/minikube/node/config.go +++ b/pkg/minikube/node/config.go @@ -24,7 +24,6 @@ import ( "strconv" "sync" - "github.com/spf13/viper" "k8s.io/klog/v2" "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/constants" @@ -36,6 +35,7 @@ import ( "k8s.io/minikube/pkg/minikube/out/register" "k8s.io/minikube/pkg/minikube/proxy" "k8s.io/minikube/pkg/minikube/reason" + "k8s.io/minikube/pkg/minikube/run" "k8s.io/minikube/pkg/minikube/style" "k8s.io/minikube/pkg/util/lock" ) @@ -69,7 +69,7 @@ func showNoK8sVersionInfo(cr cruntime.Manager) { } // configureMounts configures any requested filesystem mounts -func configureMounts(wg *sync.WaitGroup, cc config.ClusterConfig) { +func configureMounts(wg *sync.WaitGroup, cc config.ClusterConfig, options *run.CommandOptions) { wg.Add(1) defer wg.Done() @@ -79,7 +79,7 @@ func configureMounts(wg *sync.WaitGroup, cc config.ClusterConfig) { out.Step(style.Mounting, "Creating mount {{.name}} ...", out.V{"name": cc.MountString}) path := os.Args[0] - profile := viper.GetString("profile") + profile := options.ProfileName args := generateMountArgs(profile, cc) mountCmd := exec.Command(path, args...) diff --git a/pkg/minikube/node/node.go b/pkg/minikube/node/node.go index 663372597ed4..fe95c251a857 100644 --- a/pkg/minikube/node/node.go +++ b/pkg/minikube/node/node.go @@ -26,7 +26,6 @@ import ( "github.com/blang/semver/v4" "github.com/pkg/errors" - "github.com/spf13/viper" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/klog/v2" @@ -44,7 +43,7 @@ import ( // Add adds a new node config to an existing cluster. func Add(cc *config.ClusterConfig, n config.Node, delOnFail bool, options *run.CommandOptions) error { - profiles, err := config.ListValidProfiles() + profiles, err := config.ListValidProfiles(options) if err != nil { return err } @@ -66,7 +65,7 @@ func Add(cc *config.ClusterConfig, n config.Node, delOnFail bool, options *run.C n.Port = cc.APIServerPort } - if err := config.SaveNode(cc, &n); err != nil { + if err := config.SaveNode(cc, &n, options); err != nil { return errors.Wrap(err, "save node") } @@ -207,7 +206,7 @@ func Delete(cc config.ClusterConfig, name string, options *run.CommandOptions) ( } cc.Nodes = append(cc.Nodes[:index], cc.Nodes[index+1:]...) - return n, config.SaveProfile(viper.GetString(config.ProfileName), &cc) + return n, config.SaveProfile(options.ProfileName, &cc) } // Retrieve finds the node by name in the given cluster @@ -228,7 +227,7 @@ func Retrieve(cc config.ClusterConfig, name string) (*config.Node, int, error) { } // Save saves a node to a cluster -func Save(cfg *config.ClusterConfig, node *config.Node) error { +func Save(cfg *config.ClusterConfig, node *config.Node, options *run.CommandOptions) error { update := false for i, n := range cfg.Nodes { if n.Name == node.Name { @@ -241,7 +240,7 @@ func Save(cfg *config.ClusterConfig, node *config.Node) error { if !update { cfg.Nodes = append(cfg.Nodes, *node) } - return config.SaveProfile(viper.GetString(config.ProfileName), cfg) + return config.SaveProfile(options.ProfileName, cfg) } // Name returns the appropriate name for the node given the node index. diff --git a/pkg/minikube/node/start.go b/pkg/minikube/node/start.go index f62799853e7d..a0abb593862e 100755 --- a/pkg/minikube/node/start.go +++ b/pkg/minikube/node/start.go @@ -95,7 +95,7 @@ type Starter struct { // Start spins up a guest and starts the Kubernetes node. func Start(starter Starter, options *run.CommandOptions) (*kubeconfig.Settings, error) { // nolint:gocyclo var wg sync.WaitGroup - stopk8s, err := handleNoKubernetes(starter) + stopk8s, err := handleNoKubernetes(starter, options) if err != nil { return nil, err } @@ -105,8 +105,8 @@ func Start(starter Starter, options *run.CommandOptions) (*kubeconfig.Settings, showNoK8sVersionInfo(cr) - configureMounts(&wg, *starter.Cfg) - return nil, config.Write(viper.GetString(config.ProfileName), starter.Cfg) + configureMounts(&wg, *starter.Cfg, options) + return nil, config.Write(options.ProfileName, starter.Cfg) } // wait for preloaded tarball to finish downloading before configuring runtimes @@ -193,7 +193,7 @@ func Start(starter Starter, options *run.CommandOptions) (*kubeconfig.Settings, } } - go configureMounts(&wg, *starter.Cfg) + go configureMounts(&wg, *starter.Cfg, options) wg.Add(1) go func() { @@ -211,7 +211,7 @@ func Start(starter Starter, options *run.CommandOptions) (*kubeconfig.Settings, addonList := viper.GetStringSlice(config.AddonListFlag) enabledAddons := make(chan []string, 1) if starter.ExistingAddons != nil { - if viper.GetBool("force") { + if options.Force { addons.Force = true } list := addons.ToEnable(starter.Cfg, starter.ExistingAddons, addonList) @@ -254,11 +254,11 @@ func Start(starter Starter, options *run.CommandOptions) (*kubeconfig.Settings, // Write enabled addons to the config before completion klog.Infof("writing updated cluster config ...") - return kcs, config.Write(viper.GetString(config.ProfileName), starter.Cfg) + return kcs, config.Write(options.ProfileName, starter.Cfg) } // handleNoKubernetes handles starting minikube without Kubernetes. -func handleNoKubernetes(starter Starter) (bool, error) { +func handleNoKubernetes(starter Starter, options *run.CommandOptions) (bool, error) { // Do not bootstrap cluster if --no-kubernetes. if starter.Node.KubernetesVersion == constants.NoKubernetesVersion { // Stop existing Kubernetes node if applicable. @@ -269,7 +269,7 @@ func handleNoKubernetes(starter Starter) (bool, error) { } kubeadm.StopKubernetes(starter.Runner, cr) } - return true, config.Write(viper.GetString(config.ProfileName), starter.Cfg) + return true, config.Write(options.ProfileName, starter.Cfg) } return false, nil } @@ -396,7 +396,7 @@ func Provision(cc *config.ClusterConfig, n *config.Node, delOnFail bool, options // Abstraction leakage alert: startHost requires the config to be saved, to satisfy pkg/provision/buildroot. // Hence, SaveProfile must be called before startHost, and again afterwards when we know the IP. - if err := config.SaveProfile(viper.GetString(config.ProfileName), cc); err != nil { + if err := config.SaveProfile(options.ProfileName, cc); err != nil { return nil, false, nil, nil, errors.Wrap(err, "Failed to save config") } @@ -660,7 +660,7 @@ func startMachine(cfg *config.ClusterConfig, node *config.Node, delOnFail bool, if err != nil { return runner, preExists, m, hostInfo, errors.Wrap(err, "Failed to get machine client") } - hostInfo, preExists, err = startHostInternal(m, cfg, node, delOnFail) + hostInfo, preExists, err = startHostInternal(m, cfg, node, delOnFail, options) if err != nil { return runner, preExists, m, hostInfo, errors.Wrap(err, "Failed to start host") } @@ -669,7 +669,7 @@ func startMachine(cfg *config.ClusterConfig, node *config.Node, delOnFail bool, return runner, preExists, m, hostInfo, errors.Wrap(err, "Failed to get command runner") } - ip, err := validateNetwork(hostInfo, runner, cfg.KubernetesConfig.ImageRepository) + ip, err := validateNetwork(hostInfo, runner, cfg.KubernetesConfig.ImageRepository, options) if err != nil { return runner, preExists, m, hostInfo, errors.Wrap(err, "Failed to validate network") } @@ -707,8 +707,8 @@ func getPort() (int, error) { } // startHostInternal starts a new minikube host using a VM or None -func startHostInternal(api libmachine.API, cc *config.ClusterConfig, n *config.Node, delOnFail bool) (*host.Host, bool, error) { - hostInfo, exists, err := machine.StartHost(api, cc, n) +func startHostInternal(api libmachine.API, cc *config.ClusterConfig, n *config.Node, delOnFail bool, options *run.CommandOptions) (*host.Host, bool, error) { + hostInfo, exists, err := machine.StartHost(api, cc, n, options) if err == nil { return hostInfo, exists, nil } @@ -740,7 +740,7 @@ func startHostInternal(api libmachine.API, cc *config.ClusterConfig, n *config.N } } - hostInfo, exists, err = machine.StartHost(api, cc, n) + hostInfo, exists, err = machine.StartHost(api, cc, n, options) if err == nil { return hostInfo, exists, nil } @@ -752,7 +752,7 @@ func startHostInternal(api libmachine.API, cc *config.ClusterConfig, n *config.N } // validateNetwork tries to catch network problems as soon as possible -func validateNetwork(h *host.Host, r command.Runner, imageRepository string) (string, error) { +func validateNetwork(h *host.Host, r command.Runner, imageRepository string, options *run.CommandOptions) (string, error) { ip, err := h.Driver.GetIP() if err != nil { return ip, err @@ -783,7 +783,7 @@ func validateNetwork(h *host.Host, r command.Runner, imageRepository string) (st } if shouldTrySSH(h.Driver.DriverName(), ip) { - if err := trySSH(h, ip); err != nil { + if err := trySSH(h, ip, options); err != nil { return ip, err } } @@ -804,8 +804,8 @@ func shouldTrySSH(driverName, ip string) bool { return true } -func trySSH(h *host.Host, ip string) error { - if viper.GetBool("force") { +func trySSH(h *host.Host, ip string, options *run.CommandOptions) error { + if options.Force { return nil } diff --git a/pkg/minikube/registry/drvs/docker/docker.go b/pkg/minikube/registry/drvs/docker/docker.go index 766791306b1c..173983060ca8 100644 --- a/pkg/minikube/registry/drvs/docker/docker.go +++ b/pkg/minikube/registry/drvs/docker/docker.go @@ -28,7 +28,6 @@ import ( "github.com/blang/semver/v4" "github.com/docker/machine/libmachine/drivers" "github.com/pkg/errors" - "github.com/spf13/viper" "k8s.io/klog/v2" "k8s.io/minikube/pkg/drivers/kic" "k8s.io/minikube/pkg/drivers/kic/oci" @@ -96,7 +95,7 @@ func configure(cc config.ClusterConfig, n config.Node) (interface{}, error) { }), nil } -func status(_ *run.CommandOptions) (retState registry.State) { +func status(options *run.CommandOptions) (retState registry.State) { version, state := dockerVersionOrState() if state.Error != nil { return state @@ -122,7 +121,7 @@ func status(_ *run.CommandOptions) (retState registry.State) { dockerEngineVersion := versions[0] dockerPlatformVersion := versions[1] klog.Infof("docker version: %s", version) - if !viper.GetBool("force") { + if !options.Force { if s := checkDockerDesktopVersion(dockerPlatformVersion); s.Error != nil { return s } diff --git a/pkg/minikube/run/options.go b/pkg/minikube/run/options.go index 0432012e7b23..a742a8700015 100644 --- a/pkg/minikube/run/options.go +++ b/pkg/minikube/run/options.go @@ -26,4 +26,12 @@ type CommandOptions struct { // flag and we should If only download and cache files for later use and // don't install or start anything. DownloadOnly bool + + // ProfileName is set if the minikube command run with the --profile flag, using + // specific minikube instance. + ProfileName string + + // Force is true if the minikube command run with the --force flag and can + // perform possibly dangerous operations. + Force bool } diff --git a/pkg/minikube/service/service_test.go b/pkg/minikube/service/service_test.go index 5d589939cab1..cb0ac3e651e2 100644 --- a/pkg/minikube/service/service_test.go +++ b/pkg/minikube/service/service_test.go @@ -30,7 +30,6 @@ import ( "github.com/docker/machine/libmachine" "github.com/docker/machine/libmachine/host" "github.com/pkg/errors" - "github.com/spf13/viper" core "k8s.io/api/core/v1" discoveryv1 "k8s.io/api/discovery/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -43,7 +42,6 @@ import ( typed_discovery "k8s.io/client-go/kubernetes/typed/discovery/v1" "k8s.io/client-go/rest" testing_fake "k8s.io/client-go/testing" - "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/tests" ) @@ -558,7 +556,6 @@ func TestGetServiceURLs(t *testing.T) { }, } defaultTemplate := template.Must(template.New("svc-template").Parse("http://{{.IP}}:{{.Port}}")) - viper.Set(config.ProfileName, constants.DefaultClusterName) var tests = []struct { description string @@ -634,7 +631,6 @@ func TestGetServiceURLsForService(t *testing.T) { }, } defaultTemplate := template.Must(template.New("svc-template").Parse("http://{{.IP}}:{{.Port}}")) - viper.Set(config.ProfileName, constants.DefaultClusterName) var tests = []struct { description string diff --git a/pkg/minikube/tests/api_mock.go b/pkg/minikube/tests/api_mock.go index 4f553b027f6d..9b83436affd9 100644 --- a/pkg/minikube/tests/api_mock.go +++ b/pkg/minikube/tests/api_mock.go @@ -19,14 +19,12 @@ package tests import ( "encoding/json" "fmt" - "math/rand" "testing" "github.com/docker/machine/libmachine/auth" "github.com/docker/machine/libmachine/host" "github.com/docker/machine/libmachine/swarm" "github.com/pkg/errors" - "github.com/spf13/viper" "k8s.io/klog/v2" ) @@ -78,17 +76,14 @@ func (api *MockAPI) NewHost(drvName string, rawDriver []byte) (*host.Host, error h := &host.Host{ DriverName: drvName, RawDriver: rawDriver, - Driver: &MockDriver{}, - Name: fmt.Sprintf("mock-machine-%.8f", rand.Float64()), + Driver: &driver, + Name: driver.GetMachineName(), HostOptions: &host.Options{ AuthOptions: &auth.Options{}, SwarmOptions: &swarm.Options{}, }, } - api.Logf("MockAPI.NewHost: Setting profile=%q", h.Name) - viper.Set("profile", h.Name) - api.Logf("MockAPI.NewHost: %+v", h) return h, nil } diff --git a/pkg/minikube/tests/driver_mock.go b/pkg/minikube/tests/driver_mock.go index 14b54b90c94a..7c07dbb98ae2 100644 --- a/pkg/minikube/tests/driver_mock.go +++ b/pkg/minikube/tests/driver_mock.go @@ -68,8 +68,8 @@ func (d *MockDriver) GetIP() (string, error) { if d.IP != "" { return d.IP, nil } - if d.BaseDriver.IPAddress != "" { - return d.BaseDriver.IPAddress, nil + if d.IPAddress != "" { + return d.IPAddress, nil } return "127.0.0.1", nil } @@ -94,7 +94,7 @@ func (d *MockDriver) GetSSHHostname() (string, error) { // GetSSHKeyPath returns the key path for SSH func (d *MockDriver) GetSSHKeyPath() string { - return d.BaseDriver.SSHKeyPath + return d.SSHKeyPath } // GetState returns the state of the driver