Document all exported functions inside minikube

Make config get/set more symmetrical, as well.
pull/3839/head
Anders F Björklund 2019-03-16 14:33:39 +01:00
parent edf46f003f
commit dba916a016
39 changed files with 253 additions and 38 deletions

View File

@ -28,6 +28,7 @@ import (
var cacheListFormat string var cacheListFormat string
// CacheListTemplate represents the cache list template
type CacheListTemplate struct { type CacheListTemplate struct {
CacheImage string CacheImage string
} }

View File

@ -88,6 +88,7 @@ var completionCmd = &cobra.Command{
}, },
} }
// GenerateBashCompletion generates the completion for the bash shell
func GenerateBashCompletion(w io.Writer, cmd *cobra.Command) error { func GenerateBashCompletion(w io.Writer, cmd *cobra.Command) error {
_, err := w.Write([]byte(boilerPlate)) _, err := w.Write([]byte(boilerPlate))
if err != nil { if err != nil {
@ -102,6 +103,7 @@ func GenerateBashCompletion(w io.Writer, cmd *cobra.Command) error {
return nil return nil
} }
// GenerateZshCompletion generates the completion for the zsh shell
func GenerateZshCompletion(out io.Writer, cmd *cobra.Command) error { func GenerateZshCompletion(out io.Writer, cmd *cobra.Command) error {
zshInitialization := `#compdef minikube zshInitialization := `#compdef minikube

View File

@ -20,6 +20,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// AddonsCmd represents the addons command
var AddonsCmd = &cobra.Command{ var AddonsCmd = &cobra.Command{
Use: "addons SUBCOMMAND [flags]", Use: "addons SUBCOMMAND [flags]",
Short: "Modify minikube's kubernetes addons", Short: "Modify minikube's kubernetes addons",

View File

@ -29,6 +29,7 @@ import (
var addonListFormat string var addonListFormat string
// AddonListTemplate represents the addon list template
type AddonListTemplate struct { type AddonListTemplate struct {
AddonName string AddonName string
AddonStatus string AddonStatus string

View File

@ -28,10 +28,12 @@ import (
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
) )
// Bootstrapper is the name for bootstrapper
const Bootstrapper = "bootstrapper" const Bootstrapper = "bootstrapper"
type setFn func(string, string) error type setFn func(string, string) error
// Setting represents a setting
type Setting struct { type Setting struct {
name string name string
set func(config.MinikubeConfig, string, string) error set func(config.MinikubeConfig, string, string) error
@ -247,6 +249,7 @@ var settings = []Setting{
}, },
} }
// ConfigCmd represents the config command
var ConfigCmd = &cobra.Command{ var ConfigCmd = &cobra.Command{
Use: "config SUBCOMMAND [flags]", Use: "config SUBCOMMAND [flags]",
Short: "Modify minikube config", Short: "Modify minikube config",

View File

@ -28,6 +28,7 @@ import (
var configViewFormat string var configViewFormat string
// ConfigViewTemplate represents the config view template
type ConfigViewTemplate struct { type ConfigViewTemplate struct {
ConfigKey string ConfigKey string
ConfigValue interface{} ConfigValue interface{}

View File

@ -21,7 +21,7 @@ import (
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"k8s.io/minikube/pkg/minikube/config" pkgConfig "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/console" "k8s.io/minikube/pkg/minikube/console"
) )
@ -36,7 +36,7 @@ var configGetCmd = &cobra.Command{
} }
cmd.SilenceUsage = true cmd.SilenceUsage = true
val, err := config.Get(args[0]) val, err := Get(args[0])
if err != nil { if err != nil {
return err return err
} }
@ -52,3 +52,8 @@ var configGetCmd = &cobra.Command{
func init() { func init() {
ConfigCmd.AddCommand(configGetCmd) ConfigCmd.AddCommand(configGetCmd)
} }
// Get gets a property
func Get(name string) (string, error) {
return pkgConfig.Get(name)
}

View File

@ -23,6 +23,7 @@ import (
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
) )
// ProfileCmd represents the profile command
var ProfileCmd = &cobra.Command{ var ProfileCmd = &cobra.Command{
Use: "profile MINIKUBE_PROFILE_NAME. You can return to the default minikube profile by running `minikube profile default`", Use: "profile MINIKUBE_PROFILE_NAME. You can return to the default minikube profile by running `minikube profile default`",
Short: "Profile sets the current minikube profile", Short: "Profile sets the current minikube profile",

View File

@ -118,6 +118,7 @@ func concealableAskForStaticValue(readWriter io.ReadWriter, promptString string,
} }
} }
// AskForPasswordValue asks for a password value, while hiding the input
func AskForPasswordValue(s string) string { func AskForPasswordValue(s string) string {
stdInFd := int(os.Stdin.Fd()) stdInFd := int(os.Stdin.Fd())

View File

@ -42,6 +42,7 @@ func init() {
ConfigCmd.AddCommand(configSetCmd) ConfigCmd.AddCommand(configSetCmd)
} }
// Set sets a property to a value
func Set(name string, value string) error { func Set(name string, value string) error {
s, err := findSetting(name) s, err := findSetting(name)
if err != nil { if err != nil {

View File

@ -56,16 +56,19 @@ func findSetting(name string) (Setting, error) {
// Set Functions // Set Functions
// SetString sets a string value
func SetString(m config.MinikubeConfig, name string, val string) error { func SetString(m config.MinikubeConfig, name string, val string) error {
m[name] = val m[name] = val
return nil return nil
} }
// SetMap sets a map value
func SetMap(m config.MinikubeConfig, name string, val map[string]interface{}) error { func SetMap(m config.MinikubeConfig, name string, val map[string]interface{}) error {
m[name] = val m[name] = val
return nil return nil
} }
// SetConfigMap sets a config map value
func SetConfigMap(m config.MinikubeConfig, name string, val string) error { func SetConfigMap(m config.MinikubeConfig, name string, val string) error {
list := strings.Split(val, ",") list := strings.Split(val, ",")
v := make(map[string]interface{}) v := make(map[string]interface{})
@ -76,6 +79,7 @@ func SetConfigMap(m config.MinikubeConfig, name string, val string) error {
return nil return nil
} }
// SetInt sets an int value
func SetInt(m config.MinikubeConfig, name string, val string) error { func SetInt(m config.MinikubeConfig, name string, val string) error {
i, err := strconv.Atoi(val) i, err := strconv.Atoi(val)
if err != nil { if err != nil {
@ -85,6 +89,7 @@ func SetInt(m config.MinikubeConfig, name string, val string) error {
return nil return nil
} }
// SetBool sets a bool value
func SetBool(m config.MinikubeConfig, name string, val string) error { func SetBool(m config.MinikubeConfig, name string, val string) error {
b, err := strconv.ParseBool(val) b, err := strconv.ParseBool(val)
if err != nil { if err != nil {
@ -134,6 +139,7 @@ func EnableOrDisableAddon(name string, val string) error {
return nil return nil
} }
// EnableOrDisableStorageClasses enables or disables storage classes
func EnableOrDisableStorageClasses(name, val string) error { func EnableOrDisableStorageClasses(name, val string) error {
enable, err := strconv.ParseBool(val) enable, err := strconv.ParseBool(val)
if err != nil { if err != nil {

View File

@ -33,6 +33,7 @@ import (
"k8s.io/minikube/pkg/minikube/cruntime" "k8s.io/minikube/pkg/minikube/cruntime"
) )
// IsValidDriver checks if a driver is supported
func IsValidDriver(string, driver string) error { func IsValidDriver(string, driver string) error {
for _, d := range constants.SupportedVMDrivers { for _, d := range constants.SupportedVMDrivers {
if driver == d { if driver == d {
@ -42,11 +43,13 @@ func IsValidDriver(string, driver string) error {
return fmt.Errorf("Driver %s is not supported", driver) return fmt.Errorf("Driver %s is not supported", driver)
} }
// RequiresRestartMsg returns the "requires restart" message
func RequiresRestartMsg(string, string) error { func RequiresRestartMsg(string, string) error {
console.OutStyle("warning", "These changes will take effect upon a minikube delete and then a minikube start") console.OutStyle("warning", "These changes will take effect upon a minikube delete and then a minikube start")
return nil return nil
} }
// IsValidDiskSize checks if a string is a valid disk size
func IsValidDiskSize(name string, disksize string) error { func IsValidDiskSize(name string, disksize string) error {
_, err := units.FromHumanSize(disksize) _, err := units.FromHumanSize(disksize)
if err != nil { if err != nil {
@ -55,6 +58,7 @@ func IsValidDiskSize(name string, disksize string) error {
return nil return nil
} }
// IsValidURL checks if a location is a valid URL
func IsValidURL(name string, location string) error { func IsValidURL(name string, location string) error {
_, err := url.Parse(location) _, err := url.Parse(location)
if err != nil { if err != nil {
@ -63,6 +67,7 @@ func IsValidURL(name string, location string) error {
return nil return nil
} }
// IsURLExists checks if a location actually exists
func IsURLExists(name string, location string) error { func IsURLExists(name string, location string) error {
parsed, err := url.Parse(location) parsed, err := url.Parse(location)
if err != nil { if err != nil {
@ -96,6 +101,7 @@ func IsURLExists(name string, location string) error {
return nil return nil
} }
// IsPositive checks if an integer is positive
func IsPositive(name string, val string) error { func IsPositive(name string, val string) error {
i, err := strconv.Atoi(val) i, err := strconv.Atoi(val)
if err != nil { if err != nil {
@ -107,6 +113,7 @@ func IsPositive(name string, val string) error {
return nil return nil
} }
// IsValidCIDR checks if a string parses as a CIDR
func IsValidCIDR(name string, cidr string) error { func IsValidCIDR(name string, cidr string) error {
_, _, err := net.ParseCIDR(cidr) _, _, err := net.ParseCIDR(cidr)
if err != nil { if err != nil {
@ -115,6 +122,7 @@ func IsValidCIDR(name string, cidr string) error {
return nil return nil
} }
// IsValidPath checks if a string is a valid path
func IsValidPath(name string, path string) error { func IsValidPath(name string, path string) error {
_, err := os.Stat(path) _, err := os.Stat(path)
if err != nil { if err != nil {
@ -123,6 +131,7 @@ func IsValidPath(name string, path string) error {
return nil return nil
} }
// IsValidAddon checks if a string is a valid addon
func IsValidAddon(name string, val string) error { func IsValidAddon(name string, val string) error {
if _, ok := assets.Addons[name]; ok { if _, ok := assets.Addons[name]; ok {
return nil return nil

View File

@ -104,6 +104,7 @@ REM @FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
`, `,
} }
// ShellConfig represents the shell config
type ShellConfig struct { type ShellConfig struct {
Prefix string Prefix string
Delimiter string Delimiter string
@ -125,16 +126,20 @@ var (
defaultNoProxyGetter NoProxyGetter defaultNoProxyGetter NoProxyGetter
) )
// ShellDetector detects shell
type ShellDetector interface { type ShellDetector interface {
GetShell(string) (string, error) GetShell(string) (string, error)
} }
// LibmachineShellDetector detects shell, using libmachine
type LibmachineShellDetector struct{} type LibmachineShellDetector struct{}
// NoProxyGetter gets the no_proxy variable
type NoProxyGetter interface { type NoProxyGetter interface {
GetNoProxyVar() (string, string) GetNoProxyVar() (string, string)
} }
// EnvNoProxyGetter gets the no_proxy variable, using environment
type EnvNoProxyGetter struct{} type EnvNoProxyGetter struct{}
func generateUsageHint(userShell string) string { func generateUsageHint(userShell string) string {
@ -274,6 +279,7 @@ func executeTemplateStdout(shellCfg *ShellConfig) error {
return tmpl.Execute(os.Stdout, shellCfg) return tmpl.Execute(os.Stdout, shellCfg)
} }
// GetShell detects the shell
func (LibmachineShellDetector) GetShell(userShell string) (string, error) { func (LibmachineShellDetector) GetShell(userShell string) (string, error) {
if userShell != "" { if userShell != "" {
return userShell, nil return userShell, nil
@ -281,6 +287,7 @@ func (LibmachineShellDetector) GetShell(userShell string) (string, error) {
return shell.Detect() return shell.Detect()
} }
// GetNoProxyVar gets the no_proxy var
func (EnvNoProxyGetter) GetNoProxyVar() (string, string) { func (EnvNoProxyGetter) GetNoProxyVar() (string, string) {
// first check for an existing lower case no_proxy var // first check for an existing lower case no_proxy var
noProxyVar := "no_proxy" noProxyVar := "no_proxy"
@ -294,6 +301,7 @@ func (EnvNoProxyGetter) GetNoProxyVar() (string, string) {
return noProxyVar, noProxyValue return noProxyVar, noProxyValue
} }
// GetDockerActive checks if Docker is active
func GetDockerActive(host *host.Host) (bool, error) { func GetDockerActive(host *host.Host) (bool, error) {
statusCmd := `sudo systemctl is-active docker` statusCmd := `sudo systemctl is-active docker`
status, err := host.RunSSHCommand(statusCmd) status, err := host.RunSSHCommand(statusCmd)

View File

@ -60,8 +60,8 @@ const (
humanReadableDiskSize = "disk-size" humanReadableDiskSize = "disk-size"
vmDriver = "vm-driver" vmDriver = "vm-driver"
xhyveDiskDriver = "xhyve-disk-driver" xhyveDiskDriver = "xhyve-disk-driver"
NFSSharesRoot = "nfs-shares-root" nfsSharesRoot = "nfs-shares-root"
NFSShare = "nfs-share" nfsShare = "nfs-share"
kubernetesVersion = "kubernetes-version" kubernetesVersion = "kubernetes-version"
hostOnlyCIDR = "host-only-cidr" hostOnlyCIDR = "host-only-cidr"
containerRuntime = "container-runtime" containerRuntime = "container-runtime"
@ -112,8 +112,8 @@ func init() {
startCmd.Flags().String(hypervVirtualSwitch, "", "The hyperv virtual switch name. Defaults to first found. (only supported with HyperV driver)") startCmd.Flags().String(hypervVirtualSwitch, "", "The hyperv virtual switch name. Defaults to first found. (only supported with HyperV driver)")
startCmd.Flags().String(kvmNetwork, "default", "The KVM network name. (only supported with KVM driver)") startCmd.Flags().String(kvmNetwork, "default", "The KVM network name. (only supported with KVM driver)")
startCmd.Flags().String(xhyveDiskDriver, "ahci-hd", "The disk driver to use [ahci-hd|virtio-blk] (only supported with xhyve driver)") startCmd.Flags().String(xhyveDiskDriver, "ahci-hd", "The disk driver to use [ahci-hd|virtio-blk] (only supported with xhyve driver)")
startCmd.Flags().StringSlice(NFSShare, []string{}, "Local folders to share with Guest via NFS mounts (Only supported on with hyperkit now)") startCmd.Flags().StringSlice(nfsShare, []string{}, "Local folders to share with Guest via NFS mounts (Only supported on with hyperkit now)")
startCmd.Flags().String(NFSSharesRoot, "/nfsshares", "Where to root the NFS Shares (defaults to /nfsshares, only supported with hyperkit now)") startCmd.Flags().String(nfsSharesRoot, "/nfsshares", "Where to root the NFS Shares (defaults to /nfsshares, only supported with hyperkit now)")
startCmd.Flags().StringArrayVar(&dockerEnv, "docker-env", nil, "Environment variables to pass to the Docker daemon. (format: key=value)") startCmd.Flags().StringArrayVar(&dockerEnv, "docker-env", nil, "Environment variables to pass to the Docker daemon. (format: key=value)")
startCmd.Flags().StringArrayVar(&dockerOpt, "docker-opt", nil, "Specify arbitrary flags to pass to the Docker daemon. (format: key=value)") startCmd.Flags().StringArrayVar(&dockerOpt, "docker-opt", nil, "Specify arbitrary flags to pass to the Docker daemon. (format: key=value)")
startCmd.Flags().Int(apiServerPort, pkgutil.APIServerPort, "The apiserver listening port") startCmd.Flags().Int(apiServerPort, pkgutil.APIServerPort, "The apiserver listening port")
@ -271,8 +271,8 @@ func generateConfig(cmd *cobra.Command, k8sVersion string) (cfg.Config, error) {
HyperkitVpnKitSock: viper.GetString(vpnkitSock), HyperkitVpnKitSock: viper.GetString(vpnkitSock),
HyperkitVSockPorts: viper.GetStringSlice(vsockPorts), HyperkitVSockPorts: viper.GetStringSlice(vsockPorts),
XhyveDiskDriver: viper.GetString(xhyveDiskDriver), XhyveDiskDriver: viper.GetString(xhyveDiskDriver),
NFSShare: viper.GetStringSlice(NFSShare), NFSShare: viper.GetStringSlice(nfsShare),
NFSSharesRoot: viper.GetString(NFSSharesRoot), NFSSharesRoot: viper.GetString(nfsSharesRoot),
DockerEnv: dockerEnv, DockerEnv: dockerEnv,
DockerOpt: dockerOpt, DockerOpt: dockerOpt,
InsecureRegistry: insecureRegistry, InsecureRegistry: insecureRegistry,

View File

@ -36,6 +36,7 @@ import (
var statusFormat string var statusFormat string
// Status represents the status
type Status struct { type Status struct {
Host string Host string
Kubelet string Kubelet string

View File

@ -25,6 +25,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
) )
// CopyableFile is something that can be copied
type CopyableFile interface { type CopyableFile interface {
io.Reader io.Reader
GetLength() int GetLength() int
@ -34,6 +35,7 @@ type CopyableFile interface {
GetPermissions() string GetPermissions() string
} }
// BaseAsset is the base asset class
type BaseAsset struct { type BaseAsset struct {
data []byte data []byte
reader io.Reader reader io.Reader
@ -44,30 +46,37 @@ type BaseAsset struct {
Permissions string Permissions string
} }
// GetAssetName returns asset name
func (b *BaseAsset) GetAssetName() string { func (b *BaseAsset) GetAssetName() string {
return b.AssetName return b.AssetName
} }
// GetTargetDir returns target dir
func (b *BaseAsset) GetTargetDir() string { func (b *BaseAsset) GetTargetDir() string {
return b.TargetDir return b.TargetDir
} }
// GetTargetName returns target name
func (b *BaseAsset) GetTargetName() string { func (b *BaseAsset) GetTargetName() string {
return b.TargetName return b.TargetName
} }
// GetPermissions returns permissions
func (b *BaseAsset) GetPermissions() string { func (b *BaseAsset) GetPermissions() string {
return b.Permissions return b.Permissions
} }
// FileAsset is an asset using a file
type FileAsset struct { type FileAsset struct {
BaseAsset BaseAsset
} }
// NewMemoryAssetTarget creates a new MemoryAsset, with target
func NewMemoryAssetTarget(d []byte, targetPath, permissions string) *MemoryAsset { func NewMemoryAssetTarget(d []byte, targetPath, permissions string) *MemoryAsset {
return NewMemoryAsset(d, path.Dir(targetPath), path.Base(targetPath), permissions) return NewMemoryAsset(d, path.Dir(targetPath), path.Base(targetPath), permissions)
} }
// NewFileAsset creates a new FileAsset
func NewFileAsset(assetName, targetDir, targetName, permissions string) (*FileAsset, error) { func NewFileAsset(assetName, targetDir, targetName, permissions string) (*FileAsset, error) {
f := &FileAsset{ f := &FileAsset{
BaseAsset{ BaseAsset{
@ -85,6 +94,7 @@ func NewFileAsset(assetName, targetDir, targetName, permissions string) (*FileAs
return f, nil return f, nil
} }
// GetLength returns the file length, or 0 (on error)
func (f *FileAsset) GetLength() int { func (f *FileAsset) GetLength() int {
file, err := os.Open(f.AssetName) file, err := os.Open(f.AssetName)
defer file.Close() defer file.Close()
@ -105,18 +115,22 @@ func (f *FileAsset) Read(p []byte) (int, error) {
return f.reader.Read(p) return f.reader.Read(p)
} }
// MemoryAsset is a memory-based asset
type MemoryAsset struct { type MemoryAsset struct {
BaseAsset BaseAsset
} }
// GetLength returns length
func (m *MemoryAsset) GetLength() int { func (m *MemoryAsset) GetLength() int {
return m.Length return m.Length
} }
// Read reads the asset
func (m *MemoryAsset) Read(p []byte) (int, error) { func (m *MemoryAsset) Read(p []byte) (int, error) {
return m.reader.Read(p) return m.reader.Read(p)
} }
// NewMemoryAsset creates a new MemoryAsset
func NewMemoryAsset(d []byte, targetDir, targetName, permissions string) *MemoryAsset { func NewMemoryAsset(d []byte, targetDir, targetName, permissions string) *MemoryAsset {
m := &MemoryAsset{ m := &MemoryAsset{
BaseAsset{ BaseAsset{
@ -132,10 +146,12 @@ func NewMemoryAsset(d []byte, targetDir, targetName, permissions string) *Memory
return m return m
} }
// BinDataAsset is a bindata (binary data) asset
type BinDataAsset struct { type BinDataAsset struct {
BaseAsset BaseAsset
} }
// NewBinDataAsset creates a new BinDataAsset
func NewBinDataAsset(assetName, targetDir, targetName, permissions string) *BinDataAsset { func NewBinDataAsset(assetName, targetDir, targetName, permissions string) *BinDataAsset {
m := &BinDataAsset{ m := &BinDataAsset{
BaseAsset{ BaseAsset{
@ -160,10 +176,12 @@ func (m *BinDataAsset) loadData() error {
return nil return nil
} }
// GetLength returns length
func (m *BinDataAsset) GetLength() int { func (m *BinDataAsset) GetLength() int {
return m.Length return m.Length
} }
// Read reads the asset
func (m *BinDataAsset) Read(p []byte) (int, error) { func (m *BinDataAsset) Read(p []byte) (int, error) {
return m.reader.Read(p) return m.reader.Read(p)
} }

View File

@ -47,9 +47,11 @@ type Bootstrapper interface {
} }
const ( const (
// BootstrapperTypeKubeadm is the kubeadm bootstrapper type
BootstrapperTypeKubeadm = "kubeadm" BootstrapperTypeKubeadm = "kubeadm"
) )
// GetCachedImageList returns the list of images for a version
func GetCachedImageList(version string, bootstrapper string) []string { func GetCachedImageList(version string, bootstrapper string) []string {
switch bootstrapper { switch bootstrapper {
case BootstrapperTypeKubeadm: case BootstrapperTypeKubeadm:

View File

@ -86,10 +86,12 @@ var PodsByLayer = []pod{
// SkipAdditionalPreflights are additional preflights we skip depending on the runtime in use. // SkipAdditionalPreflights are additional preflights we skip depending on the runtime in use.
var SkipAdditionalPreflights = map[string][]string{} var SkipAdditionalPreflights = map[string][]string{}
// KubeadmBootstrapper is a bootstrapper using kubeadm
type KubeadmBootstrapper struct { type KubeadmBootstrapper struct {
c bootstrapper.CommandRunner c bootstrapper.CommandRunner
} }
// NewKubeadmBootstrapper creates a new KubeadmBootstrapper
func NewKubeadmBootstrapper(api libmachine.API) (*KubeadmBootstrapper, error) { func NewKubeadmBootstrapper(api libmachine.API) (*KubeadmBootstrapper, error) {
h, err := api.Load(config.GetMachineName()) h, err := api.Load(config.GetMachineName())
if err != nil { if err != nil {
@ -102,6 +104,7 @@ func NewKubeadmBootstrapper(api libmachine.API) (*KubeadmBootstrapper, error) {
return &KubeadmBootstrapper{c: runner}, nil return &KubeadmBootstrapper{c: runner}, nil
} }
// GetKubeletStatus returns the kubelet status
func (k *KubeadmBootstrapper) GetKubeletStatus() (string, error) { func (k *KubeadmBootstrapper) GetKubeletStatus() (string, error) {
statusCmd := `sudo systemctl is-active kubelet` statusCmd := `sudo systemctl is-active kubelet`
status, err := k.c.CombinedOutput(statusCmd) status, err := k.c.CombinedOutput(statusCmd)
@ -120,6 +123,7 @@ func (k *KubeadmBootstrapper) GetKubeletStatus() (string, error) {
return state.Error.String(), nil return state.Error.String(), nil
} }
// GetAPIServerStatus returns the api-server status
func (k *KubeadmBootstrapper) GetAPIServerStatus(ip net.IP) (string, error) { func (k *KubeadmBootstrapper) GetAPIServerStatus(ip net.IP) (string, error) {
url := fmt.Sprintf("https://%s:%d/healthz", ip, util.APIServerPort) url := fmt.Sprintf("https://%s:%d/healthz", ip, util.APIServerPort)
// To avoid: x509: certificate signed by unknown authority // To avoid: x509: certificate signed by unknown authority
@ -152,6 +156,7 @@ func (k *KubeadmBootstrapper) LogCommands(o bootstrapper.LogOptions) map[string]
return map[string]string{"kubelet": kcmd.String()} return map[string]string{"kubelet": kcmd.String()}
} }
// StartCluster starts the cluster
func (k *KubeadmBootstrapper) StartCluster(k8s config.KubernetesConfig) error { func (k *KubeadmBootstrapper) StartCluster(k8s config.KubernetesConfig) error {
version, err := ParseKubernetesVersion(k8s.KubernetesVersion) version, err := ParseKubernetesVersion(k8s.KubernetesVersion)
if err != nil { if err != nil {
@ -371,6 +376,7 @@ func NewKubeletConfig(k8s config.KubernetesConfig, r cruntime.Manager) (string,
return b.String(), nil return b.String(), nil
} }
// UpdateCluster updates the cluster
func (k *KubeadmBootstrapper) UpdateCluster(cfg config.KubernetesConfig) error { func (k *KubeadmBootstrapper) UpdateCluster(cfg config.KubernetesConfig) error {
if cfg.ShouldLoadCachedImages { if cfg.ShouldLoadCachedImages {
err := machine.LoadImages(k.c, constants.GetKubeadmCachedImages(cfg.KubernetesVersion), constants.ImageCacheDir) err := machine.LoadImages(k.c, constants.GetKubeadmCachedImages(cfg.KubernetesVersion), constants.ImageCacheDir)

View File

@ -60,6 +60,7 @@ func ExtraConfigForComponent(component string, opts util.ExtraOptionSlice, versi
return versionedOpts, nil return versionedOpts, nil
} }
// ComponentExtraArgs holds extra args for a component
type ComponentExtraArgs struct { type ComponentExtraArgs struct {
Component string Component string
Options map[string]string Options map[string]string
@ -73,6 +74,7 @@ var componentToKubeadmConfigKey = map[string]string{
Kubelet: "", Kubelet: "",
} }
// NewComponentExtraArgs creates a new ComponentExtraArgs
func NewComponentExtraArgs(opts util.ExtraOptionSlice, version semver.Version, featureGates string) ([]ComponentExtraArgs, error) { func NewComponentExtraArgs(opts util.ExtraOptionSlice, version semver.Version, featureGates string) ([]ComponentExtraArgs, error) {
var kubeadmExtraArgs []ComponentExtraArgs var kubeadmExtraArgs []ComponentExtraArgs
for _, extraOpt := range opts { for _, extraOpt := range opts {
@ -110,6 +112,7 @@ func NewComponentExtraArgs(opts util.ExtraOptionSlice, version semver.Version, f
return kubeadmExtraArgs, nil return kubeadmExtraArgs, nil
} }
// ParseFeatureArgs parses feature args into extra args
func ParseFeatureArgs(featureGates string) (map[string]bool, string, error) { func ParseFeatureArgs(featureGates string) (map[string]bool, string, error) {
kubeadmFeatureArgs := map[string]bool{} kubeadmFeatureArgs := map[string]bool{}
componentFeatureArgs := "" componentFeatureArgs := ""
@ -152,6 +155,7 @@ func Supports(featureName string) bool {
return false return false
} }
// ParseKubernetesVersion parses the kubernetes version
func ParseKubernetesVersion(version string) (semver.Version, error) { func ParseKubernetesVersion(version string) (semver.Version, error) {
// Strip leading 'v' prefix from version for semver parsing // Strip leading 'v' prefix from version for semver parsing
v, err := semver.Make(version[1:]) v, err := semver.Make(version[1:])
@ -269,6 +273,7 @@ var versionSpecificOpts = []VersionedExtraOption{
}, },
} }
// VersionIsBetween checks if a version is between (or including) two given versions
func VersionIsBetween(version, gte, lte semver.Version) bool { func VersionIsBetween(version, gte, lte semver.Version) bool {
if gte.NE(semver.Version{}) && !version.GTE(gte) { if gte.NE(semver.Version{}) && !version.GTE(gte) {
return false return false
@ -280,6 +285,7 @@ func VersionIsBetween(version, gte, lte semver.Version) bool {
return true return true
} }
// DefaultOptionsForComponentAndVersion returns the default option for a component and version
func DefaultOptionsForComponentAndVersion(component string, version semver.Version) (map[string]string, error) { func DefaultOptionsForComponentAndVersion(component string, version semver.Version) (map[string]string, error) {
versionedOpts := map[string]string{} versionedOpts := map[string]string{}
for _, opts := range versionSpecificOpts { for _, opts := range versionSpecificOpts {

View File

@ -411,6 +411,7 @@ func getIPForInterface(name string) (net.IP, error) {
return nil, errors.Errorf("Error finding IPV4 address for %s", name) return nil, errors.Errorf("Error finding IPV4 address for %s", name)
} }
// CheckIfHostExistsAndLoad checks if a host exists, and loads it if it does
func CheckIfHostExistsAndLoad(api libmachine.API, machineName string) (*host.Host, error) { func CheckIfHostExistsAndLoad(api libmachine.API, machineName string) (*host.Host, error) {
exists, err := api.Exists(machineName) exists, err := api.Exists(machineName)
if err != nil { if err != nil {
@ -427,6 +428,7 @@ func CheckIfHostExistsAndLoad(api libmachine.API, machineName string) (*host.Hos
return host, nil return host, nil
} }
// CreateSSHShell creates a new SSH shell / client
func CreateSSHShell(api libmachine.API, args []string) error { func CreateSSHShell(api libmachine.API, args []string) error {
machineName := cfg.GetMachineName() machineName := cfg.GetMachineName()
host, err := CheckIfHostExistsAndLoad(api, machineName) host, err := CheckIfHostExistsAndLoad(api, machineName)
@ -462,6 +464,7 @@ func EnsureMinikubeRunningOrExit(api libmachine.API, exitStatus int) {
} }
} }
// GetMountCleanupCommand returns the unmount command
func GetMountCleanupCommand(path string) string { func GetMountCleanupCommand(path string) string {
return fmt.Sprintf("sudo umount %s;", path) return fmt.Sprintf("sudo umount %s;", path)
} }
@ -471,6 +474,7 @@ sudo mkdir -p {{.Path}} || true;
sudo mount -t 9p -o trans=tcp,port={{.Port}},dfltuid={{.UID}},dfltgid={{.GID}},version={{.Version}},msize={{.Msize}} {{.IP}} {{.Path}}; sudo mount -t 9p -o trans=tcp,port={{.Port}},dfltuid={{.UID}},dfltgid={{.GID}},version={{.Version}},msize={{.Msize}} {{.IP}} {{.Path}};
sudo chmod 775 {{.Path}} || true;` sudo chmod 775 {{.Path}} || true;`
// GetMountCommand returns the mount command
func GetMountCommand(ip net.IP, path, port, mountVersion string, uid, gid, msize int) (string, error) { func GetMountCommand(ip net.IP, path, port, mountVersion string, uid, gid, msize int) (string, error) {
t := template.Must(template.New("mountCommand").Parse(mountTemplate)) t := template.Must(template.New("mountCommand").Parse(mountTemplate))
buf := bytes.Buffer{} buf := bytes.Buffer{}

View File

@ -30,19 +30,30 @@ import (
) )
const ( const (
WantUpdateNotification = "WantUpdateNotification" // WantUpdateNotification is the key for WantUpdateNotification
ReminderWaitPeriodInHours = "ReminderWaitPeriodInHours" WantUpdateNotification = "WantUpdateNotification"
WantReportError = "WantReportError" // ReminderWaitPeriodInHours is the key for WantUpdateNotification
WantReportErrorPrompt = "WantReportErrorPrompt" ReminderWaitPeriodInHours = "ReminderWaitPeriodInHours"
WantKubectlDownloadMsg = "WantKubectlDownloadMsg" // WantReportError is the key for WantReportError
WantNoneDriverWarning = "WantNoneDriverWarning" WantReportError = "WantReportError"
MachineProfile = "profile" // WantReportErrorPrompt is the key for WantReportErrorPrompt
ShowDriverDeprecationNotification = "ShowDriverDeprecationNotification" WantReportErrorPrompt = "WantReportErrorPrompt"
// WantKubectlDownloadMsg is the key for WantKubectlDownloadMsg
WantKubectlDownloadMsg = "WantKubectlDownloadMsg"
// WantNoneDriverWarning is the key for WantNoneDriverWarning
WantNoneDriverWarning = "WantNoneDriverWarning"
// MachineProfile is the key for MachineProfile
MachineProfile = "profile"
// ShowDriverDeprecationNotification is the key for ShowDriverDeprecationNotification
ShowDriverDeprecationNotification = "ShowDriverDeprecationNotification"
// ShowBootstrapperDeprecationNotification is the key for ShowBootstrapperDeprecationNotification
ShowBootstrapperDeprecationNotification = "ShowBootstrapperDeprecationNotification" ShowBootstrapperDeprecationNotification = "ShowBootstrapperDeprecationNotification"
) )
// MinikubeConfig represents minikube config
type MinikubeConfig map[string]interface{} type MinikubeConfig map[string]interface{}
// Get gets a named value from config
func Get(name string) (string, error) { func Get(name string) (string, error) {
m, err := ReadConfig() m, err := ReadConfig()
if err != nil { if err != nil {
@ -103,6 +114,7 @@ type Loader interface {
type simpleConfigLoader struct{} type simpleConfigLoader struct{}
// DefaultLoader is the default config loader
var DefaultLoader Loader = &simpleConfigLoader{} var DefaultLoader Loader = &simpleConfigLoader{}
func (c *simpleConfigLoader) LoadConfigFromFile(profile string) (*Config, error) { func (c *simpleConfigLoader) LoadConfigFromFile(profile string) (*Config, error) {

View File

@ -37,6 +37,7 @@ const (
ClusterDNSDomain = "cluster.local" ClusterDNSDomain = "cluster.local"
) )
// MinikubeHome is the name of the minikube home directory variable.
const MinikubeHome = "MINIKUBE_HOME" const MinikubeHome = "MINIKUBE_HOME"
// GetMinipath returns the path to the user's minikube dir // GetMinipath returns the path to the user's minikube dir
@ -65,6 +66,7 @@ var SupportedVMDrivers = [...]string{
"none", "none",
} }
// DefaultMinipath is the default Minikube path (under the home directory)
var DefaultMinipath = filepath.Join(homedir.HomeDir(), ".minikube") var DefaultMinipath = filepath.Join(homedir.HomeDir(), ".minikube")
// KubeconfigPath is the path to the Kubernetes client config // KubeconfigPath is the path to the Kubernetes client config
@ -91,6 +93,7 @@ const DefaultStorageClassProvisioner = "standard"
// Cache is used to modify the cache field in the config file // Cache is used to modify the cache field in the config file
const Cache = "cache" const Cache = "cache"
// TunnelRegistryPath returns the path to the runnel registry file
func TunnelRegistryPath() string { func TunnelRegistryPath() string {
return filepath.Join(GetMinipath(), "tunnels.json") return filepath.Join(GetMinipath(), "tunnels.json")
} }
@ -102,37 +105,61 @@ func MakeMiniPath(fileName ...string) string {
return filepath.Join(args...) return filepath.Join(args...)
} }
// MountProcessFileName is the filename of the mount process
var MountProcessFileName = ".mount-process" var MountProcessFileName = ".mount-process"
const ( const (
DefaultKeepContext = false // DefaultKeepContext is if we should keep context by default
SHASuffix = ".sha256" DefaultKeepContext = false
DefaultMemory = 2048 // SHASuffix is the suffix of a SHA-256 checksum file
DefaultCPUS = 2 SHASuffix = ".sha256"
DefaultDiskSize = "20g" // DefaultMemory is the default memory of a host, in megabytes
MinimumDiskSizeMB = 2000 DefaultMemory = 2048
DefaultVMDriver = "virtualbox" // DefaultCPUS is the default number of cpus of a host
DefaultCPUS = 2
// DefaultDiskSize is the default disk image size, parseable
DefaultDiskSize = "20g"
// MinimumDiskSizeMB is the minimum disk image size, in megabytes
MinimumDiskSizeMB = 2000
// DefaultVMDriver is the default virtual machine driver name
DefaultVMDriver = "virtualbox"
// DefaultStatusFormat is the default format of a host
DefaultStatusFormat = `host: {{.Host}} DefaultStatusFormat = `host: {{.Host}}
kubelet: {{.Kubelet}} kubelet: {{.Kubelet}}
apiserver: {{.ApiServer}} apiserver: {{.ApiServer}}
kubectl: {{.Kubeconfig}} kubectl: {{.Kubeconfig}}
` `
DefaultAddonListFormat = "- {{.AddonName}}: {{.AddonStatus}}\n" // DefaultAddonListFormat is the default format of addon list
DefaultConfigViewFormat = "- {{.ConfigKey}}: {{.ConfigValue}}\n" DefaultAddonListFormat = "- {{.AddonName}}: {{.AddonStatus}}\n"
DefaultCacheListFormat = "{{.CacheImage}}\n" // DefaultConfigViewFormat is the default format of config view
GithubMinikubeReleasesURL = "https://storage.googleapis.com/minikube/releases.json" DefaultConfigViewFormat = "- {{.ConfigKey}}: {{.ConfigValue}}\n"
DefaultWait = 20 // DefaultCacheListFormat is the default format of cache list
DefaultInterval = 6 DefaultCacheListFormat = "{{.CacheImage}}\n"
DefaultK8sClientTimeout = 60 * time.Second // GithubMinikubeReleasesURL is the URL of the minikube github releases JSON file
GithubMinikubeReleasesURL = "https://storage.googleapis.com/minikube/releases.json"
// DefaultWait is the default wait time, in seconds
DefaultWait = 20
// DefaultInterval is the default interval, in seconds
DefaultInterval = 6
// DefaultK8sClientTimeout is the default kubernetes client timeout
DefaultK8sClientTimeout = 60 * time.Second
// DefaultClusterBootstrapper is the default cluster bootstrapper
DefaultClusterBootstrapper = "kubeadm" DefaultClusterBootstrapper = "kubeadm"
) )
// DefaultISOURL is the default location of the minikube.iso file
var DefaultISOURL = fmt.Sprintf("https://storage.googleapis.com/%s/minikube-%s.iso", minikubeVersion.GetISOPath(), minikubeVersion.GetISOVersion()) var DefaultISOURL = fmt.Sprintf("https://storage.googleapis.com/%s/minikube-%s.iso", minikubeVersion.GetISOPath(), minikubeVersion.GetISOVersion())
// DefaultISOSHAURL is the default location of the minikube.iso.sha256 file
var DefaultISOSHAURL = DefaultISOURL + SHASuffix var DefaultISOSHAURL = DefaultISOURL + SHASuffix
// DefaultKubernetesVersion is the default kubernetes version
var DefaultKubernetesVersion = "v1.13.3" var DefaultKubernetesVersion = "v1.13.3"
// ConfigFilePath is the path of the config directory
var ConfigFilePath = MakeMiniPath("config") var ConfigFilePath = MakeMiniPath("config")
// ConfigFile is the path of the config file
var ConfigFile = MakeMiniPath("config", "config.json") var ConfigFile = MakeMiniPath("config", "config.json")
// GetProfileFile returns the Minikube profile config file // GetProfileFile returns the Minikube profile config file
@ -143,39 +170,61 @@ func GetProfileFile(profile string) string {
// DockerAPIVersion is the API version implemented by Docker running in the minikube VM. // DockerAPIVersion is the API version implemented by Docker running in the minikube VM.
const DockerAPIVersion = "1.35" const DockerAPIVersion = "1.35"
// ReportingURL is the URL for reporting a minikube error
const ReportingURL = "https://clouderrorreporting.googleapis.com/v1beta1/projects/k8s-minikube/events:report?key=AIzaSyACUwzG0dEPcl-eOgpDKnyKoUFgHdfoFuA" const ReportingURL = "https://clouderrorreporting.googleapis.com/v1beta1/projects/k8s-minikube/events:report?key=AIzaSyACUwzG0dEPcl-eOgpDKnyKoUFgHdfoFuA"
// AddonsPath is the default path of the addons configuration
const AddonsPath = "/etc/kubernetes/addons" const AddonsPath = "/etc/kubernetes/addons"
// FilesPath is the default path of files
const FilesPath = "/files" const FilesPath = "/files"
const ( const (
KubeletServiceFile = "/lib/systemd/system/kubelet.service" // KubeletServiceFile is the path to the kubelet systemd service
KubeletSystemdConfFile = "/etc/systemd/system/kubelet.service.d/10-kubeadm.conf" KubeletServiceFile = "/lib/systemd/system/kubelet.service"
KubeadmConfigFile = "/var/lib/kubeadm.yaml" // KubeletSystemdConfFile is the path to the kubelet systemd configuration
DefaultCNIConfigPath = "/etc/cni/net.d/k8s.conf" KubeletSystemdConfFile = "/etc/systemd/system/kubelet.service.d/10-kubeadm.conf"
// KubeadmConfigFile is the path to the kubeadm configuration
KubeadmConfigFile = "/var/lib/kubeadm.yaml"
// DefaultCNIConfigPath is the path to the CNI configuration
DefaultCNIConfigPath = "/etc/cni/net.d/k8s.conf"
// DefaultRktNetConfigPath is the path to the rkt net configuration
DefaultRktNetConfigPath = "/etc/rkt/net.d/k8s.conf" DefaultRktNetConfigPath = "/etc/rkt/net.d/k8s.conf"
) )
const ( const (
DefaultUfsPort = "5640" // DefaultUfsPort is the default port of UFS
DefaultUfsDebugLvl = 0 DefaultUfsPort = "5640"
// DefaultUfsDebugLvl is the default debug level of UFS
DefaultUfsDebugLvl = 0
// DefaultMountEndpoint is the default mount endpoint
DefaultMountEndpoint = "/minikube-host" DefaultMountEndpoint = "/minikube-host"
DefaultMsize = 262144 // DefaultMsize is the default number of bytes to use for 9p packet payload
DefaultMountVersion = "9p2000.u" DefaultMsize = 262144
// DefaultMountVersion is the default 9p version to use for mount
DefaultMountVersion = "9p2000.u"
) )
// GetKubernetesReleaseURL gets the location of a kubernetes client
func GetKubernetesReleaseURL(binaryName, version string) string { func GetKubernetesReleaseURL(binaryName, version string) string {
return fmt.Sprintf("https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/%s", version, runtime.GOARCH, binaryName) return fmt.Sprintf("https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/%s", version, runtime.GOARCH, binaryName)
} }
// GetKubernetesReleaseURLSHA1 gets the location of a kubernetes client checksum
func GetKubernetesReleaseURLSHA1(binaryName, version string) string { func GetKubernetesReleaseURLSHA1(binaryName, version string) string {
return fmt.Sprintf("%s.sha1", GetKubernetesReleaseURL(binaryName, version)) return fmt.Sprintf("%s.sha1", GetKubernetesReleaseURL(binaryName, version))
} }
// IsMinikubeChildProcess is the name of "is minikube child process" variable
const IsMinikubeChildProcess = "IS_MINIKUBE_CHILD_PROCESS" const IsMinikubeChildProcess = "IS_MINIKUBE_CHILD_PROCESS"
// DriverNone is the none driver
const DriverNone = "none" const DriverNone = "none"
// FileScheme is the file scheme
const FileScheme = "file" const FileScheme = "file"
// GetKubeadmCachedImages gets the images to cache for kubeadm for a version
func GetKubeadmCachedImages(kubernetesVersionStr string) []string { func GetKubeadmCachedImages(kubernetesVersionStr string) []string {
var images = []string{ var images = []string{
@ -267,6 +316,7 @@ func GetKubeadmCachedImages(kubernetesVersionStr string) []string {
return images return images
} }
// ImageCacheDir is the path to the image cache directory
var ImageCacheDir = MakeMiniPath("cache", "images") var ImageCacheDir = MakeMiniPath("cache", "images")
const ( const (

View File

@ -22,4 +22,5 @@ import (
"k8s.io/client-go/util/homedir" "k8s.io/client-go/util/homedir"
) )
// DefaultMountDir is the default mount dir
var DefaultMountDir = homedir.HomeDir() var DefaultMountDir = homedir.HomeDir()

View File

@ -24,6 +24,7 @@ import (
"github.com/golang/glog" "github.com/golang/glog"
) )
// KubernetesContainerPrefix is the prefix of each kubernetes container
const KubernetesContainerPrefix = "k8s_" const KubernetesContainerPrefix = "k8s_"
// Docker contains Docker runtime state // Docker contains Docker runtime state

View File

@ -48,6 +48,7 @@ var getWindowsVolumeName = getWindowsVolumeNameCmd
// loadImageLock is used to serialize image loads to avoid overloading the guest VM // loadImageLock is used to serialize image loads to avoid overloading the guest VM
var loadImageLock sync.Mutex var loadImageLock sync.Mutex
// CacheImagesForBootstrapper will cache images for a bootstrapper
func CacheImagesForBootstrapper(version string, clusterBootstrapper string) error { func CacheImagesForBootstrapper(version string, clusterBootstrapper string) error {
images := bootstrapper.GetCachedImageList(version, clusterBootstrapper) images := bootstrapper.GetCachedImageList(version, clusterBootstrapper)
@ -83,6 +84,7 @@ func CacheImages(images []string, cacheDir string) error {
return nil return nil
} }
// LoadImages loads previously cached images into the container runtime
func LoadImages(cmd bootstrapper.CommandRunner, images []string, cacheDir string) error { func LoadImages(cmd bootstrapper.CommandRunner, images []string, cacheDir string) error {
var g errgroup.Group var g errgroup.Group
// Load profile cluster config from file // Load profile cluster config from file
@ -108,6 +110,7 @@ func LoadImages(cmd bootstrapper.CommandRunner, images []string, cacheDir string
return nil return nil
} }
// CacheAndLoadImages caches and loads images
func CacheAndLoadImages(images []string) error { func CacheAndLoadImages(images []string) error {
if err := CacheImages(images, constants.ImageCacheDir); err != nil { if err := CacheImages(images, constants.ImageCacheDir); err != nil {
return err return err
@ -195,6 +198,7 @@ func getWindowsVolumeNameCmd(d string) (string, error) {
return vname, nil return vname, nil
} }
// LoadFromCacheBlocking loads images from cache, blocking until loaded
func LoadFromCacheBlocking(cr bootstrapper.CommandRunner, k8s config.KubernetesConfig, src string) error { func LoadFromCacheBlocking(cr bootstrapper.CommandRunner, k8s config.KubernetesConfig, src string) error {
glog.Infoln("Loading image from cache at ", src) glog.Infoln("Loading image from cache at ", src)
filename := filepath.Base(src) filename := filepath.Base(src)
@ -231,6 +235,7 @@ func LoadFromCacheBlocking(cr bootstrapper.CommandRunner, k8s config.KubernetesC
return nil return nil
} }
// DeleteFromImageCacheDir deletes images from the cache
func DeleteFromImageCacheDir(images []string) error { func DeleteFromImageCacheDir(images []string) error {
for _, image := range images { for _, image := range images {
path := filepath.Join(constants.ImageCacheDir, image) path := filepath.Join(constants.ImageCacheDir, image)
@ -282,6 +287,7 @@ func getDstPath(image, dst string) (string, error) {
return dst, nil return dst, nil
} }
// CacheImage caches an image
func CacheImage(image, dst string) error { func CacheImage(image, dst string) error {
glog.Infof("Attempting to cache image: %s at %s\n", image, dst) glog.Infof("Attempting to cache image: %s at %s\n", image, dst)
if _, err := os.Stat(dst); err == nil { if _, err := os.Stat(dst); err == nil {

View File

@ -48,6 +48,7 @@ import (
"k8s.io/minikube/pkg/provision" "k8s.io/minikube/pkg/provision"
) )
// NewRPCClient gets a new client.
func NewRPCClient(storePath, certsDir string) libmachine.API { func NewRPCClient(storePath, certsDir string) libmachine.API {
c := libmachine.NewClient(storePath, certsDir) c := libmachine.NewClient(storePath, certsDir)
c.SSHClientType = ssh.Native c.SSHClientType = ssh.Native
@ -76,6 +77,7 @@ type LocalClient struct {
legacyClient libmachine.API legacyClient libmachine.API
} }
// NewHost creates a new Host
func (api *LocalClient) NewHost(driverName string, rawDriver []byte) (*host.Host, error) { func (api *LocalClient) NewHost(driverName string, rawDriver []byte) (*host.Host, error) {
var def registry.DriverDef var def registry.DriverDef
var err error var err error
@ -116,6 +118,7 @@ func (api *LocalClient) NewHost(driverName string, rawDriver []byte) (*host.Host
}, nil }, nil
} }
// Load a new client, creating driver
func (api *LocalClient) Load(name string) (*host.Host, error) { func (api *LocalClient) Load(name string) (*host.Host, error) {
h, err := api.Filestore.Load(name) h, err := api.Filestore.Load(name)
if err != nil { if err != nil {
@ -133,6 +136,7 @@ func (api *LocalClient) Load(name string) (*host.Host, error) {
return h, json.Unmarshal(h.RawDriver, h.Driver) return h, json.Unmarshal(h.RawDriver, h.Driver)
} }
// Close closes the client
func (api *LocalClient) Close() error { func (api *LocalClient) Close() error {
if api.legacyClient != nil { if api.legacyClient != nil {
return api.legacyClient.Close() return api.legacyClient.Close()
@ -152,6 +156,7 @@ func CommandRunner(h *host.Host) (bootstrapper.CommandRunner, error) {
return bootstrapper.NewSSHRunner(client), nil return bootstrapper.NewSSHRunner(client), nil
} }
// Create creates the host
func (api *LocalClient) Create(h *host.Host) error { func (api *LocalClient) Create(h *host.Host) error {
if def, err := registry.Driver(h.DriverName); err != nil { if def, err := registry.Driver(h.DriverName); err != nil {
return err return err
@ -211,6 +216,7 @@ func (api *LocalClient) Create(h *host.Host) error {
return nil return nil
} }
// StartDriver starts the driver
func StartDriver() { func StartDriver() {
cert.SetCertGenerator(&CertGenerator{}) cert.SetCertGenerator(&CertGenerator{})
check.DefaultConnChecker = &ConnChecker{} check.DefaultConnChecker = &ConnChecker{}
@ -221,9 +227,11 @@ func StartDriver() {
localbinary.CurrentBinaryIsDockerMachine = true localbinary.CurrentBinaryIsDockerMachine = true
} }
// ConnChecker can check the connection
type ConnChecker struct { type ConnChecker struct {
} }
// Check checks the connection
func (cc *ConnChecker) Check(h *host.Host, swarm bool) (string, *auth.Options, error) { func (cc *ConnChecker) Check(h *host.Host, swarm bool) (string, *auth.Options, error) {
authOptions := h.AuthOptions() authOptions := h.AuthOptions()
dockerHost, err := h.Driver.GetURL() dockerHost, err := h.Driver.GetURL()

View File

@ -42,10 +42,12 @@ var (
lastUpdateCheckFilePath = constants.MakeMiniPath("last_update_check") lastUpdateCheckFilePath = constants.MakeMiniPath("last_update_check")
) )
// MaybePrintUpdateTextFromGithub prints update text if needed, from github
func MaybePrintUpdateTextFromGithub(output io.Writer) { func MaybePrintUpdateTextFromGithub(output io.Writer) {
MaybePrintUpdateText(output, constants.GithubMinikubeReleasesURL, lastUpdateCheckFilePath) MaybePrintUpdateText(output, constants.GithubMinikubeReleasesURL, lastUpdateCheckFilePath)
} }
// MaybePrintUpdateText prints update text if needed
func MaybePrintUpdateText(output io.Writer, url string, lastUpdatePath string) { func MaybePrintUpdateText(output io.Writer, url string, lastUpdatePath string) {
if !shouldCheckURLVersion(lastUpdatePath) { if !shouldCheckURLVersion(lastUpdatePath) {
return return
@ -80,11 +82,13 @@ func shouldCheckURLVersion(filePath string) bool {
return time.Since(lastUpdateTime).Hours() >= viper.GetFloat64(config.ReminderWaitPeriodInHours) return time.Since(lastUpdateTime).Hours() >= viper.GetFloat64(config.ReminderWaitPeriodInHours)
} }
// Release represents a release
type Release struct { type Release struct {
Name string Name string
Checksums map[string]string Checksums map[string]string
} }
// Releases represents several release
type Releases []Release type Releases []Release
func getJSON(url string, target *Releases) error { func getJSON(url string, target *Releases) error {
@ -116,6 +120,7 @@ func getLatestVersionFromURL(url string) (semver.Version, error) {
return semver.Make(strings.TrimPrefix(r[0].Name, version.VersionPrefix)) return semver.Make(strings.TrimPrefix(r[0].Name, version.VersionPrefix))
} }
// GetAllVersionsFromURL get all versions from a JSON URL
func GetAllVersionsFromURL(url string) (Releases, error) { func GetAllVersionsFromURL(url string) (Releases, error) {
var releases Releases var releases Releases
glog.Info("Checking for updates...") glog.Info("Checking for updates...")

View File

@ -89,14 +89,17 @@ var (
registry = createRegistry() registry = createRegistry()
) )
// ListDrivers lists all drivers in registry
func ListDrivers() []DriverDef { func ListDrivers() []DriverDef {
return registry.List() return registry.List()
} }
// Register registers driver
func Register(driver DriverDef) error { func Register(driver DriverDef) error {
return registry.Register(driver) return registry.Register(driver)
} }
// Driver gets a named driver
func Driver(name string) (DriverDef, error) { func Driver(name string) (DriverDef, error) {
return registry.Driver(name) return registry.Driver(name)
} }

View File

@ -43,19 +43,23 @@ import (
"k8s.io/minikube/pkg/util" "k8s.io/minikube/pkg/util"
) )
// K8sClient represents a kubernetes client
type K8sClient interface { type K8sClient interface {
GetCoreClient() (corev1.CoreV1Interface, error) GetCoreClient() (corev1.CoreV1Interface, error)
GetClientset(timeout time.Duration) (*kubernetes.Clientset, error) GetClientset(timeout time.Duration) (*kubernetes.Clientset, error)
} }
// K8sClientGetter can get a K8sClient
type K8sClientGetter struct{} type K8sClientGetter struct{}
// K8s is the current K8sClient
var K8s K8sClient var K8s K8sClient
func init() { func init() {
K8s = &K8sClientGetter{} K8s = &K8sClientGetter{}
} }
// GetCoreClient returns a core client
func (k *K8sClientGetter) GetCoreClient() (corev1.CoreV1Interface, error) { func (k *K8sClientGetter) GetCoreClient() (corev1.CoreV1Interface, error) {
client, err := k.GetClientset(constants.DefaultK8sClientTimeout) client, err := k.GetClientset(constants.DefaultK8sClientTimeout)
if err != nil { if err != nil {
@ -64,6 +68,7 @@ func (k *K8sClientGetter) GetCoreClient() (corev1.CoreV1Interface, error) {
return client.Core(), nil return client.Core(), nil
} }
// GetClientset returns a clientset
func (*K8sClientGetter) GetClientset(timeout time.Duration) (*kubernetes.Clientset, error) { func (*K8sClientGetter) GetClientset(timeout time.Duration) (*kubernetes.Clientset, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
profile := viper.GetString(config.MachineProfile) profile := viper.GetString(config.MachineProfile)
@ -87,12 +92,14 @@ func (*K8sClientGetter) GetClientset(timeout time.Duration) (*kubernetes.Clients
return client, nil return client, nil
} }
// URL represents service URL
type URL struct { type URL struct {
Namespace string Namespace string
Name string Name string
URLs []string URLs []string
} }
// URLs represents a list of URL
type URLs []URL type URLs []URL
// GetServiceURLs returns all the node port URLs for every service in a particular namespace // GetServiceURLs returns all the node port URLs for every service in a particular namespace
@ -210,6 +217,7 @@ func CheckService(namespace string, service string) error {
return nil return nil
} }
// OptionallyHTTPSFormattedURLString returns a formatted URL string, optionally HTTPS
func OptionallyHTTPSFormattedURLString(bareURLString string, https bool) (string, bool) { func OptionallyHTTPSFormattedURLString(bareURLString string, https bool) (string, bool) {
httpsFormattedString := bareURLString httpsFormattedString := bareURLString
isHTTPSchemedURL := false isHTTPSchemedURL := false
@ -225,6 +233,7 @@ func OptionallyHTTPSFormattedURLString(bareURLString string, https bool) (string
return httpsFormattedString, isHTTPSchemedURL return httpsFormattedString, isHTTPSchemedURL
} }
// WaitAndMaybeOpenService waits for a service, and opens it when running
func WaitAndMaybeOpenService(api libmachine.API, namespace string, service string, urlTemplate *template.Template, urlMode bool, https bool, func WaitAndMaybeOpenService(api libmachine.API, namespace string, service string, urlTemplate *template.Template, urlMode bool, https bool,
wait int, interval int) error { wait int, interval int) error {
if err := util.RetryAfter(wait, func() error { return CheckService(namespace, service) }, time.Duration(interval)*time.Second); err != nil { if err := util.RetryAfter(wait, func() error { return CheckService(namespace, service) }, time.Duration(interval)*time.Second); err != nil {
@ -248,6 +257,7 @@ func WaitAndMaybeOpenService(api libmachine.API, namespace string, service strin
return nil return nil
} }
// GetServiceListByLabel returns a ServiceList by label
func GetServiceListByLabel(namespace string, key string, value string) (*v1.ServiceList, error) { func GetServiceListByLabel(namespace string, key string, value string) (*v1.ServiceList, error) {
client, err := K8s.GetCoreClient() client, err := K8s.GetCoreClient()
if err != nil { if err != nil {

View File

@ -33,6 +33,7 @@ type MockAPI struct {
SaveCalled bool SaveCalled bool
} }
// NewMockAPI returns a new MockAPI
func NewMockAPI() *MockAPI { func NewMockAPI() *MockAPI {
m := MockAPI{ m := MockAPI{
FakeStore: FakeStore{ FakeStore: FakeStore{

View File

@ -25,6 +25,7 @@ import (
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
) )
// MakeTempDir creates the temp dir and returns the path
func MakeTempDir() string { func MakeTempDir() string {
tempDir, err := ioutil.TempDir("", "minipath") tempDir, err := ioutil.TempDir("", "minipath")
if err != nil { if err != nil {

View File

@ -39,6 +39,7 @@ func (driver *MockDriver) Create() error {
return nil return nil
} }
// GetIP returns the IP address
func (driver *MockDriver) GetIP() (string, error) { func (driver *MockDriver) GetIP() (string, error) {
if driver.IP != "" { if driver.IP != "" {
return driver.IP, nil return driver.IP, nil
@ -54,6 +55,7 @@ func (driver *MockDriver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{} return []mcnflag.Flag{}
} }
// GetSSHPort returns the SSH port
func (driver *MockDriver) GetSSHPort() (int, error) { func (driver *MockDriver) GetSSHPort() (int, error) {
return driver.Port, nil return driver.Port, nil
} }

View File

@ -32,6 +32,7 @@ func (s *FakeStore) Exists(name string) (bool, error) {
return ok, nil return ok, nil
} }
// List returns the list of hosts.
func (s *FakeStore) List() ([]string, error) { func (s *FakeStore) List() ([]string, error) {
hostNames := []string{} hostNames := []string{}
for h := range s.Hosts { for h := range s.Hosts {

View File

@ -32,6 +32,7 @@ type MockHost struct {
Driver drivers.Driver Driver drivers.Driver
} }
// NewMockHost creates a new MockHost
func NewMockHost() *MockHost { func NewMockHost() *MockHost {
return &MockHost{ return &MockHost{
CommandOutput: make(map[string]string), CommandOutput: make(map[string]string),
@ -40,6 +41,7 @@ func NewMockHost() *MockHost {
} }
} }
// RunSSHCommand runs a SSH command, returning output
func (m MockHost) RunSSHCommand(cmd string) (string, error) { func (m MockHost) RunSSHCommand(cmd string) (string, error) {
m.Commands[cmd] = 1 m.Commands[cmd] = 1
output, ok := m.CommandOutput[cmd] output, ok := m.CommandOutput[cmd]

View File

@ -35,69 +35,86 @@ func (provisioner *MockProvisioner) String() string {
return "mock" return "mock"
} }
// Service performs an action for a service
func (provisioner *MockProvisioner) Service(name string, action serviceaction.ServiceAction) error { func (provisioner *MockProvisioner) Service(name string, action serviceaction.ServiceAction) error {
return nil return nil
} }
// Package performs an action for a package
func (provisioner *MockProvisioner) Package(name string, action pkgaction.PackageAction) error { func (provisioner *MockProvisioner) Package(name string, action pkgaction.PackageAction) error {
return nil return nil
} }
// Hostname returns the hostname
func (provisioner *MockProvisioner) Hostname() (string, error) { func (provisioner *MockProvisioner) Hostname() (string, error) {
return "mockhostname", nil return "mockhostname", nil
} }
// SetHostname sets the hostname
func (provisioner *MockProvisioner) SetHostname(hostname string) error { func (provisioner *MockProvisioner) SetHostname(hostname string) error {
return nil return nil
} }
// GetDockerOptionsDir gets Docker options dir
func (provisioner *MockProvisioner) GetDockerOptionsDir() string { func (provisioner *MockProvisioner) GetDockerOptionsDir() string {
return "/mockdirectory" return "/mockdirectory"
} }
// GetAuthOptions returns a the auth.Options
func (provisioner *MockProvisioner) GetAuthOptions() auth.Options { func (provisioner *MockProvisioner) GetAuthOptions() auth.Options {
return auth.Options{} return auth.Options{}
} }
// GenerateDockerOptions generates Docker options
func (provisioner *MockProvisioner) GenerateDockerOptions(dockerPort int) (*provision.DockerOptions, error) { func (provisioner *MockProvisioner) GenerateDockerOptions(dockerPort int) (*provision.DockerOptions, error) {
return &provision.DockerOptions{}, nil return &provision.DockerOptions{}, nil
} }
// CompatibleWithHost checks if provisioner is compatible with host
func (provisioner *MockProvisioner) CompatibleWithHost() bool { func (provisioner *MockProvisioner) CompatibleWithHost() bool {
return true return true
} }
// SetOsReleaseInfo sets the os-release info
func (provisioner *MockProvisioner) SetOsReleaseInfo(info *provision.OsRelease) { func (provisioner *MockProvisioner) SetOsReleaseInfo(info *provision.OsRelease) {
} }
// GetOsReleaseInfo gets the os-release info
func (provisioner *MockProvisioner) GetOsReleaseInfo() (*provision.OsRelease, error) { func (provisioner *MockProvisioner) GetOsReleaseInfo() (*provision.OsRelease, error) {
return nil, nil return nil, nil
} }
// AttemptIPContact attemps to contact an IP and port
func (provisioner *MockProvisioner) AttemptIPContact(dockerPort int) { func (provisioner *MockProvisioner) AttemptIPContact(dockerPort int) {
} }
// Provision provisions the machine
func (provisioner *MockProvisioner) Provision(swarmOptions swarm.Options, authOptions auth.Options, engineOptions engine.Options) error { func (provisioner *MockProvisioner) Provision(swarmOptions swarm.Options, authOptions auth.Options, engineOptions engine.Options) error {
provisioner.Provisioned = true provisioner.Provisioned = true
return nil return nil
} }
// SSHCommand runs a SSH command
func (provisioner *MockProvisioner) SSHCommand(args string) (string, error) { func (provisioner *MockProvisioner) SSHCommand(args string) (string, error) {
return "", nil return "", nil
} }
// GetDriver gets the driver
func (provisioner *MockProvisioner) GetDriver() drivers.Driver { func (provisioner *MockProvisioner) GetDriver() drivers.Driver {
return &MockDriver{} return &MockDriver{}
} }
// GetSwarmOptions gets the swarm.Options
func (provisioner *MockProvisioner) GetSwarmOptions() swarm.Options { func (provisioner *MockProvisioner) GetSwarmOptions() swarm.Options {
return swarm.Options{} return swarm.Options{}
} }
// MockDetector can detect MockProvisioner
type MockDetector struct { type MockDetector struct {
Provisioner *MockProvisioner Provisioner *MockProvisioner
} }
// DetectProvisioner detects a provisioner
func (m *MockDetector) DetectProvisioner(d drivers.Driver) (provision.Provisioner, error) { func (m *MockDetector) DetectProvisioner(d drivers.Driver) (provision.Provisioner, error) {
return m.Provisioner, nil return m.Provisioner, nil
} }

View File

@ -154,10 +154,12 @@ func (s *SSHServer) Start() (int, error) {
return port, nil return port, nil
} }
// SetCommandToOutput sets command to output
func (s *SSHServer) SetCommandToOutput(cmdToOutput map[string]string) { func (s *SSHServer) SetCommandToOutput(cmdToOutput map[string]string) {
s.commandToOutput.Store(cmdToOutput) s.commandToOutput.Store(cmdToOutput)
} }
// GetCommandToOutput gets command to output
func (s *SSHServer) GetCommandToOutput(cmd string) (string, error) { func (s *SSHServer) GetCommandToOutput(cmd string) (string, error) {
cmdMap := s.commandToOutput.Load().(map[string]string) cmdMap := s.commandToOutput.Load().(map[string]string)
val, ok := cmdMap[cmd] val, ok := cmdMap[cmd]
@ -167,6 +169,7 @@ func (s *SSHServer) GetCommandToOutput(cmd string) (string, error) {
return val, nil return val, nil
} }
// SetSessionRequested sets session requested
func (s *SSHServer) SetSessionRequested(b bool) { func (s *SSHServer) SetSessionRequested(b bool) {
var i int32 var i int32
if b { if b {
@ -175,6 +178,7 @@ func (s *SSHServer) SetSessionRequested(b bool) {
atomic.StoreInt32(&s.hadASessionRequested, i) atomic.StoreInt32(&s.hadASessionRequested, i)
} }
// IsSessionRequested gets session requested
func (s *SSHServer) IsSessionRequested() bool { func (s *SSHServer) IsSessionRequested() bool {
return atomic.LoadInt32(&s.hadASessionRequested) != 0 return atomic.LoadInt32(&s.hadASessionRequested) != 0
} }

View File

@ -29,6 +29,7 @@ import (
// There is one tunnel registry per user, shared across multiple vms. // There is one tunnel registry per user, shared across multiple vms.
// It can register, list and check for existing and running tunnels // It can register, list and check for existing and running tunnels
// ID represents a registry ID
type ID struct { type ID struct {
//Route is the key //Route is the key
Route *Route Route *Route
@ -37,6 +38,7 @@ type ID struct {
Pid int Pid int
} }
// Equal checks if two ID are equal
func (t *ID) Equal(other *ID) bool { func (t *ID) Equal(other *ID) bool {
return t.Route.Equal(other.Route) && return t.Route.Equal(other.Route) &&
t.MachineName == other.MachineName && t.MachineName == other.MachineName &&

View File

@ -41,6 +41,7 @@ type Manager struct {
//stateCheckInterval defines how frequently the cluster and route states are checked //stateCheckInterval defines how frequently the cluster and route states are checked
const stateCheckInterval = 5 * time.Second const stateCheckInterval = 5 * time.Second
// NewManager creates a new Manager
func NewManager() *Manager { func NewManager() *Manager {
return &Manager{ return &Manager{
delay: stateCheckInterval, delay: stateCheckInterval,
@ -50,6 +51,8 @@ func NewManager() *Manager {
router: &osRouter{}, router: &osRouter{},
} }
} }
// StartTunnel starts the tunnel
func (mgr *Manager) StartTunnel(ctx context.Context, machineName string, machineAPI libmachine.API, configLoader config.Loader, v1Core v1.CoreV1Interface) (done chan bool, err error) { func (mgr *Manager) StartTunnel(ctx context.Context, machineName string, machineAPI libmachine.API, configLoader config.Loader, v1Core v1.CoreV1Interface) (done chan bool, err error) {
tunnel, err := newTunnel(machineName, machineAPI, configLoader, v1Core, mgr.registry, mgr.router) tunnel, err := newTunnel(machineName, machineAPI, configLoader, v1Core, mgr.registry, mgr.router)
if err != nil { if err != nil {
@ -117,6 +120,7 @@ func (mgr *Manager) cleanup(t controller) *Status {
return t.cleanup() return t.cleanup()
} }
// CleanupNotRunningTunnels cleans up tunnels that are not running
func (mgr *Manager) CleanupNotRunningTunnels() error { func (mgr *Manager) CleanupNotRunningTunnels() error {
tunnels, err := mgr.registry.List() tunnels, err := mgr.registry.List()
if err != nil { if err != nil {

View File

@ -23,6 +23,7 @@ import (
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
) )
// Status represents the tunnel status
type Status struct { type Status struct {
TunnelID ID TunnelID ID
@ -35,6 +36,7 @@ type Status struct {
LoadBalancerEmulatorError error LoadBalancerEmulatorError error
} }
// Clone clones an existing Status
func (t *Status) Clone() *Status { func (t *Status) Clone() *Status {
return &Status{ return &Status{
TunnelID: t.TunnelID, TunnelID: t.TunnelID,
@ -57,6 +59,7 @@ func (t *Status) String() string {
t.LoadBalancerEmulatorError) t.LoadBalancerEmulatorError)
} }
// Route represents a route
type Route struct { type Route struct {
Gateway net.IP Gateway net.IP
DestCIDR *net.IPNet DestCIDR *net.IPNet
@ -66,12 +69,14 @@ func (r *Route) String() string {
return fmt.Sprintf("%s -> %s", r.DestCIDR.String(), r.Gateway.String()) return fmt.Sprintf("%s -> %s", r.DestCIDR.String(), r.Gateway.String())
} }
// Equal checks if two routes are equal
func (r *Route) Equal(other *Route) bool { func (r *Route) Equal(other *Route) bool {
return other != nil && r.DestCIDR.IP.Equal(other.DestCIDR.IP) && return other != nil && r.DestCIDR.IP.Equal(other.DestCIDR.IP) &&
r.DestCIDR.Mask.String() == other.DestCIDR.Mask.String() && r.DestCIDR.Mask.String() == other.DestCIDR.Mask.String() &&
r.Gateway.Equal(other.Gateway) r.Gateway.Equal(other.Gateway)
} }
// Patch represents a patch
type Patch struct { type Patch struct {
Type types.PatchType Type types.PatchType
NameSpace string NameSpace string
@ -86,8 +91,11 @@ type Patch struct {
type HostState int type HostState int
const ( const (
// Unknown represents an unknown state
Unknown HostState = iota Unknown HostState = iota
// Running represents a running state
Running Running
// Stopped represents a stopped state
Stopped Stopped
) )