Merge branch 'master' into persistent

pull/5032/head
Thomas Stromberg 2019-08-14 08:12:25 -07:00
commit b983c47145
196 changed files with 5220 additions and 4813 deletions

6
.gitignore vendored
View File

@ -44,3 +44,9 @@ deploy/iso/minikube-iso/board/coreos/minikube/rootfs-overlay/etc/VERSION
/.vscode /.vscode
test/integration/testdata/minikube-linux-amd64-latest-stable test/integration/testdata/minikube-linux-amd64-latest-stable
# hugo
/public
/site/resources
/_gen

View File

@ -1,6 +1,8 @@
language: go language: go
os: linux os: linux
env:
- GOPROXY=https://proxy.golang.org
matrix: matrix:
include: include:
- go: 1.12.7 - go: 1.12.7

View File

@ -1,5 +1,24 @@
# Release Notes # Release Notes
## Version 1.3.1 - 2019-08-13
* Update code references to point to new documentation site [#5052](https://github.com/kubernetes/minikube/pull/5052)
* Localization support for help text [#4814](https://github.com/kubernetes/minikube/pull/4814)
* Fix progress bar on Windows + git bash [#5025](https://github.com/kubernetes/minikube/pull/5025)
* Restore --disable-driver-mounts flag [#5026](https://github.com/kubernetes/minikube/pull/5026)
* Fixed the template for dashboard output [#5004](https://github.com/kubernetes/minikube/pull/5004)
* Use a temp dest to atomically download the iso [#5000](https://github.com/kubernetes/minikube/pull/5000)
Thank you to our merry band of contributors for assembling this last minute bug fix release.
- Jituri, Pranav
- Medya Ghazizadeh
- Pranav Jituri
- Ramiro Berrelleza
- Sharif Elgamal
- Thomas Strömberg
- josedonizetti
## Version 1.3.0 - 2019-08-05 ## Version 1.3.0 - 2019-08-05
* Added a new command: profile list [#4811](https://github.com/kubernetes/minikube/pull/4811) * Added a new command: profile list [#4811](https://github.com/kubernetes/minikube/pull/4811)
@ -1133,7 +1152,7 @@ Huge Thank You for this release to our contributors:
* Added a `minikube dashboard` command to open the Kubernetes Dashboard. * Added a `minikube dashboard` command to open the Kubernetes Dashboard.
* Updated Docker to version 1.11.1. * Updated Docker to version 1.11.1.
* Updated Kubernetes components to v1.3.0-alpha.5-330-g760c563. * Updated Kubernetes components to v1.3.0-alpha.5-330-g760c563.
* Generated documentation for all commands. Documentation [is here](https://github.com/kubernetes/minikube/blob/master/docs/minikube.md). * Generated documentation for all commands. Documentation [is here](https://minikube.sigs.k8s.io/docs/).
## Version 0.2.0 - 6/3/2016 ## Version 0.2.0 - 6/3/2016

View File

@ -1,21 +1 @@
# Contributing guidelines This document has moved to https://minikube.sigs.k8s.io/docs/contributing/guide/
## Filing issues
File issues using the standard Github issue tracker for the repo.
## How to become a contributor and submit your own code
### Contributor License Agreements
We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles.
[Please fill out either the individual or corporate Contributor License Agreement (CLA)](http://git.k8s.io/community/CLA.md)
### Contributing A Patch
1. Submit an issue describing your proposed change to the repo in question.
1. The repo owner will respond to your issue promptly.
1. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above).
1. Fork the desired repo, develop and test your code changes.
1. Submit a pull request.

View File

@ -1,4 +0,0 @@
Thomas Stromberg <tstromberg@google.com> (@tstromberg)
Anders F Björklund <anders.f.bjorklund@gmail.com> (@afbjorklund)
Sharif Elgamal <selgamal@google.com> (@sharifelgamal)
Medya Ghazizadeh <medya@google.com> (@medyagh)

View File

@ -15,7 +15,7 @@
# Bump these on release - and please check ISO_VERSION for correctness. # Bump these on release - and please check ISO_VERSION for correctness.
VERSION_MAJOR ?= 1 VERSION_MAJOR ?= 1
VERSION_MINOR ?= 3 VERSION_MINOR ?= 3
VERSION_BUILD ?= 0 VERSION_BUILD ?= 1
# Default to .0 for higher cache hit rates, as build increments typically don't require new ISO versions # Default to .0 for higher cache hit rates, as build increments typically don't require new ISO versions
ISO_VERSION ?= v$(VERSION_MAJOR).$(VERSION_MINOR).0 ISO_VERSION ?= v$(VERSION_MAJOR).$(VERSION_MINOR).0
@ -375,7 +375,7 @@ out/minikube-installer.exe: out/minikube-windows-amd64.exe
mv out/windows_tmp/minikube-installer.exe out/minikube-installer.exe mv out/windows_tmp/minikube-installer.exe out/minikube-installer.exe
rm -rf out/windows_tmp rm -rf out/windows_tmp
out/docker-machine-driver-hyperkit: pkg/minikube/translate/translations.go out/docker-machine-driver-hyperkit:
ifeq ($(MINIKUBE_BUILD_IN_DOCKER),y) ifeq ($(MINIKUBE_BUILD_IN_DOCKER),y)
$(call DOCKER,$(HYPERKIT_BUILD_IMAGE),CC=o64-clang CXX=o64-clang++ /usr/bin/make $@) $(call DOCKER,$(HYPERKIT_BUILD_IMAGE),CC=o64-clang CXX=o64-clang++ /usr/bin/make $@)
else else
@ -441,18 +441,18 @@ release-minikube: out/minikube checksum
gsutil cp out/minikube-$(GOOS)-$(GOARCH) $(MINIKUBE_UPLOAD_LOCATION)/$(MINIKUBE_VERSION)/minikube-$(GOOS)-$(GOARCH) gsutil cp out/minikube-$(GOOS)-$(GOARCH) $(MINIKUBE_UPLOAD_LOCATION)/$(MINIKUBE_VERSION)/minikube-$(GOOS)-$(GOARCH)
gsutil cp out/minikube-$(GOOS)-$(GOARCH).sha256 $(MINIKUBE_UPLOAD_LOCATION)/$(MINIKUBE_VERSION)/minikube-$(GOOS)-$(GOARCH).sha256 gsutil cp out/minikube-$(GOOS)-$(GOARCH).sha256 $(MINIKUBE_UPLOAD_LOCATION)/$(MINIKUBE_VERSION)/minikube-$(GOOS)-$(GOARCH).sha256
out/docker-machine-driver-kvm2: pkg/minikube/translate/translations.go out/docker-machine-driver-kvm2:
ifeq ($(MINIKUBE_BUILD_IN_DOCKER),y) ifeq ($(MINIKUBE_BUILD_IN_DOCKER),y)
docker inspect -f '{{.Id}} {{.RepoTags}}' $(KVM_BUILD_IMAGE) || $(MAKE) kvm-image docker inspect -f '{{.Id}} {{.RepoTags}}' $(KVM_BUILD_IMAGE) || $(MAKE) kvm-image
$(call DOCKER,$(KVM_BUILD_IMAGE),/usr/bin/make $@ COMMIT=$(COMMIT)) $(call DOCKER,$(KVM_BUILD_IMAGE),/usr/bin/make $@ COMMIT=$(COMMIT))
# make extra sure that we are linking with the older version of libvirt (1.3.1) # make extra sure that we are linking with the older version of libvirt (1.3.1)
test "`strings $@ | grep '^LIBVIRT_[0-9]' | sort | tail -n 1`" = "LIBVIRT_1.2.9" test "`strings $@ | grep '^LIBVIRT_[0-9]' | sort | tail -n 1`" = "LIBVIRT_1.2.9"
else else
go build \ go build \
-installsuffix "static" \ -installsuffix "static" \
-ldflags="$(KVM2_LDFLAGS)" \ -ldflags="$(KVM2_LDFLAGS)" \
-tags "libvirt.1.3.1 without_lxc" \ -tags "libvirt.1.3.1 without_lxc" \
-o $(BUILD_DIR)/docker-machine-driver-kvm2 \ -o $(BUILD_DIR)/docker-machine-driver-kvm2 \
k8s.io/minikube/cmd/drivers/kvm k8s.io/minikube/cmd/drivers/kvm
endif endif
chmod +X $@ chmod +X $@
@ -493,3 +493,21 @@ install-kvm-driver: out/docker-machine-driver-kvm2
release-kvm-driver: install-kvm-driver checksum release-kvm-driver: install-kvm-driver checksum
gsutil cp $(GOBIN)/docker-machine-driver-kvm2 gs://minikube/drivers/kvm/$(VERSION)/ gsutil cp $(GOBIN)/docker-machine-driver-kvm2 gs://minikube/drivers/kvm/$(VERSION)/
gsutil cp $(GOBIN)/docker-machine-driver-kvm2.sha256 gs://minikube/drivers/kvm/$(VERSION)/ gsutil cp $(GOBIN)/docker-machine-driver-kvm2.sha256 gs://minikube/drivers/kvm/$(VERSION)/
site/themes/docsy/assets/vendor/bootstrap/package.js:
git submodule update -f --init --recursive
# hugo for generating site previews
out/hugo/hugo:
mkdir -p out
test -d out/hugo || git clone https://github.com/gohugoio/hugo.git out/hugo
(cd out/hugo && go build --tags extended)
# Serve the documentation site to localhost
.PHONY: site
site: site/themes/docsy/assets/vendor/bootstrap/package.js out/hugo/hugo
(cd site && ../out/hugo/hugo serve \
--disableFastRender \
--navigateToChanged \
--ignoreCache \
--buildFuture)

122
README.md
View File

@ -9,53 +9,47 @@
[GoReport Status]: https://goreportcard.com/report/github.com/kubernetes/minikube [GoReport Status]: https://goreportcard.com/report/github.com/kubernetes/minikube
[GoReport Widget]: https://goreportcard.com/badge/github.com/kubernetes/minikube [GoReport Widget]: https://goreportcard.com/badge/github.com/kubernetes/minikube
<img src="https://github.com/kubernetes/minikube/raw/master/images/logo/logo.png" width="100"> <img src="https://github.com/kubernetes/minikube/raw/master/images/logo/logo.png" width="100" alt="minikube logo">
## What is minikube? minikube implements a local Kubernetes cluster on macOS, Linux, and Windows. minikube's [primary goals](https://minikube.sigs.k8s.io/docs/concepts/principles/) are to be the best tool for local Kubernetes application development and to support all Kubernetes features that fit.
minikube implements a local Kubernetes cluster on macOS, Linux, and Windows. <img src="https://github.com/kubernetes/minikube/raw/master/site/content/en/start.png" width="730" alt="screenshot">
![screenshot](/images/start.jpg)
minikube's [primary goals](https://github.com/kubernetes/minikube/blob/master/docs/contributors/principles.md) are to be the best tool for local Kubernetes application development and to support all Kubernetes features that fit. We hope you enjoy it!
## News
:mega: **Please fill out our [fast 5-question survey](https://forms.gle/Gg3hG5ZySw8c1C24A)** so that we can learn how & why you use minikube, and what improvements we should make. Thank you! :dancers:
* 2019-08-05 - v1.3.0 released! [[download](https://github.com/kubernetes/minikube/releases/tag/v1.3.0)] [[release notes](https://github.com/kubernetes/minikube/blob/master/CHANGELOG.md#version-130---2019-08-05)]
## Features ## Features
minikube runs the latest stable release of Kubernetes, with support for standard Kubernetes features like: minikube runs the latest stable release of Kubernetes, with support for standard Kubernetes features like:
* [LoadBalancer](https://github.com/kubernetes/minikube/blob/master/docs/tunnel.md) - using `minikube tunnel` * [LoadBalancer](https://minikube.sigs.k8s.io/docs/tasks/loadbalancer/) - using `minikube tunnel`
* Multi-cluster - using `minikube start -p <name>` * Multi-cluster - using `minikube start -p <name>`
* NodePorts - using `minikube service` * NodePorts - using `minikube service`
* [Persistent Volumes](https://github.com/kubernetes/minikube/blob/master/docs/persistent_volumes.md) * [Persistent Volumes](https://minikube.sigs.k8s.io/docs/reference/persistent_volumes/)
* Ingress * Ingress
* RBAC * [Dashboard](https://minikube.sigs.k8s.io/docs/tasks/dashboard/) - `minikube dashboard`
* [Dashboard](https://github.com/kubernetes/minikube/blob/master/docs/dashboard.md) - `minikube dashboard` * [Container runtimes](https://minikube.sigs.k8s.io/docs/reference/runtimes/) - `start --container-runtime`
* [Container runtimes](https://github.com/kubernetes/minikube/blob/master/docs/alternative_runtimes.md) - `start --container-runtime` * [Configure apiserver and kubelet options](https://minikube.sigs.k8s.io/docs/reference/configuration/kubernetes/) via command-line flags
* [Configure apiserver and kubelet options](https://github.com/kubernetes/minikube/blob/master/docs/configuring_kubernetes.md) via command-line flags
As well as developer-friendly features: As well as developer-friendly features:
* [Addons](https://github.com/kubernetes/minikube/blob/master/docs/addons.md) - a marketplace for developers to share configurations for running services on minikube * [Addons](https://minikube.sigs.k8s.io/docs/tasks/addons/) - a marketplace for developers to share configurations for running services on minikube
* [GPU support](https://github.com/kubernetes/minikube/blob/master/docs/gpu.md) - for machine learning * [NVIDIA GPU support](https://minikube.sigs.k8s.io/docs/tutorials/nvidia_gpu/) - for machine learning
* [Filesystem mounts](https://github.com/kubernetes/minikube/blob/master/docs/host_folder_mount.md) * [Filesystem mounts](https://minikube.sigs.k8s.io/docs/tasks/mount/)
* Automatic failure analysis
**For more information, see the official [minikube website](https://minikube.sigs.k8s.io)**
## Installation
Installation methods can be found in the [Getting Started Guide](https://minikube.sigs.k8s.io/docs/start/)
## Documentation ## Documentation
* [**Installation**](https://kubernetes.io/docs/tasks/tools/install-minikube/) See https://minikube.sigs.k8s.io/docs/
* [Advanced Topics and Tutorials](https://github.com/kubernetes/minikube/blob/master/docs/README.md)
* [Contributors Guide](https://github.com/kubernetes/minikube/blob/master/docs/contributors/README.md) ## More Examples
See our [examples page](https://minikube.sigs.k8s.io/docs/examples/)
## Community ## Community
![Help Wanted!](/images/help_wanted.jpg)
minikube is a Kubernetes [#sig-cluster-lifecycle](https://github.com/kubernetes/community/tree/master/sig-cluster-lifecycle) project. minikube is a Kubernetes [#sig-cluster-lifecycle](https://github.com/kubernetes/community/tree/master/sig-cluster-lifecycle) project.
* [**#minikube on Kubernetes Slack**](https://kubernetes.slack.com) - Live chat with minikube developers! * [**#minikube on Kubernetes Slack**](https://kubernetes.slack.com) - Live chat with minikube developers!
@ -63,74 +57,6 @@ minikube is a Kubernetes [#sig-cluster-lifecycle](https://github.com/kubernetes/
* [minikube-dev mailing list](https://groups.google.com/forum/#!forum/minikube-dev) * [minikube-dev mailing list](https://groups.google.com/forum/#!forum/minikube-dev)
* [Bi-weekly office hours, Mondays @ 10am PST](https://tinyurl.com/minikube-oh) * [Bi-weekly office hours, Mondays @ 10am PST](https://tinyurl.com/minikube-oh)
* [Contributing](https://github.com/kubernetes/minikube/blob/master/CONTRIBUTING.md) * [Contributing](https://minikube.sigs.k8s.io/docs/contributing/)
* [Development Roadmap](https://github.com/kubernetes/minikube/blob/master/docs/contributors/roadmap.md) * [Development Roadmap](https://minikube.sigs.k8s.io/docs/contributing/roadmap/)
## Installation
See the [installation guide](https://kubernetes.io/docs/tasks/tools/install-minikube/). For the impatient, here is the TL;DR:
* *macOS 10.12 (Sierra)*
* Requires installing a hypervisor, such as [hyperkit](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#hyperkit-driver) (recommended) or VirtualBox
* using [brew](https://brew.sh/): `brew cask install minikube`
* manually: `curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-amd64 && sudo install minikube-darwin-amd64 /usr/local/bin/minikube`
* *Windows 10*
* Requires a hypervisor, such as VirtualBox (recommended) or HyperV
* VT-x/AMD-v virtualization must be enabled in BIOS
* using [chocolatey](https://chocolatey.org/) `choco install minikube`
* manually: Download and run the [installer](https://storage.googleapis.com/minikube/releases/latest/minikube-installer.exe)
* *Linux*
* Requires either the [kvm2 driver](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#kvm2-driver) (recommended), or VirtualBox
* VT-x/AMD-v virtualization must be enabled in BIOS
* manually: `curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && sudo install minikube-linux-amd64 /usr/local/bin/minikube`
### Supported Hypervisors
`minikube start` defaults to virtualbox, but supports other drivers using the `--vm-driver` argument:
* [KVM2](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#kvm2-driver) - Recommended Linux driver
* [hyperkit](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#hyperkit-driver) - Recommended macOS driver
* virtualbox - Recommended Windows driver
* [none](https://github.com/kubernetes/minikube/blob/master/docs/vmdriver-none.md) - bare-metal execution on Linux, at the expense of system security and reliability
Other drivers which are not yet part of our continuous integration system are:
* [hyperv](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#hyperV-driver)
* [vmware](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#vmware-unified-driver)
* [parallels](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#parallels-driver)
## Quick Start
Start a cluster by running:
`minikube start`
Access Kubernetes Dashboard within Minikube:
`minikube dashboard`
Once started, you can interact with your cluster using `kubectl`, just like any other Kubernetes cluster. For instance, starting a server:
`kubectl run hello-minikube --image=k8s.gcr.io/echoserver:1.4 --port=8080`
Exposing a service as a NodePort
`kubectl expose deployment hello-minikube --type=NodePort`
minikube makes it easy to open this exposed endpoint in your browser:
`minikube service hello-minikube`
Start a second local cluster:
`minikube start -p cluster2`
Stop your local cluster:
`minikube stop`
Delete your local cluster:
`minikube delete`

View File

@ -24,8 +24,8 @@ import (
pkgConfig "k8s.io/minikube/pkg/minikube/config" pkgConfig "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
pkgutil "k8s.io/minikube/pkg/util"
) )
// ProfileCmd represents the profile command // ProfileCmd represents the profile command
@ -48,6 +48,15 @@ var ProfileCmd = &cobra.Command{
if profile == "default" { if profile == "default" {
profile = "minikube" profile = "minikube"
} }
if !pkgConfig.ProfileExists(profile) {
err := pkgConfig.CreateEmptyProfile(profile)
if err != nil {
exit.WithError("Creating a new profile failed", err)
}
out.SuccessT("Created a new profile : {{.profile_name}}", out.V{"profile_name": profile})
}
err := Set(pkgConfig.MachineProfile, profile) err := Set(pkgConfig.MachineProfile, profile)
if err != nil { if err != nil {
exit.WithError("Setting profile failed", err) exit.WithError("Setting profile failed", err)
@ -62,7 +71,7 @@ var ProfileCmd = &cobra.Command{
out.SuccessT("Skipped switching kubectl context for {{.profile_name}} , because --keep-context", out.V{"profile_name": profile}) out.SuccessT("Skipped switching kubectl context for {{.profile_name}} , because --keep-context", out.V{"profile_name": profile})
out.SuccessT("To connect to this cluster, use: kubectl --context={{.profile_name}}", out.V{"profile_name": profile}) out.SuccessT("To connect to this cluster, use: kubectl --context={{.profile_name}}", out.V{"profile_name": profile})
} else { } else {
err := pkgutil.SetCurrentContext(constants.KubeconfigPath, profile) err := kubeconfig.SetCurrentContext(constants.KubeconfigPath, profile)
if err != nil { if err != nil {
out.ErrT(out.Sad, `Error while setting kubectl current context : {{.error}}`, out.V{"error": err}) out.ErrT(out.Sad, `Error while setting kubectl current context : {{.error}}`, out.V{"error": err})
} }

View File

@ -45,7 +45,7 @@ var profileListCmd = &cobra.Command{
validProfiles, invalidProfiles, err := config.ListProfiles() validProfiles, invalidProfiles, err := config.ListProfiles()
if len(validProfiles) == 0 || err != nil { if len(validProfiles) == 0 || err != nil {
exit.UsageT("No minikube profile was found. you could create one using: `minikube start`") exit.UsageT("No minikube profile was found. You can create one using `minikube start`.")
} }
for _, p := range validProfiles { for _, p := range validProfiles {
validData = append(validData, []string{p.Name, p.Config.MachineConfig.VMDriver, p.Config.KubernetesConfig.NodeIP, strconv.Itoa(p.Config.KubernetesConfig.NodePort), p.Config.KubernetesConfig.KubernetesVersion}) validData = append(validData, []string{p.Name, p.Config.MachineConfig.VMDriver, p.Config.KubernetesConfig.NodeIP, strconv.Itoa(p.Config.KubernetesConfig.NodePort), p.Config.KubernetesConfig.KubernetesVersion})

View File

@ -129,7 +129,7 @@ var dashboardCmd = &cobra.Command{
if dashboardURLMode { if dashboardURLMode {
out.Ln(url) out.Ln(url)
} else { } else {
out.ErrT(out.Celebrate, "Opening {{.url}} in your default browser...", out.V{"url": url}) out.T(out.Celebrate, "Opening {{.url}} in your default browser...", out.V{"url": url})
if err = browser.OpenURL(url); err != nil { if err = browser.OpenURL(url); err != nil {
exit.WithCodeT(exit.Software, "failed to open browser: {{.error}}", out.V{"error": err}) exit.WithCodeT(exit.Software, "failed to open browser: {{.error}}", out.V{"error": err})
} }

View File

@ -17,22 +17,27 @@ limitations under the License.
package cmd package cmd
import ( import (
"fmt"
"io/ioutil"
"os" "os"
"path/filepath"
"strconv"
"github.com/docker/machine/libmachine" "github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/mcnerror" "github.com/docker/machine/libmachine/mcnerror"
"github.com/golang/glog"
ps "github.com/mitchellh/go-ps"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config" cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
cmdUtil "k8s.io/minikube/cmd/util"
"k8s.io/minikube/pkg/minikube/cluster" "k8s.io/minikube/pkg/minikube/cluster"
pkg_config "k8s.io/minikube/pkg/minikube/config" pkg_config "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
pkgutil "k8s.io/minikube/pkg/util"
) )
// deleteCmd represents the delete command // deleteCmd represents the delete command
@ -75,11 +80,11 @@ func runDelete(cmd *cobra.Command, args []string) {
} }
} }
if err := cmdUtil.KillMountProcess(); err != nil { if err := killMountProcess(); err != nil {
out.FatalT("Failed to kill mount process: {{.error}}", out.V{"error": err}) out.FatalT("Failed to kill mount process: {{.error}}", out.V{"error": err})
} }
if err := os.RemoveAll(constants.GetProfilePath(viper.GetString(pkg_config.MachineProfile))); err != nil { if err := pkg_config.DeleteProfile(viper.GetString(pkg_config.MachineProfile)); err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
out.T(out.Meh, `"{{.profile_name}}" profile does not exist`, out.V{"profile_name": profile}) out.T(out.Meh, `"{{.profile_name}}" profile does not exist`, out.V{"profile_name": profile})
os.Exit(0) os.Exit(0)
@ -89,7 +94,7 @@ func runDelete(cmd *cobra.Command, args []string) {
out.T(out.Crushed, `The "{{.cluster_name}}" cluster has been deleted.`, out.V{"cluster_name": profile}) out.T(out.Crushed, `The "{{.cluster_name}}" cluster has been deleted.`, out.V{"cluster_name": profile})
machineName := pkg_config.GetMachineName() machineName := pkg_config.GetMachineName()
if err := pkgutil.DeleteKubeConfigContext(constants.KubeconfigPath, machineName); err != nil { if err := kubeconfig.DeleteContext(constants.KubeconfigPath, machineName); err != nil {
exit.WithError("update config", err) exit.WithError("update config", err)
} }
@ -107,3 +112,51 @@ func uninstallKubernetes(api libmachine.API, kc pkg_config.KubernetesConfig, bsN
out.ErrT(out.Empty, "Failed to delete cluster: {{.error}}", out.V{"error": err}) out.ErrT(out.Empty, "Failed to delete cluster: {{.error}}", out.V{"error": err})
} }
} }
// killMountProcess kills the mount process, if it is running
func killMountProcess() error {
pidPath := filepath.Join(constants.GetMinipath(), constants.MountProcessFileName)
if _, err := os.Stat(pidPath); os.IsNotExist(err) {
return nil
}
glog.Infof("Found %s ...", pidPath)
out, err := ioutil.ReadFile(pidPath)
if err != nil {
return errors.Wrap(err, "ReadFile")
}
glog.Infof("pidfile contents: %s", out)
pid, err := strconv.Atoi(string(out))
if err != nil {
return errors.Wrap(err, "error parsing pid")
}
// os.FindProcess does not check if pid is running :(
entry, err := ps.FindProcess(pid)
if err != nil {
return errors.Wrap(err, "ps.FindProcess")
}
if entry == nil {
glog.Infof("Stale pid: %d", pid)
if err := os.Remove(pidPath); err != nil {
return errors.Wrap(err, "Removing stale pid")
}
return nil
}
// We found a process, but it still may not be ours.
glog.Infof("Found process %d: %s", pid, entry.Executable())
proc, err := os.FindProcess(pid)
if err != nil {
return errors.Wrap(err, "os.FindProcess")
}
glog.Infof("Killing pid %d ...", pid)
if err := proc.Kill(); err != nil {
glog.Infof("Kill failed with %v - removing probably stale pid...", err)
if err := os.Remove(pidPath); err != nil {
return errors.Wrap(err, "Removing likely stale unkillable pid")
}
return errors.Wrap(err, fmt.Sprintf("Kill(%d/%s)", pid, entry.Executable()))
}
return nil
}

View File

@ -44,7 +44,7 @@ var (
// logsCmd represents the logs command // logsCmd represents the logs command
var logsCmd = &cobra.Command{ var logsCmd = &cobra.Command{
Use: "logs", Use: "logs",
Short: "Gets the logs of the running instance, used for debugging minikube, not user code", Short: "Gets the logs of the running instance, used for debugging minikube, not user code.",
Long: `Gets the logs of the running instance, used for debugging minikube, not user code.`, Long: `Gets the logs of the running instance, used for debugging minikube, not user code.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
cfg, err := config.Load() cfg, err := config.Load()

View File

@ -27,8 +27,8 @@ import (
"syscall" "syscall"
"github.com/golang/glog" "github.com/golang/glog"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
cmdUtil "k8s.io/minikube/cmd/util"
"k8s.io/minikube/pkg/minikube/cluster" "k8s.io/minikube/pkg/minikube/cluster"
"k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
@ -62,7 +62,7 @@ var mountCmd = &cobra.Command{
Long: `Mounts the specified directory into minikube.`, Long: `Mounts the specified directory into minikube.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if isKill { if isKill {
if err := cmdUtil.KillMountProcess(); err != nil { if err := killMountProcess(); err != nil {
exit.WithError("Error killing mount process", err) exit.WithError("Error killing mount process", err)
} }
os.Exit(0) os.Exit(0)
@ -118,7 +118,7 @@ var mountCmd = &cobra.Command{
exit.WithCodeT(exit.Data, "error parsing the input ip address for mount") exit.WithCodeT(exit.Data, "error parsing the input ip address for mount")
} }
} }
port, err := cmdUtil.GetPort() port, err := getPort()
if err != nil { if err != nil {
exit.WithError("Error finding port for mount", err) exit.WithError("Error finding port for mount", err)
} }
@ -210,3 +210,18 @@ func init() {
mountCmd.Flags().StringSliceVar(&options, "options", []string{}, "Additional mount options, such as cache=fscache") mountCmd.Flags().StringSliceVar(&options, "options", []string{}, "Additional mount options, such as cache=fscache")
mountCmd.Flags().IntVar(&mSize, "msize", constants.DefaultMsize, "The number of bytes to use for 9p packet payload") mountCmd.Flags().IntVar(&mSize, "msize", constants.DefaultMsize, "The number of bytes to use for 9p packet payload")
} }
// getPort asks the kernel for a free open port that is ready to use
func getPort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
panic(err)
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return -1, errors.Errorf("Error accessing port %d", addr.Port)
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}

View File

@ -38,6 +38,7 @@ import (
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/notify" "k8s.io/minikube/pkg/minikube/notify"
"k8s.io/minikube/pkg/minikube/translate"
) )
var dirs = [...]string{ var dirs = [...]string{
@ -101,12 +102,57 @@ var RootCmd = &cobra.Command{
// Execute adds all child commands to the root command sets flags appropriately. // Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd. // This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() { func Execute() {
for _, c := range RootCmd.Commands() {
c.Short = translate.T(c.Short)
c.Long = translate.T(c.Long)
c.Flags().VisitAll(func(flag *pflag.Flag) {
flag.Usage = translate.T(flag.Usage)
})
c.SetUsageTemplate(usageTemplate())
}
RootCmd.Short = translate.T(RootCmd.Short)
RootCmd.Long = translate.T(RootCmd.Long)
RootCmd.Flags().VisitAll(func(flag *pflag.Flag) {
flag.Usage = translate.T(flag.Usage)
})
if err := RootCmd.Execute(); err != nil { if err := RootCmd.Execute(); err != nil {
// Cobra already outputs the error, typically because the user provided an unknown command. // Cobra already outputs the error, typically because the user provided an unknown command.
os.Exit(exit.BadUsage) os.Exit(exit.BadUsage)
} }
} }
// usageTemplate just calls translate.T on the default usage template
// explicitly using the raw string instead of calling c.UsageTemplate()
// so the extractor can find this monstrosity of a string
func usageTemplate() string {
return fmt.Sprintf(`%s:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
%s:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
%s:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
%s:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
%s:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
%s:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
%s:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
%s{{end}}
`, translate.T("Usage"), translate.T("Aliases"), translate.T("Examples"), translate.T("Available Commands"), translate.T("Flags"), translate.T("Global Flags"), translate.T("Additional help topics"), translate.T(`Use "{{.CommandPath}} [command] --help" for more information about a command.`))
}
// Handle config values for flags used in external packages (e.g. glog) // Handle config values for flags used in external packages (e.g. glog)
// by setting them directly, using values from viper when not passed in as args // by setting them directly, using values from viper when not passed in as args
func setFlagsUsingViper() { func setFlagsUsingViper() {
@ -127,12 +173,13 @@ func setFlagsUsingViper() {
} }
func init() { func init() {
translate.DetermineLocale()
RootCmd.PersistentFlags().StringP(config.MachineProfile, "p", constants.DefaultMachineName, `The name of the minikube VM being used. This can be set to allow having multiple instances of minikube independently.`) RootCmd.PersistentFlags().StringP(config.MachineProfile, "p", constants.DefaultMachineName, `The name of the minikube VM being used. This can be set to allow having multiple instances of minikube independently.`)
RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", constants.DefaultClusterBootstrapper, "The name of the cluster bootstrapper that will set up the kubernetes cluster.") RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", constants.DefaultClusterBootstrapper, "The name of the cluster bootstrapper that will set up the kubernetes cluster.")
groups := templates.CommandGroups{ groups := templates.CommandGroups{
{ {
Message: "Basic Commands:", Message: translate.T("Basic Commands:"),
Commands: []*cobra.Command{ Commands: []*cobra.Command{
startCmd, startCmd,
statusCmd, statusCmd,
@ -142,14 +189,14 @@ func init() {
}, },
}, },
{ {
Message: "Images Commands:", Message: translate.T("Images Commands:"),
Commands: []*cobra.Command{ Commands: []*cobra.Command{
dockerEnvCmd, dockerEnvCmd,
cacheCmd, cacheCmd,
}, },
}, },
{ {
Message: "Configuration and Management Commands:", Message: translate.T("Configuration and Management Commands:"),
Commands: []*cobra.Command{ Commands: []*cobra.Command{
configCmd.AddonsCmd, configCmd.AddonsCmd,
configCmd.ConfigCmd, configCmd.ConfigCmd,
@ -158,14 +205,14 @@ func init() {
}, },
}, },
{ {
Message: "Networking and Connectivity Commands:", Message: translate.T("Networking and Connectivity Commands:"),
Commands: []*cobra.Command{ Commands: []*cobra.Command{
serviceCmd, serviceCmd,
tunnelCmd, tunnelCmd,
}, },
}, },
{ {
Message: "Advanced Commands:", Message: translate.T("Advanced Commands:"),
Commands: []*cobra.Command{ Commands: []*cobra.Command{
mountCmd, mountCmd,
sshCmd, sshCmd,
@ -173,7 +220,7 @@ func init() {
}, },
}, },
{ {
Message: "Troubleshooting Commands:", Message: translate.T("Troubleshooting Commands:"),
Commands: []*cobra.Command{ Commands: []*cobra.Command{
sshKeyCmd, sshKeyCmd,
ipCmd, ipCmd,
@ -185,7 +232,7 @@ func init() {
} }
groups.Add(RootCmd) groups.Add(RootCmd)
// any not grouped command will show in Other Commands group. // Ungrouped commands will show up in the "Other Commands" section
RootCmd.AddCommand(completionCmd) RootCmd.AddCommand(completionCmd)
templates.ActsAsRootCommand(RootCmd, []string{"options"}, groups...) templates.ActsAsRootCommand(RootCmd, []string{"options"}, groups...)
@ -193,7 +240,6 @@ func init() {
if err := viper.BindPFlags(RootCmd.PersistentFlags()); err != nil { if err := viper.BindPFlags(RootCmd.PersistentFlags()); err != nil {
exit.WithError("Unable to bind flags", err) exit.WithError("Unable to bind flags", err)
} }
cobra.OnInitialize(initConfig) cobra.OnInitialize(initConfig)
} }

View File

@ -17,7 +17,6 @@ limitations under the License.
package cmd package cmd
import ( import (
"encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net" "net"
@ -32,8 +31,6 @@ import (
"strings" "strings"
"time" "time"
"k8s.io/minikube/pkg/minikube/drivers/none"
"github.com/blang/semver" "github.com/blang/semver"
"github.com/docker/machine/libmachine" "github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/host" "github.com/docker/machine/libmachine/host"
@ -46,7 +43,6 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config" cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
cmdutil "k8s.io/minikube/cmd/util"
"k8s.io/minikube/pkg/minikube/bootstrapper" "k8s.io/minikube/pkg/minikube/bootstrapper"
"k8s.io/minikube/pkg/minikube/bootstrapper/kubeadm" "k8s.io/minikube/pkg/minikube/bootstrapper/kubeadm"
"k8s.io/minikube/pkg/minikube/cluster" "k8s.io/minikube/pkg/minikube/cluster"
@ -54,7 +50,9 @@ import (
cfg "k8s.io/minikube/pkg/minikube/config" cfg "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/cruntime" "k8s.io/minikube/pkg/minikube/cruntime"
"k8s.io/minikube/pkg/minikube/drivers/none"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/logs" "k8s.io/minikube/pkg/minikube/logs"
"k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
@ -134,20 +132,21 @@ func initMinikubeFlags() {
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viper.AutomaticEnv() viper.AutomaticEnv()
startCmd.Flags().Int(cpus, constants.DefaultCPUS, "Number of CPUs allocated to the minikube VM") startCmd.Flags().Int(cpus, constants.DefaultCPUS, "Number of CPUs allocated to the minikube VM.")
startCmd.Flags().String(memory, constants.DefaultMemorySize, "Amount of RAM allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g)") startCmd.Flags().String(memory, constants.DefaultMemorySize, "Amount of RAM allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).")
startCmd.Flags().String(humanReadableDiskSize, constants.DefaultDiskSize, "Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g)") startCmd.Flags().String(humanReadableDiskSize, constants.DefaultDiskSize, "Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).")
startCmd.Flags().Bool(downloadOnly, false, "If true, only download and cache files for later use - don't install or start anything.") startCmd.Flags().Bool(downloadOnly, false, "If true, only download and cache files for later use - don't install or start anything.")
startCmd.Flags().Bool(cacheImages, true, "If true, cache docker images for the current bootstrapper and load them into the machine. Always false with --vm-driver=none.") startCmd.Flags().Bool(cacheImages, true, "If true, cache docker images for the current bootstrapper and load them into the machine. Always false with --vm-driver=none.")
startCmd.Flags().String(isoURL, constants.DefaultISOURL, "Location of the minikube iso") startCmd.Flags().String(isoURL, constants.DefaultISOURL, "Location of the minikube iso.")
startCmd.Flags().Bool(keepContext, constants.DefaultKeepContext, "This will keep the existing kubectl context and will create a minikube context.") startCmd.Flags().Bool(keepContext, constants.DefaultKeepContext, "This will keep the existing kubectl context and will create a minikube context.")
startCmd.Flags().String(containerRuntime, "docker", "The container runtime to be used (docker, crio, containerd)") startCmd.Flags().Bool(embedCerts, constants.DefaultEmbedCerts, "if true, will embed the certs in kubeconfig.")
startCmd.Flags().Bool(createMount, false, "This will start the mount daemon and automatically mount files into minikube") startCmd.Flags().String(containerRuntime, "docker", "The container runtime to be used (docker, crio, containerd).")
startCmd.Flags().String(mountString, constants.DefaultMountDir+":"+constants.DefaultMountEndpoint, "The argument to pass the minikube mount command on start") startCmd.Flags().Bool(createMount, false, "This will start the mount daemon and automatically mount files into minikube.")
startCmd.Flags().String(criSocket, "", "The cri socket path to be used") startCmd.Flags().String(mountString, constants.DefaultMountDir+":"+constants.DefaultMountEndpoint, "The argument to pass the minikube mount command on start.")
startCmd.Flags().String(networkPlugin, "", "The name of the network plugin") startCmd.Flags().String(criSocket, "", "The cri socket path to be used.")
startCmd.Flags().Bool(enableDefaultCNI, false, "Enable the default CNI plugin (/etc/cni/net.d/k8s.conf). Used in conjunction with \"--network-plugin=cni\"") startCmd.Flags().String(networkPlugin, "", "The name of the network plugin.")
startCmd.Flags().Bool(waitUntilHealthy, true, "Wait until Kubernetes core services are healthy before exiting") startCmd.Flags().Bool(enableDefaultCNI, false, "Enable the default CNI plugin (/etc/cni/net.d/k8s.conf). Used in conjunction with \"--network-plugin=cni\".")
startCmd.Flags().Bool(waitUntilHealthy, true, "Wait until Kubernetes core services are healthy before exiting.")
} }
// initKubernetesFlags inits the commandline flags for kubernetes related options // initKubernetesFlags inits the commandline flags for kubernetes related options
@ -160,7 +159,7 @@ func initKubernetesFlags() {
Valid kubeadm parameters: `+fmt.Sprintf("%s, %s", strings.Join(kubeadm.KubeadmExtraArgsWhitelist[kubeadm.KubeadmCmdParam], ", "), strings.Join(kubeadm.KubeadmExtraArgsWhitelist[kubeadm.KubeadmConfigParam], ","))) Valid kubeadm parameters: `+fmt.Sprintf("%s, %s", strings.Join(kubeadm.KubeadmExtraArgsWhitelist[kubeadm.KubeadmCmdParam], ", "), strings.Join(kubeadm.KubeadmExtraArgsWhitelist[kubeadm.KubeadmConfigParam], ",")))
startCmd.Flags().String(featureGates, "", "A set of key=value pairs that describe feature gates for alpha/experimental features.") startCmd.Flags().String(featureGates, "", "A set of key=value pairs that describe feature gates for alpha/experimental features.")
startCmd.Flags().String(dnsDomain, constants.ClusterDNSDomain, "The cluster dns domain name used in the kubernetes cluster") startCmd.Flags().String(dnsDomain, constants.ClusterDNSDomain, "The cluster dns domain name used in the kubernetes cluster")
startCmd.Flags().Int(apiServerPort, pkgutil.APIServerPort, "The apiserver listening port") startCmd.Flags().Int(apiServerPort, constants.APIServerPort, "The apiserver listening port")
startCmd.Flags().String(apiServerName, constants.APIServerName, "The apiserver name which is used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine") startCmd.Flags().String(apiServerName, constants.APIServerName, "The apiserver name which is used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine")
startCmd.Flags().StringArrayVar(&apiServerNames, "apiserver-names", nil, "A set of apiserver names which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine") startCmd.Flags().StringArrayVar(&apiServerNames, "apiserver-names", nil, "A set of apiserver names which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine")
startCmd.Flags().IPSliceVar(&apiServerIPs, "apiserver-ips", nil, "A set of apiserver IP Addresses which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine") startCmd.Flags().IPSliceVar(&apiServerIPs, "apiserver-ips", nil, "A set of apiserver IP Addresses which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine")
@ -169,6 +168,7 @@ func initKubernetesFlags() {
// initDriverFlags inits the commandline flags for vm drivers // initDriverFlags inits the commandline flags for vm drivers
func initDriverFlags() { func initDriverFlags() {
startCmd.Flags().String(vmDriver, constants.DefaultVMDriver, fmt.Sprintf("VM driver is one of: %v", constants.SupportedVMDrivers)) startCmd.Flags().String(vmDriver, constants.DefaultVMDriver, fmt.Sprintf("VM driver is one of: %v", constants.SupportedVMDrivers))
startCmd.Flags().Bool(disableDriverMounts, false, "Disables the filesystem mounts provided by the hypervisors")
// kvm2 // kvm2
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)")
@ -259,12 +259,11 @@ func runStart(cmd *cobra.Command, args []string) {
registryMirror = viper.GetStringSlice("registry_mirror") registryMirror = viper.GetStringSlice("registry_mirror")
} }
vmDriver := viper.GetString(vmDriver) if err := cmdcfg.IsValidDriver(runtime.GOOS, viper.GetString(vmDriver)); err != nil {
if err := cmdcfg.IsValidDriver(runtime.GOOS, vmDriver); err != nil {
exit.WithCodeT( exit.WithCodeT(
exit.Failure, exit.Failure,
"The driver '{{.driver}}' is not supported on {{.os}}", "The driver '{{.driver}}' is not supported on {{.os}}",
out.V{"driver": vmDriver, "os": runtime.GOOS}, out.V{"driver": viper.GetString(vmDriver), "os": runtime.GOOS},
) )
} }
@ -273,7 +272,7 @@ func runStart(cmd *cobra.Command, args []string) {
validateDriverVersion(viper.GetString(vmDriver)) validateDriverVersion(viper.GetString(vmDriver))
k8sVersion, isUpgrade := getKubernetesVersion() k8sVersion, isUpgrade := getKubernetesVersion()
config, err := generateConfig(cmd, k8sVersion) config, err := generateCfgFromFlags(cmd, k8sVersion)
if err != nil { if err != nil {
exit.WithError("Failed to generate config", err) exit.WithError("Failed to generate config", err)
} }
@ -305,8 +304,13 @@ func runStart(cmd *cobra.Command, args []string) {
// setup kube adm and certs and return bootstrapperx // setup kube adm and certs and return bootstrapperx
bs := setupKubeAdm(machineAPI, config.KubernetesConfig) bs := setupKubeAdm(machineAPI, config.KubernetesConfig)
// The kube config must be update must come before bootstrapping, otherwise health checks may use a stale IP // The kube config must be update must come before bootstrapping, otherwise health checks may use a stale IP
kubeconfig := updateKubeConfig(host, &config) kubeconfig, err := setupKubeconfig(host, &config)
if err != nil {
exit.WithError("Failed to setup kubeconfig", err)
}
// pull images or restart cluster // pull images or restart cluster
bootstrapCluster(bs, cr, mRunner, config.KubernetesConfig, preExists, isUpgrade) bootstrapCluster(bs, cr, mRunner, config.KubernetesConfig, preExists, isUpgrade)
configureMounts() configureMounts()
@ -324,6 +328,33 @@ func runStart(cmd *cobra.Command, args []string) {
} }
func setupKubeconfig(h *host.Host, c *cfg.Config) (*kubeconfig.Settings, error) {
addr, err := h.Driver.GetURL()
if err != nil {
exit.WithError("Failed to get driver URL", err)
}
addr = strings.Replace(addr, "tcp://", "https://", -1)
addr = strings.Replace(addr, ":2376", ":"+strconv.Itoa(c.KubernetesConfig.NodePort), -1)
if c.KubernetesConfig.APIServerName != constants.APIServerName {
addr = strings.Replace(addr, c.KubernetesConfig.NodeIP, c.KubernetesConfig.APIServerName, -1)
}
kcs := &kubeconfig.Settings{
ClusterName: cfg.GetMachineName(),
ClusterServerAddress: addr,
ClientCertificate: constants.MakeMiniPath("client.crt"),
ClientKey: constants.MakeMiniPath("client.key"),
CertificateAuthority: constants.MakeMiniPath("ca.crt"),
KeepContext: viper.GetBool(keepContext),
EmbedCerts: viper.GetBool(embedCerts),
}
kcs.SetPath(kubeconfig.PathFromEnv())
if err := kubeconfig.Update(kcs); err != nil {
return kcs, err
}
return kcs, nil
}
func handleDownloadOnly(cacheGroup *errgroup.Group, k8sVersion string) { func handleDownloadOnly(cacheGroup *errgroup.Group, k8sVersion string) {
// If --download-only, complete the remaining downloads and exit. // If --download-only, complete the remaining downloads and exit.
if !viper.GetBool(downloadOnly) { if !viper.GetBool(downloadOnly) {
@ -401,9 +432,9 @@ func showVersionInfo(k8sVersion string, cr cruntime.Manager) {
} }
} }
func showKubectlConnectInfo(kubeconfig *pkgutil.KubeConfigSetup) { func showKubectlConnectInfo(kcs *kubeconfig.Settings) {
if kubeconfig.KeepContext { if kcs.KeepContext {
out.T(out.Kubectl, "To connect to this cluster, use: kubectl --context={{.name}}", out.V{"name": kubeconfig.ClusterName}) out.T(out.Kubectl, "To connect to this cluster, use: kubectl --context={{.name}}", out.V{"name": kcs.ClusterName})
} else { } else {
out.T(out.Ready, `Done! kubectl is now configured to use "{{.name}}"`, out.V{"name": cfg.GetMachineName()}) out.T(out.Ready, `Done! kubectl is now configured to use "{{.name}}"`, out.V{"name": cfg.GetMachineName()})
} }
@ -487,7 +518,7 @@ func validateUser() {
func validateConfig() { func validateConfig() {
diskSizeMB := pkgutil.CalculateSizeInMB(viper.GetString(humanReadableDiskSize)) diskSizeMB := pkgutil.CalculateSizeInMB(viper.GetString(humanReadableDiskSize))
if diskSizeMB < pkgutil.CalculateSizeInMB(constants.MinimumDiskSize) { if diskSizeMB < pkgutil.CalculateSizeInMB(constants.MinimumDiskSize) {
exit.WithCodeT(exit.Config, "Requested disk size {{.size_in_mb}} is less than minimum of {{.size_in_mb2}}", out.V{"size_in_mb": diskSizeMB, "size_in_mb2": pkgutil.CalculateSizeInMB(constants.MinimumDiskSize)}) exit.WithCodeT(exit.Config, "Requested disk size {{.requested_size}} is less than minimum of {{.minimum_size}}", out.V{"requested_size": diskSizeMB, "minimum_size": pkgutil.CalculateSizeInMB(constants.MinimumDiskSize)})
} }
err := autoSetOptions(viper.GetString(vmDriver)) err := autoSetOptions(viper.GetString(vmDriver))
@ -497,7 +528,7 @@ func validateConfig() {
memorySizeMB := pkgutil.CalculateSizeInMB(viper.GetString(memory)) memorySizeMB := pkgutil.CalculateSizeInMB(viper.GetString(memory))
if memorySizeMB < pkgutil.CalculateSizeInMB(constants.MinimumMemorySize) { if memorySizeMB < pkgutil.CalculateSizeInMB(constants.MinimumMemorySize) {
exit.UsageT("Requested memory allocation {{.size_in_mb}} is less than the minimum allowed of {{.size_in_mb2}}", out.V{"size_in_mb": memorySizeMB, "size_in_mb2": pkgutil.CalculateSizeInMB(constants.MinimumMemorySize)}) exit.UsageT("Requested memory allocation {{.requested_size}} is less than the minimum allowed of {{.minimum_size}}", out.V{"requested_size": memorySizeMB, "minimum_size": pkgutil.CalculateSizeInMB(constants.MinimumMemorySize)})
} }
if memorySizeMB < pkgutil.CalculateSizeInMB(constants.DefaultMemorySize) { if memorySizeMB < pkgutil.CalculateSizeInMB(constants.DefaultMemorySize) {
out.T(out.Notice, "Requested memory allocation ({{.memory}}MB) is less than the default memory allocation of {{.default_memorysize}}MB. Beware that minikube might not work correctly or crash unexpectedly.", out.T(out.Notice, "Requested memory allocation ({{.memory}}MB) is less than the default memory allocation of {{.default_memorysize}}MB. Beware that minikube might not work correctly or crash unexpectedly.",
@ -559,8 +590,8 @@ func waitCacheImages(g *errgroup.Group) {
} }
} }
// generateConfig generates cfg.Config based on flags and supplied arguments // generateCfgFromFlags generates cfg.Config based on flags and supplied arguments
func generateConfig(cmd *cobra.Command, k8sVersion string) (cfg.Config, error) { func generateCfgFromFlags(cmd *cobra.Command, k8sVersion string) (cfg.Config, error) {
r, err := cruntime.New(cruntime.Config{Type: viper.GetString(containerRuntime)}) r, err := cruntime.New(cruntime.Config{Type: viper.GetString(containerRuntime)})
if err != nil { if err != nil {
return cfg.Config{}, err return cfg.Config{}, err
@ -616,6 +647,7 @@ func generateConfig(cmd *cobra.Command, k8sVersion string) (cfg.Config, error) {
cfg := cfg.Config{ cfg := cfg.Config{
MachineConfig: cfg.MachineConfig{ MachineConfig: cfg.MachineConfig{
KeepContext: viper.GetBool(keepContext), KeepContext: viper.GetBool(keepContext),
EmbedCerts: viper.GetBool(embedCerts),
MinikubeISO: viper.GetString(isoURL), MinikubeISO: viper.GetString(isoURL),
Memory: pkgutil.CalculateSizeInMB(viper.GetString(memory)), Memory: pkgutil.CalculateSizeInMB(viper.GetString(memory)),
CPUs: viper.GetInt(cpus), CPUs: viper.GetInt(cpus),
@ -686,7 +718,7 @@ func prepareNone(vmDriver string) {
out.T(out.Empty, "") out.T(out.Empty, "")
out.WarningT("The 'none' driver provides limited isolation and may reduce system security and reliability.") out.WarningT("The 'none' driver provides limited isolation and may reduce system security and reliability.")
out.WarningT("For more information, see:") out.WarningT("For more information, see:")
out.T(out.URL, "https://github.com/kubernetes/minikube/blob/master/docs/vmdriver-none.md") out.T(out.URL, "https://minikube.sigs.k8s.io/docs/reference/drivers/none/")
out.T(out.Empty, "") out.T(out.Empty, "")
} }
@ -749,7 +781,7 @@ func validateNetwork(h *host.Host) string {
ipExcluded := proxy.IsIPExcluded(ip) // Skip warning if minikube ip is already in NO_PROXY ipExcluded := proxy.IsIPExcluded(ip) // Skip warning if minikube ip is already in NO_PROXY
k = strings.ToUpper(k) // for http_proxy & https_proxy k = strings.ToUpper(k) // for http_proxy & https_proxy
if (k == "HTTP_PROXY" || k == "HTTPS_PROXY") && !ipExcluded && !warnedOnce { if (k == "HTTP_PROXY" || k == "HTTPS_PROXY") && !ipExcluded && !warnedOnce {
out.WarningT("You appear to be using a proxy, but your NO_PROXY environment does not include the minikube IP ({{.ip_address}}). Please see https://github.com/kubernetes/minikube/blob/master/docs/http_proxy.md for more details", out.V{"ip_address": ip}) out.WarningT("You appear to be using a proxy, but your NO_PROXY environment does not include the minikube IP ({{.ip_address}}). Please see https://minikube.sigs.k8s.io/docs/reference/networking/proxy/ for more details", out.V{"ip_address": ip})
warnedOnce = true warnedOnce = true
} }
} }
@ -769,7 +801,7 @@ func validateKubernetesVersions(old *cfg.Config) (string, bool) {
nvs, err := semver.Make(strings.TrimPrefix(rawVersion, version.VersionPrefix)) nvs, err := semver.Make(strings.TrimPrefix(rawVersion, version.VersionPrefix))
if err != nil { if err != nil {
exit.WithCodeT(exit.Data, `Unable to parse "{{.kubenretes_version}}": {{.error}}`, out.V{"kubenretes_version": rawVersion, "error": err}) exit.WithCodeT(exit.Data, `Unable to parse "{{.kubernetes_version}}": {{.error}}`, out.V{"kubernetes_version": rawVersion, "error": err})
} }
nv := version.VersionPrefix + nvs.String() nv := version.VersionPrefix + nvs.String()
@ -813,34 +845,6 @@ func setupKubeAdm(mAPI libmachine.API, kc cfg.KubernetesConfig) bootstrapper.Boo
return bs return bs
} }
// updateKubeConfig sets up kubectl
func updateKubeConfig(h *host.Host, c *cfg.Config) *pkgutil.KubeConfigSetup {
addr, err := h.Driver.GetURL()
if err != nil {
exit.WithError("Failed to get driver URL", err)
}
addr = strings.Replace(addr, "tcp://", "https://", -1)
addr = strings.Replace(addr, ":2376", ":"+strconv.Itoa(c.KubernetesConfig.NodePort), -1)
if c.KubernetesConfig.APIServerName != constants.APIServerName {
addr = strings.Replace(addr, c.KubernetesConfig.NodeIP, c.KubernetesConfig.APIServerName, -1)
}
kcs := &pkgutil.KubeConfigSetup{
ClusterName: cfg.GetMachineName(),
ClusterServerAddress: addr,
ClientCertificate: constants.MakeMiniPath("client.crt"),
ClientKey: constants.MakeMiniPath("client.key"),
CertificateAuthority: constants.MakeMiniPath("ca.crt"),
KeepContext: viper.GetBool(keepContext),
EmbedCerts: viper.GetBool(embedCerts),
}
kcs.SetKubeConfigFile(cmdutil.GetKubeConfigPath())
if err := pkgutil.SetupKubeConfig(kcs); err != nil {
exit.WithError("Failed to setup kubeconfig", err)
}
return kcs
}
// configureRuntimes does what needs to happen to get a runtime going. // configureRuntimes does what needs to happen to get a runtime going.
func configureRuntimes(runner cruntime.CommandRunner) cruntime.Manager { func configureRuntimes(runner cruntime.CommandRunner) cruntime.Manager {
config := cruntime.Config{Type: viper.GetString(containerRuntime), Runner: runner} config := cruntime.Config{Type: viper.GetString(containerRuntime), Runner: runner}
@ -914,47 +918,8 @@ func configureMounts() {
} }
// saveConfig saves profile cluster configuration in $MINIKUBE_HOME/profiles/<profilename>/config.json // saveConfig saves profile cluster configuration in $MINIKUBE_HOME/profiles/<profilename>/config.json
func saveConfig(clusterConfig *cfg.Config) error { func saveConfig(clusterCfg *cfg.Config) error {
data, err := json.MarshalIndent(clusterConfig, "", " ") return cfg.CreateProfile(viper.GetString(cfg.MachineProfile), clusterCfg)
if err != nil {
return err
}
glog.Infof("Saving config:\n%s", data)
path := constants.GetProfileFile(viper.GetString(cfg.MachineProfile))
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
// If no config file exists, don't worry about swapping paths
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := ioutil.WriteFile(path, data, 0600); err != nil {
return err
}
return nil
}
tf, err := ioutil.TempFile(filepath.Dir(path), "config.json.tmp")
if err != nil {
return err
}
defer os.Remove(tf.Name())
if err = ioutil.WriteFile(tf.Name(), data, 0600); err != nil {
return err
}
if err = tf.Close(); err != nil {
return err
}
if err = os.Remove(path); err != nil {
return err
}
if err = os.Rename(tf.Name(), path); err != nil {
return err
}
return nil
} }
func validateDriverVersion(vmDriver string) { func validateDriverVersion(vmDriver string) {
@ -1003,7 +968,7 @@ func validateDriverVersion(vmDriver string) {
minikubeVersion, err := version.GetSemverVersion() minikubeVersion, err := version.GetSemverVersion()
if err != nil { if err != nil {
out.WarningT("Error parsing minukube version: {{.error}}", out.V{"error": err}) out.WarningT("Error parsing minikube version: {{.error}}", out.V{"error": err})
return return
} }

View File

@ -25,14 +25,13 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config" cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
"k8s.io/minikube/cmd/util"
"k8s.io/minikube/pkg/minikube/cluster" "k8s.io/minikube/pkg/minikube/cluster"
"k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
pkgutil "k8s.io/minikube/pkg/util"
) )
var statusFormat string var statusFormat string
@ -93,10 +92,10 @@ var statusCmd = &cobra.Command{
glog.Errorln("Error host driver ip status:", err) glog.Errorln("Error host driver ip status:", err)
} }
apiserverPort, err := pkgutil.GetPortFromKubeConfig(util.GetKubeConfigPath(), config.GetMachineName()) apiserverPort, err := kubeconfig.Port(config.GetMachineName())
if err != nil { if err != nil {
// Fallback to presuming default apiserver port // Fallback to presuming default apiserver port
apiserverPort = pkgutil.APIServerPort apiserverPort = constants.APIServerPort
} }
apiserverSt, err = clusterBootstrapper.GetAPIServerStatus(ip, apiserverPort) apiserverSt, err = clusterBootstrapper.GetAPIServerStatus(ip, apiserverPort)
@ -106,7 +105,7 @@ var statusCmd = &cobra.Command{
returnCode |= clusterNotRunningStatusFlag returnCode |= clusterNotRunningStatusFlag
} }
ks, err := pkgutil.GetKubeConfigStatus(ip, util.GetKubeConfigPath(), config.GetMachineName()) ks, err := kubeconfig.IsClusterInConfig(ip, config.GetMachineName())
if err != nil { if err != nil {
glog.Errorln("Error kubeconfig status:", err) glog.Errorln("Error kubeconfig status:", err)
} }

View File

@ -23,11 +23,11 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
cmdUtil "k8s.io/minikube/cmd/util"
"k8s.io/minikube/pkg/minikube/cluster" "k8s.io/minikube/pkg/minikube/cluster"
pkg_config "k8s.io/minikube/pkg/minikube/config" pkg_config "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
pkgutil "k8s.io/minikube/pkg/util" pkgutil "k8s.io/minikube/pkg/util"
@ -71,12 +71,12 @@ func runStop(cmd *cobra.Command, args []string) {
out.T(out.Stopped, `"{{.profile_name}}" stopped.`, out.V{"profile_name": profile}) out.T(out.Stopped, `"{{.profile_name}}" stopped.`, out.V{"profile_name": profile})
} }
if err := cmdUtil.KillMountProcess(); err != nil { if err := killMountProcess(); err != nil {
out.T(out.WarningType, "Unable to kill mount process: {{.error}}", out.V{"error": err}) out.T(out.WarningType, "Unable to kill mount process: {{.error}}", out.V{"error": err})
} }
machineName := pkg_config.GetMachineName() machineName := pkg_config.GetMachineName()
err = pkgutil.UnsetCurrentContext(constants.KubeconfigPath, machineName) err = kubeconfig.UnsetCurrentContext(constants.KubeconfigPath, machineName)
if err != nil { if err != nil {
exit.WithError("update config", err) exit.WithError("update config", err)
} }

View File

@ -22,9 +22,9 @@ import (
"k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/util"
) )
// updateContextCmd represents the update-context command // updateContextCmd represents the update-context command
@ -44,7 +44,7 @@ var updateContextCmd = &cobra.Command{
if err != nil { if err != nil {
exit.WithError("Error host driver ip status", err) exit.WithError("Error host driver ip status", err)
} }
updated, err := util.UpdateKubeconfigIP(ip, constants.KubeconfigPath, machineName) updated, err := kubeconfig.UpdateIP(ip, constants.KubeconfigPath, machineName)
if err != nil { if err != nil {
exit.WithError("update config", err) exit.WithError("update config", err)
} }

View File

@ -33,7 +33,6 @@ import (
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/machine" "k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out" "k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/minikube/translate"
_ "k8s.io/minikube/pkg/provision" _ "k8s.io/minikube/pkg/provision"
) )
@ -51,7 +50,6 @@ func main() {
} }
out.SetOutFile(os.Stdout) out.SetOutFile(os.Stdout)
out.SetErrFile(os.Stderr) out.SetErrFile(os.Stderr)
translate.DetermineLocale()
cmd.Execute() cmd.Execute()
} }

View File

@ -1,104 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package util is a hodge-podge of utility functions that should be moved elsewhere.
package util
import (
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strconv"
"github.com/golang/glog"
ps "github.com/mitchellh/go-ps"
"github.com/pkg/errors"
"k8s.io/minikube/pkg/minikube/constants"
)
// GetPort asks the kernel for a free open port that is ready to use
func GetPort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
panic(err)
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return -1, errors.Errorf("Error accessing port %d", addr.Port)
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
// KillMountProcess kills the mount process, if it is running
func KillMountProcess() error {
pidPath := filepath.Join(constants.GetMinipath(), constants.MountProcessFileName)
if _, err := os.Stat(pidPath); os.IsNotExist(err) {
return nil
}
glog.Infof("Found %s ...", pidPath)
out, err := ioutil.ReadFile(pidPath)
if err != nil {
return errors.Wrap(err, "ReadFile")
}
glog.Infof("pidfile contents: %s", out)
pid, err := strconv.Atoi(string(out))
if err != nil {
return errors.Wrap(err, "error parsing pid")
}
// os.FindProcess does not check if pid is running :(
entry, err := ps.FindProcess(pid)
if err != nil {
return errors.Wrap(err, "ps.FindProcess")
}
if entry == nil {
glog.Infof("Stale pid: %d", pid)
if err := os.Remove(pidPath); err != nil {
return errors.Wrap(err, "Removing stale pid")
}
return nil
}
// We found a process, but it still may not be ours.
glog.Infof("Found process %d: %s", pid, entry.Executable())
proc, err := os.FindProcess(pid)
if err != nil {
return errors.Wrap(err, "os.FindProcess")
}
glog.Infof("Killing pid %d ...", pid)
if err := proc.Kill(); err != nil {
glog.Infof("Kill failed with %v - removing probably stale pid...", err)
if err := os.Remove(pidPath); err != nil {
return errors.Wrap(err, "Removing likely stale unkillable pid")
}
return errors.Wrap(err, fmt.Sprintf("Kill(%d/%s)", pid, entry.Executable()))
}
return nil
}
// GetKubeConfigPath gets the path to the first kubeconfig
func GetKubeConfigPath() string {
kubeConfigEnv := os.Getenv(constants.KubeconfigEnvVar)
if kubeConfigEnv == "" {
return constants.KubeconfigPath
}
return filepath.SplitList(kubeConfigEnv)[0]
}

View File

@ -1,47 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"os"
"testing"
"k8s.io/client-go/tools/clientcmd"
)
func TestGetKubeConfigPath(t *testing.T) {
var tests = []struct {
input string
want string
}{
{
input: "/home/fake/.kube/.kubeconfig",
want: "/home/fake/.kube/.kubeconfig",
},
{
input: "/home/fake/.kube/.kubeconfig:/home/fake2/.kubeconfig",
want: "/home/fake/.kube/.kubeconfig",
},
}
for _, test := range tests {
os.Setenv(clientcmd.RecommendedConfigPathEnvVar, test.input)
if result := GetKubeConfigPath(); result != test.want {
t.Errorf("Expected first splitted chunk, got: %s", result)
}
}
}

View File

@ -59,4 +59,4 @@ BR2_TARGET_ROOTFS_ISO9660=y
BR2_TARGET_ROOTFS_ISO9660_BOOT_MENU="$(BR2_EXTERNAL_MINIKUBE_PATH)/board/coreos/minikube/isolinux.cfg" BR2_TARGET_ROOTFS_ISO9660_BOOT_MENU="$(BR2_EXTERNAL_MINIKUBE_PATH)/board/coreos/minikube/isolinux.cfg"
BR2_TARGET_SYSLINUX=y BR2_TARGET_SYSLINUX=y
BR2_PACKAGE_HOST_E2TOOLS=y BR2_PACKAGE_HOST_E2TOOLS=y
BR2_PACKAGE_SYSTEMD_TIMESYNCD=n BR2_PACKAGE_SYSTEMD_TIMESYNCD=y

View File

@ -1,4 +1,12 @@
[ [
{
"name": "v1.3.1",
"checksums": {
"darwin": "5947abe57fa390fcfd96849ac87fc9319f026d4b13f944b6beecc3615e3668be",
"linux": "057a4f4ca36ff51ecad59509d94d3694543b874949e805e2b79792ceef21f983",
"windows": "be1999452b166de72f946aac17ca7c40d53b8a5c8f59dad912c2413f7cc42563"
}
},
{ {
"name": "v1.3.0", "name": "v1.3.0",
"checksums": { "checksums": {

View File

@ -1,11 +1 @@
# Accessing Host Resources From Inside A Pod This document has moved to https://minikube.sigs.k8s.io/docs/tasks/accessing-host-resources/
## When you have a VirtualBox driver
In order to access host resources from inside a pod, run the following command to determine the host IP you can use:
```shell
ip addr
```
The IP address under `vboxnet1` is the IP that you need to access the host from within a pod.

View File

@ -1,50 +1 @@
# Add-ons This document has moved to https://minikube.sigs.k8s.io/docs/tasks/addons/
Minikube has a set of built in addons that can be used enabled, disabled, and opened inside of the local k8s environment. Below is an example of this functionality for the `heapster` addon:
```shell
$ minikube addons list
- registry: disabled
- registry-creds: disabled
- freshpod: disabled
- addon-manager: enabled
- dashboard: enabled
- heapster: disabled
- efk: disabled
- ingress: disabled
- default-storageclass: enabled
- storage-provisioner: enabled
- storage-provisioner-gluster: disabled
- nvidia-driver-installer: disabled
- nvidia-gpu-device-plugin: disabled
# minikube must be running for these commands to take effect
$ minikube addons enable heapster
heapster was successfully enabled
$ minikube addons open heapster # This will open grafana (interacting w/ heapster) in the browser
Waiting, endpoint for service is not ready yet...
Waiting, endpoint for service is not ready yet...
Created new window in existing browser session.
```
The currently supported addons include:
* [Kubernetes Dashboard](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/dashboard)
* [Heapster](https://github.com/kubernetes/heapster): [Troubleshooting Guide](https://github.com/kubernetes/heapster/blob/master/docs/influxdb.md) Note:You will need to login to Grafana as admin/admin in order to access the console
* [EFK](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/fluentd-elasticsearch)
* [Registry](https://github.com/kubernetes/minikube/tree/master/deploy/addons/registry)
* [Registry Credentials](https://github.com/upmc-enterprises/registry-creds)
* [Ingress](https://github.com/kubernetes/ingress-nginx)
* [Freshpod](https://github.com/GoogleCloudPlatform/freshpod)
* [nvidia-driver-installer](https://github.com/GoogleCloudPlatform/container-engine-accelerators/tree/master/nvidia-driver-installer/minikube)
* [nvidia-gpu-device-plugin](https://github.com/GoogleCloudPlatform/container-engine-accelerators/tree/master/cmd/nvidia_gpu)
* [logviewer](https://github.com/ivans3/minikube-log-viewer)
* [gvisor](../deploy/addons/gvisor/README.md)
* [storage-provisioner-gluster](../deploy/addons/storage-provisioner-gluster/README.md)
If you would like to have minikube properly start/restart custom addons, place the addon(s) you wish to be launched with minikube in the `.minikube/addons` directory. Addons in this folder will be moved to the minikube VM and launched each time minikube is started/restarted.
If you have a request for an addon in minikube, please open an issue with the name and preferably a link to the addon with a description of its purpose and why it should be added. You can also attempt to add the addon to minikube by following the guide at [Adding an Addon](contributors/adding_an_addon.md)
**Note:** If you want to have a look at the default configuration for the addons, see [deploy/addons](https://github.com/kubernetes/minikube/tree/master/deploy/addons).

View File

@ -1,41 +1 @@
# Alternative runtimes This document has moved to https://minikube.sigs.k8s.io/docs/reference/runtimes/
## Using CRI-O
To use [CRI-O](https://github.com/kubernetes-sigs/cri-o) as the container runtime, run:
```shell
$ minikube start --container-runtime=cri-o
```
Or you can use the extended version:
```shell
$ minikube start --container-runtime=cri-o \
--network-plugin=cni \
--enable-default-cni \
--cri-socket=/var/run/crio/crio.sock \
--extra-config=kubelet.container-runtime=remote \
--extra-config=kubelet.container-runtime-endpoint=unix:///var/run/crio/crio.sock \
--extra-config=kubelet.image-service-endpoint=unix:///var/run/crio/crio.sock
```
## Using containerd
To use [containerd](https://github.com/containerd/containerd) as the container runtime, run:
```shell
$ minikube start --container-runtime=containerd
```
Or you can use the extended version:
```shell
$ minikube start --container-runtime=containerd \
--network-plugin=cni \
--enable-default-cni \
--cri-socket=/run/containerd/containerd.sock \
--extra-config=kubelet.container-runtime=remote \
--extra-config=kubelet.container-runtime-endpoint=unix:///run/containerd/containerd.sock \
--extra-config=kubelet.image-service-endpoint=unix:///run/containerd/containerd.sock
```

View File

@ -1,31 +1 @@
# Building images within the VM This document has moved to https://minikube.sigs.k8s.io/docs/tasks/building_within/
When using a single VM of Kubernetes it's really handy to build inside the VM; as this means you don't have to build on your host machine and push the image into a docker registry - you can just build inside the same machine as minikube which speeds up local experiments.
## Docker (containerd)
For Docker, you can either set up your host docker client to communicate by [reusing the docker daemon](reusing_the_docker_daemon.md).
Or you can use `minikube ssh` to connect to the virtual machine, and run the `docker build` there:
```shell
docker build
```
For more information on the `docker build` command, read the [Docker documentation](https://docs.docker.com/engine/reference/commandline/build/) (docker.com).
## Podman (cri-o)
For Podman, there is no daemon running. The processes are started by the user, monitored by `conmon`.
So you need to use `minikube ssh`, and you will also make sure to run the command as the root user:
```shell
sudo -E podman build
```
For more information on the `podman build` command, read the [Podman documentation](https://github.com/containers/libpod/blob/master/docs/podman-build.1.md) (podman.io).
## Build context
For the build context you can use any directory on the virtual machine, or any address on the network.

View File

@ -1,20 +1 @@
# Caching Images This document has moved to https://minikube.sigs.k8s.io/docs/tasks/caching
Minikube supports caching non-minikube images using the `minikube cache` command. Images can be added to the cache by running `minikube cache add <img>`, and deleted by running `minikube cache delete <img>`.
Images in the cache will be loaded on `minikube start`. If you want to list all available cached images, you can use `minikube cache list` command to list. Below is an example of this functionality:
```shell
# cache a image into $HOME/.minikube/cache/images
$ minikube cache add ubuntu:16.04
$ minikube cache add redis:3
# list cached images
$ minikube cache list
redis:3
ubuntu:16.04
# delete cached images
$ minikube cache delete ubuntu:16.04
$ minikube cache delete $(minikube cache list)
```

View File

@ -1,340 +1 @@
# minikube CLI Commands This document has moved to https://minikube.sigs.k8s.io/docs/reference/commands/
This document serves as a reference to all the commands, flags and their accepted arguments
## Global Flags
These flags can be used globally with any command on the CLI. Following are the global flags -
```
--alsologtostderr log to standard error as well as files
-b, --bootstrapper string The name of the cluster bootstrapper that will set up the kubernetes cluster. (default "kubeadm")
-h, --help help for minikube
--log_backtrace_at traceLocation when logging hits line file:N, emit a stack trace (default :0)
--log_dir string If non-empty, write log files in this directory
--logtostderr log to standard error instead of files
-p, --profile string The name of the minikube VM being used.
This can be modified to allow for multiple minikube instances to be run independently (default "minikube")
--stderrthreshold severity logs at or above this threshold go to stderr (default 2)
-v, --v Level log level for V logs
--vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging
```
## Commands
In this section, all commands which are accepted by the `minikube` CLI are described. To get help about any command, you can also type in `minikube help <command>`
---
### addons
**Description -** Modifies minikube addons files using subcommands like `minikube addons enable heapster`
**Usage -**
```
minikube addons SUBCOMMAND [flags]
minikube addons [command]
```
**Available Subcommands -**
```
configure Configures the addon w/ADDON_NAME within minikube (example: minikube addons configure registry-creds). For a list of available addons use: minikube addons list
disable Disables the addon w/ADDON_NAME within minikube (example: minikube addons disable dashboard). For a list of available addons use: minikube addons list
enable Enables the addon w/ADDON_NAME within minikube (example: minikube addons enable dashboard). For a list of available addons use: minikube addons list
list Lists all available minikube addons as well as their current statuses (enabled/disabled)
open Opens the addon w/ADDON_NAME within minikube (example: minikube addons open dashboard). For a list of available addons use: minikube addons list
```
---
### cache
**Description -** Add or delete an image from the local cache.
**Usage -** `minikube cache [command]`
**Available Subcommands-**
```
add Add an image to local cache.
delete Delete an image from the local cache.
list List all available images from the local cache.
```
---
### completion
**Description -**
> Outputs minikube shell completion for the given shell (bash or zsh)
>
> This depends on the bash-completion binary. Example installation instructions:
> OS X:
> $ brew install bash-completion
> $ source $(brew --prefix)/etc/bash_completion
> $ minikube completion bash > ~/.minikube-completion # for bash users
> $ minikube completion zsh > ~/.minikube-completion # for zsh users
> $ source ~/.minikube-completion
> Ubuntu:
> $ apt-get install bash-completion
> $ source /etc/bash-completion
> $ source <(minikube completion bash) # for bash users
> $ source <(minikube completion zsh) # for zsh users
>
> Additionally, you may want to output the completion to a file and source in your .bashrc
>
> Note for zsh users: [1] zsh completions are only supported in versions of zsh >= 5.2
**Usage -** `minikube completion SHELL`
---
### config
**Description -** config modifies minikube config files using subcommands like `minikube config set vm-driver kvm`
Configurable fields:
* vm-driver
* feature-gates
* v
* cpus
* disk-size
* host-only-cidr
* memory
* log_dir
* kubernetes-version
* iso-url
* WantUpdateNotification
* ReminderWaitPeriodInHours
* WantReportError
* WantReportErrorPrompt
* WantKubectlDownloadMsg
* WantNoneDriverWarning
* profile
* bootstrapper
* ShowDriverDeprecationNotification
* ShowBootstrapperDeprecationNotification
* dashboard
* addon-manager
* default-storageclass
* heapster
* efk
* ingress
* registry
* registry-creds
* freshpod
* default-storageclass
* storage-provisioner
* storage-provisioner-gluster
* metrics-server
* nvidia-driver-installer
* nvidia-gpu-device-plugin
* logviewer
* gvisor
* hyperv-virtual-switch
* disable-driver-mounts
* cache
* embed-certs
**Usage -**
```
minikube config SUBCOMMAND [flags]
minikube config [command]
```
**Available Subcommands-**
```
get Gets the value of PROPERTY_NAME from the minikube config file
set Sets an individual value in a minikube config file
unset unsets an individual value in a minikube config file
view Display values currently set in the minikube config file
```
---
### dashboard
**Description -** Access the kubernetes dashboard running within the minikube cluster
**Usage -** `minikube dashboard [flags]`
**Available Flags -**
```
-h, --help help for dashboard
--url Display dashboard URL instead of opening a browser
```
---
### delete
**Description -** Deletes a local kubernetes cluster. This command deletes the VM, and removes all
associated files.
**Usage -** `minikube delete`
---
### docker-env
**Description -** Sets up docker env variables; similar to '$(docker-machine env)'.
**Usage -** `minikube docker-env [flags]`
**Available Flags -**
```
-h, --help help for docker-env
--no-proxy Add machine IP to NO_PROXY environment variable
--shell string Force environment to be configured for a specified shell: [fish, cmd, powershell, tcsh, bash, zsh], default is auto-detect
-u, --unset Unset variables instead of setting them
```
---
### help
**Description -** Help provides help for any command in the application. Simply type minikube help [path to command] for full details.
**Usage -** `minikube help [command] [flags]`
---
### ip
**Description -** Retrieves the IP address of the running cluster, and writes it to STDOUT.
**Usage -** `minikube ip`
---
### kubectl
**Description -** Run the kubernetes client, download it if necessary.
**Usage -** `minikube kubectl`
---
### logs
**Description -** Gets the logs of the running instance, used for debugging minikube, not user code.
**Usage -** `minikube logs [flags]`
**Available Flags -**
```
-f, --follow Show only the most recent journal entries, and continuously print new entries as they are appended to the journal.
-h, --help help for logs
-n, --length int Number of lines back to go within the log (default 50)
--problems Show only log entries which point to known problems
```
---
### mount
**Description -** Mounts the specified directory into minikube.
**Usage -** `minikube mount [flags] <source directory>:<target directory>`
**Available Flags -**
```
--9p-version string Specify the 9p version that the mount should use (default "9p2000.L")
--gid string Default group id used for the mount (default "docker")
-h, --help help for mount
--ip string Specify the ip that the mount should be setup on
--kill Kill the mount process spawned by minikube start
--mode uint File permissions used for the mount (default 493)
--msize int The number of bytes to use for 9p packet payload (default 262144)
--options strings Additional mount options, such as cache=fscache
--type string Specify the mount filesystem type (supported types: 9p) (default "9p")
--uid string Default user id used for the mount (default "docker")
```
---
### profile
**Description -** Sets the current minikube profile, or gets the current profile if no arguments are provided. This is used to run and manage multiple minikube instance. You can return to the default minikube profile by running `minikube profile default`
**Usage -**
```
minikube profile [MINIKUBE_PROFILE_NAME]. You can return to the default minikube profile by running `minikube profile default` [flags]
```
---
### service
**Description -** Gets the kubernetes URL(s) for the specified service in your local cluster. In the case of multiple URLs they will be printed one at a time.
**Usage -**
```
minikube service [flags] SERVICE
minikube service [command]
```
**Available Commands -**
```
list Lists the URLs for the services in your local cluster
```
**Available Flags -**
```
--format string Format to output service URL in. This format will be applied to each url individually and they will be printed one at a time. (default "http://{{.IP}}:{{.Port}}")
-h, --help help for service
--https Open the service URL with https instead of http
--interval int The time interval for each check that wait performs in seconds (default 20)
-n, --namespace string The service namespace (default "default")
--url Display the kubernetes service URL in the CLI instead of opening it in the default browser
--wait int Amount of time to wait for a service in seconds (default 20)
```
---
### ssh
**Description -** Log into or run a command on a machine with SSH; similar to 'docker-machine ssh'.
**Usage -** `minikube ssh`
---
### ssh-key
**Description -** Retrieve the ssh identity key path of the specified cluster.
**Usage -** `minikube ssh-key`
---
### start
**Description -** Starts a local kubernetes cluster.
**Usage -** `minikube start [flags]`
**Available Flags -**
```
--apiserver-ips ipSlice A set of apiserver IP Addresses which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine (default [])
--apiserver-name string The apiserver name which is used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine (default "minikubeCA")
--apiserver-names stringArray A set of apiserver names which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine
--apiserver-port int The apiserver listening port (default 8443)
--cache-images If true, cache docker images for the current bootstrapper and load them into the machine. Always false with --vm-driver=none. (default true)
--container-runtime string The container runtime to be used (docker, crio, containerd) (default "docker")
--cpus int Number of CPUs allocated to the minikube VM (default 2)
--cri-socket string The cri socket path to be used
--disable-driver-mounts Disables the filesystem mounts provided by the hypervisors (vboxfs)
--disk-size string Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g) (default "20000mb")
--dns-domain string The cluster dns domain name used in the kubernetes cluster (default "cluster.local")
--docker-env stringArray Environment variables to pass to the Docker daemon. (format: key=value)
--docker-opt stringArray Specify arbitrary flags to pass to the Docker daemon. (format: key=value)
--download-only If true, only download and cache files for later use - don't install or start anything.
--enable-default-cni Enable the default CNI plugin (/etc/cni/net.d/k8s.conf). Used in conjunction with "--network-plugin=cni"
--extra-config ExtraOption A set of key=value pairs that describe configuration that may be passed to different components.
The key should be '.' separated, and the first part before the dot is the component to apply the configuration to.
Valid components are: kubelet, kubeadm, apiserver, controller-manager, etcd, proxy, scheduler
Valid kubeadm parameters: ignore-preflight-errors, dry-run, kubeconfig, kubeconfig-dir, node-name, cri-socket, experimental-upload-certs, certificate-key, rootfs, pod-network-cidr
--feature-gates string A set of key=value pairs that describe feature gates for alpha/experimental features.
--gpu Enable experimental NVIDIA GPU support in minikube (works only with kvm2 driver on Linux)
-h, --help help for start
--hidden Hide the hypervisor signature from the guest in minikube (works only with kvm2 driver on Linux)
--host-only-cidr string The CIDR to be used for the minikube VM (only supported with Virtualbox driver) (default "192.168.99.1/24")
--hyperkit-vpnkit-sock string Location of the VPNKit socket used for networking. If empty, disables Hyperkit VPNKitSock, if 'auto' uses Docker for Mac VPNKit connection, otherwise uses the specified VSock.
--hyperkit-vsock-ports strings List of guest VSock ports that should be exposed as sockets on the host (Only supported on with hyperkit now).
--hyperv-virtual-switch string The hyperv virtual switch name. Defaults to first found. (only supported with HyperV driver)
--image-mirror-country string Country code of the image mirror to be used. Leave empty to use the global one. For Chinese mainland users, set it to cn
--image-repository string Alternative image repository to pull docker images from. This can be used when you have limited access to gcr.io. Set it to "auto" to let minikube decide one for you. For Chinese mainland users, you may use local gcr.io mirrors such as registry.cn-hangzhou.aliyuncs.com/google_containers
--insecure-registry strings Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.
--iso-url string Location of the minikube iso (default "https://storage.googleapis.com/minikube/iso/minikube-v1.2.0.iso")
--keep-context This will keep the existing kubectl context and will create a minikube context.
--kubernetes-version string The kubernetes version that the minikube VM will use (ex: v1.2.3) (default "v1.15.0")
--kvm-network string The KVM network name. (only supported with KVM driver) (default "default")
--memory string Amount of RAM allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g) (default "2000mb")
--mount This will start the mount daemon and automatically mount files into minikube
--mount-string string The argument to pass the minikube mount command on start (default "C:\\Users\\Pranav.Jituri:/minikube-host")
--network-plugin string The name of the network plugin
--nfs-share strings Local folders to share with Guest via NFS mounts (Only supported on with hyperkit now)
--nfs-shares-root string Where to root the NFS Shares (defaults to /nfsshares, only supported with hyperkit now) (default "/nfsshares")
--no-vtx-check Disable checking for the availability of hardware virtualization before the vm is started (virtualbox)
--registry-mirror strings Registry mirrors to pass to the Docker daemon
--service-cluster-ip-range string The CIDR to be used for service cluster IPs. (default "10.96.0.0/12")
--uuid string Provide VM UUID to restore MAC address (only supported with Hyperkit driver).
--vm-driver string VM driver is one of: [virtualbox parallels vmwarefusion kvm hyperv hyperkit kvm2 vmware none] (default "virtualbox")
```
---
### status
**Description -** Gets the status of a local kubernetes cluster. Exit status contains the status of minikube's VM, cluster and kubernetes encoded on it's bits in this order from right to left.
Eg: 7 meaning: 1 (for minikube NOK) + 2 (for cluster NOK) + 4 (for kubernetes NOK)
**Usage -** `minikube status [flags]`
**Available Flags -**
```
--format string Go template format string for the status output. The format for Go templates can be found here: https://golang.org/pkg/text/template/
For the list accessible variables for the template, see the struct values here: https://godoc.org/k8s.io/minikube/cmd/minikube/cmd#Status (default "host: {{.Host}}\nkubelet: {{.Kubelet}}\napiserver: {{.APIServer}}\nkubectl: {{.Kubeconfig}}\n")
```
---
### stop
**Description -** Stops a local kubernetes cluster running in Virtualbox. This command stops the VM
itself, leaving all files intact. The cluster can be started again with the `start` command.
**Usage -** `minikube stop`
---
### tunnel
**Description -** Creates a route to services deployed with type LoadBalancer and sets their Ingress to their ClusterIP
**Usage -** `minikube tunnel [flags]`
**Available Flags -**
```
-c, --cleanup call with cleanup=true to remove old tunnels
```
---
### update-check
**Description -** Print current and latest version number.
**Usage -** `minikube update-check`
---
### update-context
**Description -** Retrieves the IP address of the running cluster, checks it with IP in kubeconfig, and corrects kubeconfig if incorrect.
**Usage -** `minikube update-context`
---
### version
**Description -** Print the version of minikube.
**Usage -** `minikube version`

View File

@ -1,43 +1 @@
# Configuring Kubernetes This document has moved to https://minikube.sigs.k8s.io/docs/reference/configuration/kubernetes/
Minikube has a "configurator" feature that allows users to configure the Kubernetes components with arbitrary values.
To use this feature, you can use the `--extra-config` flag on the `minikube start` command.
This flag is repeated, so you can pass it several times with several different values to set multiple options.
## Selecting a Kubernetes version
minikube defaults to the latest stable version of Kubernetes. You may select a different Kubernetes release by using the `--kubernetes-version` flag, for example:
`minikube start --kubernetes-version=v1.10.13`
minikube follows the [Kubernetes Version and Version Skew Support Policy](https://kubernetes.io/docs/setup/version-skew-policy/), so we guarantee support for the latest build for the last 3 minor Kubernetes releases. When practical, minikube extends this policy three additional minor releases so that users can emulate legacy environments.
As of August 2019, this means that minikube supports and actively tests against the latest builds of:
* v1.15.x (default)
* v1.14.x
* v1.13.x
* v1.12.x
* v1.11.x (best effort)
* v1.10.x (best effort)
For more up to date information, see `OldestKubernetesVersion` and `NewestKubernetesVersion` in [constants.go](https://github.com/kubernetes/minikube/blob/master/pkg/minikube/constants/constants.go)
## kubeadm
The kubeadm bootstrapper can be configured by the `--extra-config` flag on the `minikube start` command. It takes a string of the form `component.key=value` where `component` is one of the strings
* kubeadm
* kubelet
* apiserver
* controller-manager
* scheduler
and `key=value` is a flag=value pair for the component being configured. For example,
```shell
minikube start --extra-config=apiserver.v=10 --extra-config=kubelet.max-pods=100
minikube start --extra-config=kubeadm.ignore-preflight-errors=SystemVerification # allows any version of docker
```

View File

@ -1,21 +1 @@
# Contributing This document has moved to https://minikube.sigs.k8s.io/docs/contributing/
* **New contributors** ([contributors.md](https://github.com/kubernetes/minikube/blob/master/CONTRIBUTING.md)): Process for new contributors, CLA instructions
* **Roadmap** ([roadmap.md](roadmap.md)): The roadmap for future minikube development
## New Features and Dependencies
* **Adding a new addon** ([adding_an_addon.md](adding_an_addon.md)): How to add a new addon to minikube for `minikube addons`
* **Adding a new driver** ([adding_driver.md](adding_driver.md)): How to add a new driver to minikube for `minikube create --vm-driver=<driver>`
## Building and Releasing
* **Build Guide** ([build_guide.md](build_guide.md)): How to build minikube from source
* **ISO Build Guide** ([minikube_iso.md](minikube_iso.md)): How to build and hack on the ISO image that minikube uses
* **CI Builds** ([ci_builds.md](./ci_builds.md)): Accessing CI build artifacts from Jenkins
* **Releasing minikube** ([releasing_minikube.md](releasing_minikube.md)): Steps to release a new version of minikube

View File

@ -1,56 +1 @@
# Adding a New Addon This document has moved to https://minikube.sigs.k8s.io/docs/contributing/addons/
To add a new addon to minikube the following steps are required:
* For the new addon's .yaml file(s):
* Put the required .yaml files for the addon in the `minikube/deploy/addons` directory.
* Add the `kubernetes.io/minikube-addons: <NEW_ADDON_NAME>` label to each piece of the addon (ReplicationController, Service, etc.)
* Also, `addonmanager.kubernetes.io/mode` annotation is needed so that your resources are picked up by the `addon-manager` minikube addon.
* In order to have `minikube addons open <NEW_ADDON_NAME>` work properly, the `kubernetes.io/minikube-addons-endpoint: <NEW_ADDON_NAME>` label must be added to the appropriate endpoint service (what the user would want to open/interact with). This service must be of type NodePort.
* To add the addon into minikube commands/VM:
* Add the addon with appropriate fields filled into the `Addon` dictionary, see this [commit](https://github.com/kubernetes/minikube/commit/41998bdad0a5543d6b15b86b0862233e3204fab6#diff-e2da306d559e3f019987acc38431a3e8R133) and example.
```go
// cmd/minikube/cmd/config/config.go
var settings = []Setting{
...,
// add other addon setting
{
name: "efk",
set: SetBool,
validations: []setFn{IsValidAddon},
callbacks: []setFn{EnableOrDisableAddon},
},
}
```
* Add the addon to settings list, see this [commit](https://github.com/kubernetes/minikube/commit/41998bdad0a5543d6b15b86b0862233e3204fab6#diff-07ad0c54f98b231e68537d908a214659R89) and example.
```go
// pkg/minikube/assets/addons.go
var Addons = map[string]*Addon{
...,
// add other addon asset
"efk": NewAddon([]*BinAsset{
MustBinAsset(
"deploy/addons/efk/efk-configmap.yaml",
constants.AddonsPath,
"efk-configmap.yaml",
"0640"),
MustBinAsset(
"deploy/addons/efk/efk-rc.yaml",
constants.AddonsPath,
"efk-rc.yaml",
"0640"),
MustBinAsset(
"deploy/addons/efk/efk-svc.yaml",
constants.AddonsPath,
"efk-svc.yaml",
"0640"),
}, false, "efk"),
}
```
* Rebuild minikube using make out/minikube. This will put the addon's .yaml binary files into the minikube binary using go-bindata.
* Test addon using `minikube addons enable <NEW_ADDON_NAME>` command to start service.

View File

@ -1,100 +1 @@
# Adding new driver (Deprecated) This document has moved to https://minikube.sigs.k8s.io/docs/contributing/drivers/
New drivers should be added into <https://github.com/machine-drivers>
Minikube relies on docker machine drivers to manage machines. This document talks about how to
add an existing docker machine driver into minikube registry, so that minikube can use the driver
by `minikube create --vm-driver=<new_driver>`. This document is not going to talk about how to
create a new docker machine driver.
## Understand your driver
First of all, before started, you need to understand your driver in terms of:
- Which operating system is your driver running on?
- Is your driver builtin the minikube binary or triggered through RPC?
- How to translate minikube config to driver config?
- If builtin, how to instantiate the driver instance?
Builtin basically means whether or not you need separate driver binary in your `$PATH` for minikube to
work. For instance, `hyperkit` is not builtin, because you need `docker-machine-driver-hyperkit` in your
`$PATH`. `vmwarefusion` is builtin, because you don't need anything.
## Understand registry
Registry is what minikube uses to register all the supported drivers. The driver author registers
their drivers in registry, and minikube runtime will look at the registry to find a driver and use the
driver metadata to determine what workflow to apply while those drivers are being used.
The godoc of registry is available here: <https://godoc.org/k8s.io/minikube/pkg/minikube/registry>
[DriverDef](https://godoc.org/k8s.io/minikube/pkg/minikube/registry#DriverDef) is the main
struct to define a driver metadata. Essentially, you need to define 4 things at most, which is
pretty simple once you understand your driver well:
- Name: unique name of the driver, it will be used as the unique ID in registry and as
`--vm-driver` option in minikube command
- Builtin: `true` if the driver is builtin minikube binary. `false` otherwise.
- ConfigCreator: how to translate a minikube config to driver config. The driver config will be persistent
on your `$USER/.minikube` directory. Most likely the driver config is the driver itself.
- DriverCreator: Only needed when driver is builtin, to instantiate the driver instance.
## An example
All drivers are located in `k8s.io/minikube/pkg/minikube/drivers`. Take `vmwarefusion` as an example:
```golang
// +build darwin
package vmwarefusion
import (
"github.com/docker/machine/drivers/vmwarefusion"
"github.com/docker/machine/libmachine/drivers"
cfg "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/registry"
)
func init() {
registry.Register(registry.DriverDef{
Name: "vmwarefusion",
Builtin: true,
ConfigCreator: createVMwareFusionHost,
DriverCreator: func() drivers.Driver {
return vmwarefusion.NewDriver("", "")
},
})
}
func createVMwareFusionHost(config cfg.MachineConfig) interface{} {
d := vmwarefusion.NewDriver(cfg.GetMachineName(), constants.GetMinipath()).(*vmwarefusion.Driver)
d.Boot2DockerURL = config.Downloader.GetISOFileURI(config.MinikubeISO)
d.Memory = config.Memory
d.CPU = config.CPUs
d.DiskSize = config.DiskSize
d.SSHPort = 22
d.ISO = d.ResolveStorePath("boot2docker.iso")
return d
}
```
- In init function, register a `DriverDef` in registry. Specify the metadata in the `DriverDef`. As mentioned
earlier, it's builtin, so you also need to specify `DriverCreator` to tell minikube how to create a `drivers.Driver`.
- Another important thing is `vmwarefusion` only runs on MacOS. You need to add a build tag on top so it only
runs on MacOS, so that the releases on Windows and Linux won't have this driver in registry.
- Last but not least, import the driver in `pkg/minikube/cluster/default_drivers.go` to include it in build.
## Summary
In summary, the process includes the following steps:
1. Add the driver under `k8s.io/minikube/pkg/minikube/drivers`
- Add build tag for supported operating system
- Define driver metadata in `DriverDef`
2. Add import in `pkg/minikube/cluster/default_drivers.go`
Any Questions: please ping your friend [@anfernee](https://github.com/anfernee)

View File

@ -1,114 +1 @@
# Build Guide This document has moved to https://minikube.sigs.k8s.io/docs/contributing/building/
## Build Requirements
* A recent Go distribution (>=1.12)
* If you're not on Linux, you'll need a Docker installation
* minikube requires at least 4GB of RAM to compile, which can be problematic when using docker-machine
### Prerequisites for different GNU/Linux distributions
#### Fedora
On Fedora you need to install _glibc-static_
```shell
$ sudo dnf install -y glibc-static
```
### Building from Source
Clone and build minikube:
```shell
$ git clone https://github.com/kubernetes/minikube.git
$ cd minikube
$ make
```
Note: Make sure that you uninstall any previous versions of minikube before building
from the source.
### Building from Source in Docker (using Debian stretch image with golang)
Clone minikube:
```shell
$ git clone https://github.com/kubernetes/minikube.git
```
Build (cross compile for linux / OS X and Windows) using make:
```shell
$ cd minikube
$ MINIKUBE_BUILD_IN_DOCKER=y make cross
```
Check "out" directory:
```shell
$ ls out/
minikube-darwin-amd64 minikube-linux-amd64 minikube-windows-amd64.exe
```
You can also build platform specific executables like below:
1. `make windows` will build the binary for Windows platform
2. `make linux` will build the binary for Linux platform
3. `make darwin` will build the binary for Darwin/Mac platform
### Run Instructions
Start the cluster using your built minikube with:
```shell
$ ./out/minikube start
```
## Running Tests
### Unit Tests
Unit tests are run on Travis before code is merged. To run as part of a development cycle:
```shell
make test
```
### Integration Tests
Integration tests are currently run manually.
To run them, build the binary and run the tests:
```shell
make integration
```
You may find it useful to set various options to test only a particular test against a non-default driver. For instance:
```shell
env TEST_ARGS="-minikube-start-args=--vm-driver=hyperkit -test.run TestStartStop" make integration
```
### Conformance Tests
These are Kubernetes tests that run against an arbitrary cluster and exercise a wide range of Kubernetes features.
You can run these against minikube by following these steps:
* Clone the Kubernetes repo somewhere on your system.
* Run `make quick-release` in the k8s repo.
* Start up a minikube cluster with: `minikube start`.
* Set following two environment variables:
```shell
export KUBECONFIG=$HOME/.kube/config
export KUBERNETES_CONFORMANCE_TEST=y
```
* Run the tests (from the k8s repo):
```shell
go run hack/e2e.go -v --test --test_args="--ginkgo.focus=\[Conformance\]" --check-version-skew=false
```
To run a specific conformance test, you can use the `ginkgo.focus` flag to filter the set using a regular expression.
The `hack/e2e.go` wrapper and the `e2e.sh` wrappers have a little trouble with quoting spaces though, so use the `\s` regular expression character instead.
For example, to run the test `should update annotations on modification [Conformance]`, use following command:
```shell
go run hack/e2e.go -v --test --test_args="--ginkgo.focus=should\supdate\sannotations\son\smodification" --check-version-skew=false
```

View File

@ -1,11 +1 @@
# CI Builds This document has moved to https://minikube.sigs.k8s.io/docs/contributing/building/
We publish CI builds of minikube, built at every Pull Request. Builds are available at (substitute in the relevant PR number):
- <https://storage.googleapis.com/minikube-builds/PR_NUMBER/minikube-darwin-amd64>
- <https://storage.googleapis.com/minikube-builds/PR_NUMBER/minikube-linux-amd64>
- <https://storage.googleapis.com/minikube-builds/PR_NUMBER/minikube-windows-amd64.exe>
We also publish CI builds of minikube-iso, built at every Pull Request that touches deploy/iso/minikube-iso. Builds are available at:
- <https://storage.googleapis.com/minikube-builds/PR_NUMBER/minikube-testing.iso>

View File

@ -1,78 +1 @@
# minikube ISO image This document has moved to https://minikube.sigs.k8s.io/docs/contributing/iso/
This includes the configuration for an alternative bootable ISO image meant to be used in conjunction with minikube.
It includes:
- systemd as the init system
- docker
- CRI-O
## Hacking
### Requirements
* Linux
```shell
sudo apt-get install build-essential gnupg2 p7zip-full git wget cpio python \
unzip bc gcc-multilib automake libtool locales
```
Either import your private key or generate a sign-only key using `gpg2 --gen-key`.
Also be sure to have an UTF-8 locale set up in order to build the ISO.
### Build instructions
```shell
$ git clone https://github.com/kubernetes/minikube.git
$ cd minikube
$ make buildroot-image
$ make out/minikube.iso
```
The build will occur inside a docker container. If you want to do this on
baremetal, replace `make out/minikube.iso` with `IN_DOCKER=1 make out/minikube.iso`.
The bootable ISO image will be available in `out/minikube.iso`.
### Testing local minikube-iso changes
```shell
$ ./out/minikube start --iso-url=file://$(pwd)/out/minikube.iso
```
### Buildroot configuration
To change the buildroot configuration, execute:
```shell
$ cd out/buildroot
$ make menuconfig
$ make
```
To save any buildroot configuration changes made with `make menuconfig`, execute:
```shell
$ cd out/buildroot
$ make savedefconfig
```
The changes will be reflected in the `minikube-iso/configs/minikube_defconfig` file.
```shell
$ git status
## master
M deploy/iso/minikube-iso/configs/minikube_defconfig
```
### Saving buildroot/kernel configuration changes
To make any kernel configuration changes and save them, execute:
```shell
$ make linux-menuconfig
```
This will open the kernel configuration menu, and then save your changes to our
iso directory after they've been selected.

View File

@ -1,25 +1 @@
# Principles of Minikube This document has moved to https://minikube.sigs.k8s.io/docs/concepts/principles/
The primary goal of minikube is to make it simple to run Kubernetes locally, for day-to-day development workflows and learning purposes. Here are the guiding principles for minikube, in rough priority order:
1. User-friendly and accessible
2. Inclusive and community-driven
3. Cross-platform
4. Support all Kubernetes features
5. High-fidelity
6. Compatible with all supported Kubernetes releases
7. Support for all Kubernetes-friendly container runtimes
8. Stable and easy to debug
Here are some specific minikube features that align with our goal:
* Single command setup and teardown UX
* Support for local storage, networking, auto-scaling, load balancing, etc.
* Unified UX across operating systems
* Minimal dependencies on third party software
* Minimal resource overhead
## Non-Goals
* Simplifying Kubernetes production deployment experience
* Supporting all possible deployment configurations of Kubernetes, such as storage, networking, etc.

View File

@ -1,109 +1 @@
# Steps to Release Minikube This document has moved to https://minikube.sigs.k8s.io/docs/contributing/releasing/
## Preparation
* Announce release intent on #minikube
* Pause merge requests so that they are not accidentally left out of the ISO or release notes
## Build a new ISO
Major releases always get a new ISO. Minor bugfixes may or may not require it: check for changes in the `deploy/iso` folder.
To check, run `git log -- deploy/iso` from the root directory and see if there has been a commit since the most recent release.
Note: you can build the ISO using the `hack/jenkins/build_iso.sh` script locally.
* navigate to the minikube ISO jenkins job
* Ensure that you are logged in (top right)
* Click "▶️ Build with Parameters" (left)
* For `ISO_VERSION`, type in the intended release version (same as the minikube binary's version)
* For `ISO_BUCKET`, type in `minikube/iso`
* Click *Build*
The build will take roughly 50 minutes.
## Update Makefile
Edit the minikube `Makefile`, updating the version number values at the top:
* `VERSION_MAJOR`, `VERSION_MINOR`, `VERSION_BUILD` as necessary
* `ISO_VERSION` - defaults to MAJOR.MINOR.0 - update if point release requires a new ISO to be built.
Make sure the integration tests run against this PR, once the new ISO is built.
## Ad-Hoc testing of other platforms
If there are supported platforms which do not have functioning Jenkins workers (Windows), you may use the following to build a sanity check:
```shell
env BUILD_IN_DOCKER=y make cross checksum
```
## Send out Makefile PR
Once submitted, HEAD will use the new ISO. Please pay attention to test failures, as this is our integration test across platforms. If there are known acceptable failures, please add a PR comment linking to the appropriate issue.
## Update Release Notes
Run the following script to update the release notes:
```shell
hack/release_notes.sh
```
Merge the output into CHANGELOG.md. See [PR#3175](https://github.com/kubernetes/minikube/pull/3175) as an example. Then get the PR submitted.
## Tag the Release
```shell
sh hack/tag_release.sh 1.<minor>.<patch>
```
## Build the Release
This step uses the git tag to publish new binaries to GCS and create a github release:
* navigate to the minikube "Release" jenkins job
* Ensure that you are logged in (top right)
* Click "▶️ Build with Parameters" (left)
* `VERSION_MAJOR`, `VERSION_MINOR`, and `VERSION_BUILD` should reflect the values in your Makefile
* For `ISO_SHA256`, run: `gsutil cat gs://minikube/iso/minikube-v<version>.iso.sha256`
* Click *Build*
## Check the release logs
After job completion, click "Console Output" to verify that the release completed without errors. This is typically where one will see brew automation fail, for instance.
## Check releases.json
This file is used for auto-update notifications, but is not active until releases.json is copied to GCS.
minikube-bot will send out a PR to update the release checksums at the top of `deploy/minikube/releases.json`. You should merge this PR.
## Package managers which include minikube
These are downstream packages that are being maintained by others and how to upgrade them to make sure they have the latest versions
| Package Manager | URL | TODO |
| --- | --- | --- |
| Arch Linux AUR | <https://aur.archlinux.org/packages/minikube-bin/> | "Flag as package out-of-date"
| Brew Cask | <https://github.com/Homebrew/homebrew-cask/blob/master/Casks/minikube.rb> | The release job creates a new PR in [Homebrew/homebrew-cask](https://github.com/Homebrew/homebrew-cask) with an updated version and SHA256, double check that it's created.
WARNING: The Brew cask automation is error-prone. please ensure that a PR was created.
## Verification
Verify release checksums by running`make check-release`
## Update minikube frontpage
We document the last 3 releases on our frontpage. Please add it to the list: <https://github.com/kubernetes/minikube/blob/master/README.md>
## Update official Kubernetes docs
If there are major changes, please send a PR to update <https://kubernetes.io/docs/setup/minikube/>
## Announce!
- #minikube on Slack
- minikube-dev, minikube-users mailing list
- Twitter (optional!)

View File

@ -1,50 +1 @@
# minikube roadmap (2019) This document has moved to https://minikube.sigs.k8s.io/docs/contributing/roadmap/
This roadmap is a living document outlining the major technical improvements which we would like to see in minikube during 2019, divided by how they apply to our [guiding principles](principles.md)
Please send a PR to suggest any improvements to it.
## (#1) User-friendly and accessible
- [ ] Creation of a user-centric minikube website for installation & documentation [#4388](https://github.com/kubernetes/minikube/issues/4388)
- [ ] Localized output to 5+ written languages [#4186](https://github.com/kubernetes/minikube/issues/4186) [#4185](https://github.com/kubernetes/minikube/issues/4185)
- [x] Make minikube usable in environments with challenging connectivity requirements
- [ ] Support lightweight deployment methods for environments where VM's are impractical [#4389](https://github.com/kubernetes/minikube/issues/4389) [#4390](https://github.com/kubernetes/minikube/issues/4390)
- [x] Add offline support
## (#2) Inclusive and community-driven
- [x] Increase community involvement in planning and decision making
- [ ] Make the continuous integration and release infrastructure publicly available [#3256](https://github.com/kubernetes/minikube/issues/4390)
- [x] Double the number of active maintainers
## (#3) Cross-platform
- [ ] Users should never need to separately install supporting binaries [#3975](https://github.com/kubernetes/minikube/issues/3975) [#4391](https://github.com/kubernetes/minikube/issues/4391)
- [ ] Simplified installation process across all supported platforms
## (#4) Support all Kubernetes features
- [ ] Add multi-node support [#94](https://github.com/kubernetes/minikube/issues/94)
## (#5) High-fidelity
- [ ] Reduce guest VM overhead by 50% [#3207](https://github.com/kubernetes/minikube/issues/3207)
- [x] Disable swap in the guest VM
## (#6) Compatible with all supported Kubernetes releases
- [x] Continuous Integration testing across all supported Kubernetes releases
- [ ] Automatic PR generation for updating the default Kubernetes release minikube uses [#4392](https://github.com/kubernetes/minikube/issues/4392)
## (#7) Support for all Kubernetes-friendly container runtimes
- [x] Run all integration tests across all supported container runtimes
- [ ] Support for Kata Containers [#4347](https://github.com/kubernetes/minikube/issues/4347)
## (#8) Stable and easy to debug
- [x] Pre-flight error checks for common connectivity and configuration errors
- [ ] Improve the `minikube status` command so that it can diagnose common issues
- [ ] Mark all features not covered by continuous integration as `experimental`
- [x] Stabilize and improve profiles support (AKA multi-cluster)

View File

@ -1,37 +1 @@
# Dashboard This document has moved to https://minikube.sigs.k8s.io/docs/tasks/dashboard/
Minikube supports the [Kubernetes Dashboard](https://github.com/kubernetes/dashboard) out of the box.
## Accessing the UI
To access the dashboard:
```shell
minikube dashboard
```
This will enable the dashboard add-on, and open the proxy in the default web browser.
To stop the proxy (leaves the dashboard running), abort the started process (`Ctrl+C`).
## Individual steps
If the automatic command doesn't work for you for some reason, here are the steps:
```console
$ minikube addons enable dashboard
✅ dashboard was successfully enabled
```
If you have your kubernetes client configured for minikube, you can start the proxy:
```console
$ kubectl --context minikube proxy
Starting to serve on 127.0.0.1:8001
```
Access the dashboard at:
<http://localhost:8001/api/v1/namespaces/kube-system/services/http:kubernetes-dashboard:/proxy/>
For additional information, see [this page](https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/).

View File

@ -1,17 +1 @@
# Debugging Issues With Minikube This document has moved to https://minikube.sigs.k8s.io/docs/tasks/debug/
To debug issues with minikube (not *Kubernetes* but **minikube** itself), you can use the `-v` flag to see debug level info. The specified values for `-v` will do the following (the values are all encompassing in that higher values will give you all lower value outputs as well):
* `--v=0` will output **INFO** level logs
* `--v=1` will output **WARNING** level logs
* `--v=2` will output **ERROR** level logs
* `--v=3` will output *libmachine* logging
* `--v=7` will output *libmachine --debug* level logging
Example:
`minikube start --v=1` Will start minikube and output all warnings to stdout.
If you need to access additional tools for debugging, minikube also includes the [CoreOS toolbox](https://github.com/coreos/toolbox)
You can ssh into the toolbox and access these additional commands using:
`minikube ssh toolbox`

View File

@ -1,263 +1 @@
# VM Driver plugin installation This document has moved to https://minikube.sigs.k8s.io/docs/reference/drivers/
Minikube uses Docker Machine to manage the Kubernetes VM so it benefits from the
driver plugin architecture that Docker Machine uses to provide a consistent way to
manage various VM providers. Minikube embeds VirtualBox and VMware Fusion drivers
so there are no additional steps to use them. However, other drivers require an
extra binary to be present in the host PATH.
The following drivers currently require driver plugin binaries to be present in
the host PATH:
* [KVM2](#kvm2-driver)
* [Hyperkit](#hyperkit-driver)
* [Hyper-V](#hyper-v-driver)
* [VMware](#vmware-unified-driver)
* [Parallels](#parallels-driver)
## KVM2 driver
### KVM2 install
To install the KVM2 driver, first install and configure the prerequisites, namely libvirt 1.3.1 or higher, and qemu-kvm:
* Debian or Ubuntu 18.x: `sudo apt install libvirt-clients libvirt-daemon-system qemu-kvm`
* Ubuntu 16.x or older: `sudo apt install libvirt-bin libvirt-daemon-system qemu-kvm`
* Fedora/CentOS/RHEL: `sudo yum install libvirt libvirt-daemon-kvm qemu-kvm`
* openSUSE/SLES: `sudo zypper install libvirt qemu-kvm`
Check your installed virsh version:
`virsh --version`
If your version of virsh is newer than 1.3.1 (January 2016), you may download our pre-built driver:
```shell
curl -LO https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-kvm2 \
&& sudo install docker-machine-driver-kvm2 /usr/local/bin/
```
If your version of virsh is older than 1.3.1 (Januarry 2016), you may build your own driver binary if you have go 1.12+ installed.
```console
$ sudo apt install libvirt-dev
$ git clone https://github.com/kubernetes/minikube.git
$ cd minikube
$ make out/docker-machine-driver-kvm2
$ sudo install out/docker-machine-driver-kvm2 /usr/local/bin
$
```
To finish the kvm installation, start and verify the `libvirtd` service
```shell
sudo systemctl enable libvirtd.service
sudo systemctl start libvirtd.service
sudo systemctl status libvirtd.service
```
Add your user to `libvirt` group (older distributions may use `libvirtd` instead)
```shell
sudo usermod -a -G libvirt $(whoami)
```
Join the `libvirt` group with your current shell session:
```shell
newgrp libvirt
```
To use the kvm2 driver:
```shell
minikube start --vm-driver kvm2
```
or, to use kvm2 as a default driver for `minikube start`:
```shell
minikube config set vm-driver kvm2
```
### KVM2 upgrade
```shell
curl -LO https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-kvm2 \
&& sudo install docker-machine-driver-kvm2 /usr/local/bin/
```
### KVM2 troubleshoot
If minikube can't start, check if the kvm default network exists.
```shell
virsh net-list
Name State Autostart Persistent
----------------------------------------------------------
default active yes yes
```
In case the default network doesn't exist you can define it.
```shell
curl https://raw.githubusercontent.com/libvirt/libvirt/master/src/network/default.xml > kvm-default.xml
virsh net-define kvm-default.xml
virsh net-start default
```
Make sure you are running the lastest version of your driver.
```shell
docker-machine-driver-kvm2 version
```
## Hyperkit driver
Install the [hyperkit](http://github.com/moby/hyperkit) VM manager using [brew](https://brew.sh):
```shell
brew install hyperkit
```
Then install the most recent version of minikube's fork of the hyperkit driver:
```shell
curl -LO https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-hyperkit \
&& sudo install -o root -g wheel -m 4755 docker-machine-driver-hyperkit /usr/local/bin/
```
If you are using [dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html) in your setup and cluster creation fails (stuck at kube-dns initialization) you might need to add `listen-address=192.168.64.1` to `dnsmasq.conf`.
*Note: If `dnsmasq.conf` contains `listen-address=127.0.0.1` kubernetes discovers dns at 127.0.0.1:53 and tries to use it using bridge ip address, but dnsmasq replies only to requests from 127.0.0.1*
To use the driver:
```shell
minikube start --vm-driver hyperkit
```
or, to use hyperkit as a default driver for minikube:
```shell
minikube config set vm-driver hyperkit
```
### Hyperkit upgrade
```shell
curl -LO https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-hyperkit \
&& sudo install -o root -g wheel -m 4755 docker-machine-driver-hyperkit /usr/local/bin/
```
### Hyperkit troubleshoot
Make sure you are running the lastest version of your driver.
```shell
docker-machine-driver-hyperkit version
```
## Hyper-V driver
Hyper-V users will need to create a new external network switch as described [here](https://docs.docker.com/machine/drivers/hyper-v/). This step may prevent a problem in which `minikube start` hangs indefinitely, unable to ssh into the minikube virtual machine. In this add, add the `--hyperv-virtual-switch=switch-name` argument to the `minikube start` command.
Older Hyper-V VM's may have **dynamic memory management** enabled, which can cause problems of unexpected and random restarts which manifests itself in simply losing the connection to the cluster, after which `minikube status` would simply state `stopped`. **Solution**: run `minikube delete` to delete the old VM.
To use the driver:
```shell
minikube start --vm-driver hyperv --hyperv-virtual-switch=switch-name
```
or, to use hyperv as a default driver:
```shell
minikube config set vm-driver hyperv && minikube config set hyperv-virtual-switch switch-name
```
and run minikube as usual:
```shell
minikube start
```
## VMware unified driver
The VMware unified driver will eventually replace the existing vmwarefusion driver.
The new unified driver supports both VMware Fusion (on macOS) and VMware Workstation (on Linux and Windows)
To install the vmware unified driver, head over at <https://github.com/machine-drivers/docker-machine-driver-vmware/releases> and download the release for your operating system.
The driver must be:
1. Stored in `$PATH`
2. Named `docker-machine-driver-vmware`
3. Executable (`chmod +x` on UNIX based platforms)
If you're running on macOS with Fusion, this is an easy way install the driver:
```shell
export LATEST_VERSION=$(curl -L -s -H 'Accept: application/json' https://github.com/machine-drivers/docker-machine-driver-vmware/releases/latest | sed -e 's/.*"tag_name":"\([^"]*\)".*/\1/') \
&& curl -L -o docker-machine-driver-vmware https://github.com/machine-drivers/docker-machine-driver-vmware/releases/download/$LATEST_VERSION/docker-machine-driver-vmware_darwin_amd64 \
&& chmod +x docker-machine-driver-vmware \
&& mv docker-machine-driver-vmware /usr/local/bin/
```
To use the driver:
```shell
minikube start --vm-driver vmware
```
or, to use vmware unified driver as a default driver:
```shell
minikube config set vm-driver vmware
```
and run minikube as usual:
```shell
minikube start
```
## Parallels driver
This driver is useful for users who own Parallels Desktop for Mac that do not have VT-x hardware support required by the hyperkit driver.
Pre-requisites: Parallels Desktop for Mac
Install the [Parallels docker-machine driver](https://github.com/Parallels/docker-machine-parallels) using [brew](https://brew.sh):
```shell
brew install docker-machine-parallels
```
To use the driver:
```shell
minikube start --vm-driver parallels
```
or, to use parallels as a default driver for minikube:
```shell
minikube config set vm-driver parallels
```
## Troubleshooting
minikube is currently unable to display the error message received back from the VM driver. Users can however reveal the error by passing `--alsologtostderr -v=8` to `minikube start`. For instance:
```shell
minikube start --vm-driver=kvm2 --alsologtostderr -v=8
```
Output:
```text
Found binary path at /usr/local/bin/docker-machine-driver-kvm2
Launching plugin server for driver kvm2
Error starting plugin binary: fork/exec /usr/local/bin/docker-machine-driver-kvm2: exec format error
```

View File

@ -1,59 +1 @@
This document has moved to https://minikube.sigs.k8s.io/docs/reference/environment_variables
# minikube Environment Variables
## Config option variables
minikube supports passing environment variables instead of flags for every value listed in `minikube config list`. This is done by passing an environment variable with the prefix `MINIKUBE_`.
For example the `minikube start --iso-url="$ISO_URL"` flag can also be set by setting the `MINIKUBE_ISO_URL="$ISO_URL"` environment variable.
## Other variables
Some features can only be accessed by environment variables, here is a list of these features:
* **MINIKUBE_HOME** - (string) sets the path for the .minikube directory that minikube uses for state/configuration
* **MINIKUBE_IN_STYLE** - (bool) manually sets whether or not emoji and colors should appear in minikube. Set to false or 0 to disable this feature, true or 1 to force it to be turned on.
* **MINIKUBE_WANTUPDATENOTIFICATION** - (bool) sets whether the user wants an update notification for new minikube versions
* **MINIKUBE_REMINDERWAITPERIODINHOURS** - (int) sets the number of hours to check for an update notification
* **CHANGE_MINIKUBE_NONE_USER** - (bool) automatically change ownership of ~/.minikube to the value of $SUDO_USER
* **MINIKUBE_ENABLE_PROFILING** - (int, `1` enables it) enables trace profiling to be generated for minikube
## Making these values permanent
To make the exported variables permanent:
* Linux and macOS: Add these declarations to `~/.bashrc` or wherever your shells environment variables are stored.
* Windows: Add these declarations via [system settings](https://support.microsoft.com/en-au/help/310519/how-to-manage-environment-variables-in-windows-xp) or using [setx](https://stackoverflow.com/questions/5898131/set-a-persistent-environment-variable-from-cmd-exe)
### Example: Disabling emoji
```shell
export MINIKUBE_IN_STYLE=false
minikube start
```
### Example: Profiling
```shell
MINIKUBE_ENABLE_PROFILING=1 minikube start
```
Output:
``` text
2017/01/09 13:18:00 profile: cpu profiling enabled, /tmp/profile933201292/cpu.pprof
Starting local Kubernetes cluster...
Kubectl is now configured to use the cluster.
2017/01/09 13:19:06 profile: cpu profiling disabled, /tmp/profile933201292/cpu.pprof
```
Examine the cpu profiling results:
```shell
go tool pprof /tmp/profile933201292/cpu.pprof
```

View File

@ -1,121 +1 @@
# (Experimental) NVIDIA GPU support in minikube This document has moved to https://minikube.sigs.k8s.io/docs/tutorials/nvidia_gpu/
minikube has experimental support for using NVIDIA GPUs on Linux.
## Using NVIDIA GPUs on minikube on Linux with `--vm-driver=kvm2`
When using NVIDIA GPUs with the kvm2 vm-driver. We passthrough spare GPUs on the
host to the minikube VM. Doing so has a few prerequisites:
- You must install the [kvm2 driver](drivers.md#kvm2-driver). If you already had
this installed make sure that you fetch the latest
`docker-machine-driver-kvm2` binary that has GPU support.
- Your CPU must support IOMMU. Different vendors have different names for this
technology. Intel calls it Intel VT-d. AMD calls it AMD-Vi. Your motherboard
must also support IOMMU.
- You must enable IOMMU in the kernel: add `intel_iommu=on` or `amd_iommu=on`
(depending to your CPU vendor) to the kernel command line. Also add `iommu=pt`
to the kernel command line.
- You must have spare GPUs that are not used on the host and can be passthrough
to the VM. These GPUs must not be controlled by the nvidia/nouveau driver. You
can ensure this by either not loading the nvidia/nouveau driver on the host at
all or assigning the spare GPU devices to stub kernel modules like `vfio-pci`
or `pci-stub` at boot time. You can do that by adding the
[vendorId:deviceId](https://pci-ids.ucw.cz/read/PC/10de) of your spare GPU to
the kernel command line. For ex. for Quadro M4000 add `pci-stub.ids=10de:13f1`
to the kernel command line. Note that you will have to do this for all GPUs
you want to passthrough to the VM and all other devices that are in the IOMMU
group of these GPUs.
- Once you reboot the system after doing the above, you should be ready to use
GPUs with kvm2. Run the following command to start minikube:
```shell
minikube start --vm-driver kvm2 --gpu
```
This command will check if all the above conditions are satisfied and
passthrough spare GPUs found on the host to the VM.
If this succeeded, run the following commands:
```shell
minikube addons enable nvidia-gpu-device-plugin
minikube addons enable nvidia-driver-installer
```
This will install the NVIDIA driver (that works for GeForce/Quadro cards)
on the VM.
- If everything succeeded, you should be able to see `nvidia.com/gpu` in the
capacity:
```shell
kubectl get nodes -ojson | jq .items[].status.capacity
```
### Where can I learn more about GPU passthrough?
See the excellent documentation at
<https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF>
### Why are so many manual steps required to use GPUs with kvm2 on minikube?
These steps require elevated privileges which minikube doesn't run with and they
are disruptive to the host, so we decided to not do them automatically.
## Using NVIDIA GPU on minikube on Linux with `--vm-driver=none`
NOTE: This approach used to expose GPUs here is different than the approach used
to expose GPUs with `--vm-driver=kvm2`. Please don't mix these instructions.
- Install minikube.
- Install the nvidia driver, nvidia-docker and configure docker with nvidia as
the default runtime. See instructions at
<https://github.com/NVIDIA/nvidia-docker>
- Start minikube:
```shell
minikube start --vm-driver=none --apiserver-ips 127.0.0.1 --apiserver-name localhost
```
- Install NVIDIA's device plugin:
```shell
kubectl create -f https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.10/nvidia-device-plugin.yml
```
## Why does minikube not support NVIDIA GPUs on macOS?
VM drivers supported by minikube for macOS doesn't support GPU passthrough:
- [mist64/xhyve#108](https://github.com/mist64/xhyve/issues/108)
- [moby/hyperkit#159](https://github.com/moby/hyperkit/issues/159)
- [VirtualBox docs](http://www.virtualbox.org/manual/ch09.html#pcipassthrough)
Also:
- For quite a while, all Mac hardware (both laptops and desktops) have come with
Intel or AMD GPUs (and not with NVIDIA GPUs). Recently, Apple added [support
for eGPUs](https://support.apple.com/en-us/HT208544), but even then all the
supported GPUs listed are AMDs.
- nvidia-docker [doesn't support
macOS](https://github.com/NVIDIA/nvidia-docker/issues/101) either.
## Why does minikube not support NVIDIA GPUs on Windows?
minikube supports Windows host through Hyper-V or VirtualBox.
- VirtualBox doesn't support PCI passthrough for [Windows
host](http://www.virtualbox.org/manual/ch09.html#pcipassthrough).
- Hyper-V supports DDA (discrete device assignment) but [only for Windows Server
2016](https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/plan/plan-for-deploying-devices-using-discrete-device-assignment)
Since the only possibility of supporting GPUs on minikube on Windows is on a
server OS where users don't usually run minikube, we haven't invested time in
trying to support NVIDIA GPUs on minikube on Windows.
Also, nvidia-docker [doesn't support
Windows](https://github.com/NVIDIA/nvidia-docker/issues/197) either.

View File

@ -1,76 +1 @@
# Mounting Host Folders This document has moved to https://minikube.sigs.k8s.io/docs/tasks/mount/
`minikube mount /path/to/dir/to/mount:/vm-mount-path` is the recommended way to mount directories into minikube so that they can be used in your local Kubernetes cluster. The command works on all supported platforms. Below is an example workflow for using `minikube mount`:
```shell
# terminal 1
$ mkdir ~/mount-dir
$ minikube mount ~/mount-dir:/mount-9p
Mounting /home/user/mount-dir/ into /mount-9p on the minikubeVM
This daemon process needs to stay alive for the mount to still be accessible...
ufs starting
# This process has to stay open, so in another terminal...
```
```shell
# terminal 2
$ echo "hello from host" > ~/mount-dir/hello-from-host
$ kubectl run -i --rm --tty ubuntu --overrides='
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "ubuntu"
},
"spec": {
"containers": [
{
"name": "ubuntu",
"image": "ubuntu:14.04",
"args": [
"bash"
],
"stdin": true,
"stdinOnce": true,
"tty": true,
"workingDir": "/mount-9p",
"volumeMounts": [{
"mountPath": "/mount-9p",
"name": "host-mount"
}]
}
],
"volumes": [
{
"name": "host-mount",
"hostPath": {
"path": "/mount-9p"
}
}
]
}
}
' --image=ubuntu:14.04 --restart=Never -- bash
Waiting for pod default/ubuntu to be running, status is Pending, pod ready: false
Waiting for pod default/ubuntu to be running, status is Running, pod ready: false
# ======================================================================================
# We are now in the pod
#=======================================================================================
root@ubuntu:/mount-9p# cat hello-from-host
hello from host
root@ubuntu:/mount-9p# echo "hello from pod" > /mount-9p/hello-from-pod
root@ubuntu:/mount-9p# ls
hello-from-host hello-from-pod
root@ubuntu:/mount-9p# exit
exit
Waiting for pod default/ubuntu to terminate, status is Running
pod "ubuntu" deleted
# ======================================================================================
# We are back on the host
#=======================================================================================
$ cat ~/mount-dir/hello-from-pod
hello from pod
```
Some drivers themselves provide host-folder sharing options, but we plan to deprecate these in the future as they are all implemented differently and they are not configurable through minikube.

View File

@ -1,102 +1 @@
# minikube: Using HTTP/HTTPS proxies This document has moved to https://minikube.sigs.k8s.io/docs/reference/networking/proxy/
minikube requires access to the internet via HTTP, HTTPS, and DNS protocols. If a HTTP proxy is required to access the internet, you may need to pass the proxy connection information to both minikube and Docker using environment variables:
* `HTTP_PROXY` - The URL to your HTTP proxy
* `HTTPS_PROXY` - The URL to your HTTPS proxy
* `NO_PROXY` - A comma-separated list of hosts which should not go through the proxy.
The NO_PROXY variable here is important: Without setting it, minikube may not be able to access resources within the VM. minikube uses two IP ranges, which should not go through the proxy:
* **192.168.99.0/24**: Used by the minikube VM. Configurable for some hypervisors via `--host-only-cidr`
* **192.168.39.0/24**: Used by the minikube kvm2 driver.
* **10.96.0.0/12**: Used by service cluster IP's. Configurable via `--service-cluster-ip-range`
One important note: If NO_PROXY is required by non-Kubernetes applications, such as Firefox or Chrome, you may want to specifically add the minikube IP to the comma-separated list, as they may not understand IP ranges ([#3827](https://github.com/kubernetes/minikube/issues/3827)).
## Example Usage
### macOS and Linux
```shell
export HTTP_PROXY=http://<proxy hostname:port>
export HTTPS_PROXY=https://<proxy hostname:port>
export NO_PROXY=localhost,127.0.0.1,10.96.0.0/12,192.168.99.0/24,192.168.39.0/24
minikube start
```
To make the exported variables permanent, consider adding the declarations to ~/.bashrc or wherever your user-set environment variables are stored.
### Windows
```shell
set HTTP_PROXY=http://<proxy hostname:port>
set HTTPS_PROXY=https://<proxy hostname:port>
set NO_PROXY=localhost,127.0.0.1,10.96.0.0/12,192.168.99.1/24,192.168.39.0/24
minikube start
```
To set these environment variables permanently, consider adding these to your [system settings](https://support.microsoft.com/en-au/help/310519/how-to-manage-environment-variables-in-windows-xp) or using [setx](https://stackoverflow.com/questions/5898131/set-a-persistent-environment-variable-from-cmd-exe)
## Configuring Docker to use a proxy
As of v1.0, minikube automatically configures the Docker instance inside of the VM to use the proxy environment variables, unless you have specified a `--docker-env` override. If you need to manually configure Docker for a set of proxies, use:
```shell
minikube start \
--docker-env=HTTP_PROXY=$HTTP_PROXY \
--docker-env HTTPS_PROXY=$HTTPS_PROXY \
--docker-env NO_PROXY=$NO_PROXY
```
## Troubleshooting
### unable to cache ISO... connection refused
```text
Unable to start VM: unable to cache ISO: https://storage.googleapis.com/minikube/iso/minikube.iso:
failed to download: failed to download to temp file: download failed: 5 error(s) occurred:
* Temporary download error: Get https://storage.googleapis.com/minikube/iso/minikube.iso:
proxyconnect tcp: dial tcp <host>:<port>: connect: connection refused
```
This error indicates that the host:port combination defined by HTTPS_PROXY or HTTP_PROXY is incorrect, or that the proxy is unavailable.
## Unable to pull images..Client.Timeout exceeded while awaiting headers
```text
Unable to pull images, which may be OK:
failed to pull image "k8s.gcr.io/kube-apiserver:v1.13.3": output: Error response from daemon:
Get https://k8s.gcr.io/v2/: net/http: request canceled while waiting for connection
(Client.Timeout exceeded while awaiting headers)
```
This error indicates that the container runtime running within the VM does not have access to the internet. Verify that you are passing the appropriate value to `--docker-env HTTPS_PROXY`.
## x509: certificate signed by unknown authority
```text
[ERROR ImagePull]: failed to pull image k8s.gcr.io/kube-apiserver:v1.13.3:
output: Error response from daemon:
Get https://k8s.gcr.io/v2/: x509: certificate signed by unknown authority
```
This is because minikube VM is stuck behind a proxy that rewrites HTTPS responses to contain its own TLS certificate. The [solution](https://github.com/kubernetes/minikube/issues/3613#issuecomment-461034222) is to install the proxy certificate into a location that is copied to the VM at startup, so that it can be validated.
Ask your IT department for the appropriate PEM file, and add it to:
`~/.minikube/files/etc/ssl/certs`
Then run `minikube delete` and `minikube start`.
## downloading binaries: proxyconnect tcp: tls: oversized record received with length 20527
Your need to set a correct `HTTPS_PROXY` value.
## Additional Information
* [Configure Docker to use a proxy server](https://docs.docker.com/network/proxy/)

View File

@ -1,28 +1 @@
# Enabling Docker Insecure Registry This document has moved to https://minikube.sigs.k8s.io/docs/tasks/registry/
Minikube allows users to configure the docker engine's `--insecure-registry` flag. You can use the `--insecure-registry` flag on the
`minikube start` command to enable insecure communication between the docker engine and registries listening to requests from the CIDR range.
One nifty hack is to allow the kubelet running in minikube to talk to registries deployed inside a pod in the cluster without backing them
with TLS certificates. Because the default service cluster IP is known to be available at 10.0.0.1, users can pull images from registries
deployed inside the cluster by creating the cluster with `minikube start --insecure-registry "10.0.0.0/24"`.
## Private Container Registries
**GCR/ECR/Docker**: Minikube has an addon, `registry-creds` which maps credentials into Minikube to support pulling from Google Container Registry (GCR), Amazon's EC2 Container Registry (ECR), and Private Docker registries. You will need to run `minikube addons configure registry-creds` and `minikube addons enable registry-creds` to get up and running. An example of this is below:
```shell
$ minikube addons configure registry-creds
Do you want to enable AWS Elastic Container Registry? [y/n]: n
Do you want to enable Google Container Registry? [y/n]: y
-- Enter path to credentials (e.g. /home/user/.config/gcloud/application_default_credentials.json):/home/user/.config/gcloud/application_default_credentials.json
Do you want to enable Docker Registry? [y/n]: n
registry-creds was successfully configured
$ minikube addons enable registry-creds
```
For additional information on private container registries, see [this page](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/).
We recommend you use _ImagePullSecrets_, but if you would like to configure access on the minikube VM you can place the `.dockercfg` in the `/home/docker` directory or the `config.json` in the `/var/lib/kubelet` directory. Make sure to restart your kubelet (for kubeadm) process with `sudo systemctl restart kubelet`.

View File

@ -1,78 +1,2 @@
# Networking This document has moved to https://minikube.sigs.k8s.io/docs/reference/networking/
## Firewalls, VPN's, and proxies
minikube may require access from the host to the following IP ranges: 192.168.99.0/24, 192.168.39.0/24, and 10.96.0.0/12. These networks can be changed in minikube using `--host-only-cidr` and `--service-cluster-ip-range`.
* To use minikube with a proxy, see [Using HTTP/HTTPS proxies](http_proxy.md).
* If you are using minikube with a VPN, you may need to configure the VPN to allow local routing for traffic to the afforementioned IP ranges.
* If you are using minikube with a local firewall, you will need to allow access from the host to the afforementioned IP ranges on TCP ports 22 and 8443. You will also need to add access from these IP's to TCP ports 443 and 53 externally to pull images.
## Access to NodePort services
The minikube VM is exposed to the host system via a host-only IP address, that can be obtained with the `minikube ip` command. Any services of type `NodePort` can be accessed over that IP address, on the NodePort.
To determine the NodePort for your service, you can use a `kubectl` command like this (note that `nodePort` begins with lowercase `n` in JSON output):
`kubectl get service $SERVICE --output='jsonpath="{.spec.ports[0].nodePort}"'`
We also have a shortcut for fetching the minikube IP and a service's `NodePort`:
`minikube service --url $SERVICE`
### Increasing the NodePort range
By default, minikube only exposes ports 30000-32767. If this is not enough, you can configure the apiserver to allow all ports using:
`minikube start --extra-config=apiserver.service-node-port-range=1-65535`
This flag also accepts a comma separated list of ports and port ranges.
## Access to LoadBalancer services using `minikube tunnel`
Services of type `LoadBalancer` can be exposed via the `minikube tunnel` command.
````shell
minikube tunnel
````
Will output:
```text
out/minikube tunnel
Password: *****
Status:
machine: minikube
pid: 59088
route: 10.96.0.0/12 -> 192.168.99.101
minikube: Running
services: []
errors:
minikube: no errors
router: no errors
loadbalancer emulator: no errors
````
Tunnel might ask you for password for creating and deleting network routes.
## Cleaning up orphaned routes
If the `minikube tunnel` shuts down in an unclean way, it might leave a network route around.
This case the ~/.minikube/tunnels.json file will contain an entry for that tunnel.
To cleanup orphaned routes, run:
````shell
minikube tunnel --cleanup
````
## Tunnel: Avoid entering password multiple times
`minikube tunnel` runs as a separate daemon, creates a network route on the host to the service CIDR of the cluster using the cluster's IP address as a gateway. Adding a route requires root privileges for the user, and thus there are differences in how to run `minikube tunnel` depending on the OS.
If you want to avoid entering the root password, consider setting NOPASSWD for "ip" and "route" commands:
<https://superuser.com/questions/1328452/sudoers-nopasswd-for-single-executable-but-allowing-others>

View File

@ -1,40 +1 @@
# Offline support in minikube This document has moved to https://minikube.sigs.k8s.io/docs/reference/cache/
As of v1.0, `minikube start` is offline compatible out of the box. Here are some implementation details to help systems integrators:
## Requirements
* On the initial run for a given Kubernetes release, `minikube start` must have access to the internet, or a configured `--image-repository` to pull from.
## Cache location
* `~/.minikube/cache` - Top-level folder
* `~/.minikube/cache/iso` - VM ISO image. Typically updated once per major minikube release.
* `~/.minikube/cache/images` - Docker images used by Kubernetes.
* `~/.minikube/cache/<version>` - Kubernetes binaries, such as `kubeadm` and `kubelet`
## Sharing the minikube cache
For offline use on other hosts, one can copy the contents of `~/.minikube/cache`. As of the v1.0 release, this directory
contains 685MB of data:
```text
cache/iso/minikube-v1.0.0.iso
cache/images/gcr.io/k8s-minikube/storage-provisioner_v1.8.1
cache/images/k8s.gcr.io/k8s-dns-sidecar-amd64_1.14.13
cache/images/k8s.gcr.io/k8s-dns-dnsmasq-nanny-amd64_1.14.13
cache/images/k8s.gcr.io/kubernetes-dashboard-amd64_v1.10.1
cache/images/k8s.gcr.io/kube-scheduler_v1.14.0
cache/images/k8s.gcr.io/coredns_1.3.1
cache/images/k8s.gcr.io/kube-controller-manager_v1.14.0
cache/images/k8s.gcr.io/kube-apiserver_v1.14.0
cache/images/k8s.gcr.io/pause_3.1
cache/images/k8s.gcr.io/etcd_3.3.10
cache/images/k8s.gcr.io/kube-addon-manager_v9.0
cache/images/k8s.gcr.io/k8s-dns-kube-dns-amd64_1.14.13
cache/images/k8s.gcr.io/kube-proxy_v1.14.0
cache/v1.14.0/kubeadm
cache/v1.14.0/kubelet
```
If any of these files exist, minikube will use copy them into the VM directly rather than pulling them from the internet.

View File

@ -1,33 +1 @@
# OpenID Connect Authentication This document has moved to https://minikube.sigs.k8s.io/docs/tutorials/openid_connect_auth/
Minikube `kube-apiserver` can be configured to support OpenID Connect Authentication.
Read more about OpenID Connect Authentication for Kubernetes here: <https://kubernetes.io/docs/reference/access-authn-authz/authentication/#openid-connect-tokens>
## Configuring the API Server
Configuration values can be passed to the API server using the `--extra-config` flag on the `minikube start` command. See [configuring_kubernetes.md](https://github.com/kubernetes/minikube/blob/master/docs/configuring_kubernetes.md) for more details.
The following example configures your Minikube cluster to support RBAC and OIDC:
```shell
minikube start \
--extra-config=apiserver.authorization-mode=RBAC \
--extra-config=apiserver.oidc-issuer-url=https://example.com \
--extra-config=apiserver.oidc-username-claim=email \
--extra-config=apiserver.oidc-client-id=kubernetes-local
```
## Configuring kubectl
You can use the kubectl `oidc` authenticator to create a kubeconfig as shown in the Kubernetes docs: <https://kubernetes.io/docs/reference/access-authn-authz/authentication/#option-1-oidc-authenticator>
`minikube start` already creates a kubeconfig that includes a `cluster`, in order to use it with your `oidc` authenticator kubeconfig, you can run:
```shell
kubectl config set-context kubernetes-local-oidc --cluster=minikube --user username@example.com
Context "kubernetes-local-oidc" created.
kubectl config use-context kubernetes-local-oidc
```
For the new context to work you will need to create, at the very minimum, a `Role` and a `RoleBinding` in your cluster to grant permissions to the `subjects` included in your `oidc-username-claim`.

View File

@ -1,39 +1 @@
# Persistent Volumes This document has moved to https://minikube.sigs.k8s.io/docs/reference/persistent_volumes/
Minikube supports [PersistentVolumes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/) of type `hostPath` out of the box. These PersistentVolumes are mapped to a directory inside the running Minikube instance (usually a VM, unless you use `--vm-driver=none`). For more information on how this works, read the Dynamic Provisioning section below.
## A note on mounts, persistence, and Minikube hosts
Minikube is configured to persist files stored under the following directories, which are made in the Minikube VM (or on your localhost if running on bare metal). You may lose data from other directories on reboots.
* `/data`
* `/var/lib/minikube`
* `/var/lib/docker`
* `/tmp/hostpath_pv`
* `/tmp/hostpath-provisioner`
Here is an example PersistentVolume config to persist data in the '/data' directory:
```yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv0001
spec:
accessModes:
- ReadWriteOnce
capacity:
storage: 5Gi
hostPath:
path: /data/pv0001/
```
You can also achieve persistence by creating a PV in a mounted host folder.
## Dynamic provisioning and CSI
In addition, minikube implements a very simple, canonical implementation of dynamic storage controller that runs alongside its deployment. This manages provisioning of *hostPath* volumes (rather then via the previous, in-tree hostPath provider).
The default [Storage Provisioner Controller](https://github.com/kubernetes/minikube/blob/master/pkg/storage/storage_provisioner.go) is managed internally, in the minikube codebase, demonstrating how easy it is to plug a custom storage controller into kubernetes as a storage component of the system, and provides pods with dynamically, to test your pod's behaviour when persistent storage is mapped to it.
Note that this is not a CSI based storage provider, rather, it simply declares a PersistentVolume object of type hostpath dynamically when the controller see's that there is an outstanding storage request.

View File

@ -1,81 +1 @@
# Reusing the Docker daemon This document has moved to https://minikube.sigs.k8s.io/docs/tasks/docker_daemon/
## Method 1: Without minikube registry addon
When using a single VM of Kubernetes it's really handy to reuse the Docker daemon inside the VM; as this means you don't have to build on your host machine and push the image into a docker registry - you can just build inside the same docker daemon as minikube which speeds up local experiments.
To be able to work with the docker daemon on your mac/linux host use the docker-env command in your shell:
```shell
eval $(minikube docker-env)
```
You should now be able to use docker on the command line on your host mac/linux machine talking to the docker daemon inside the minikube VM:
```shell
docker ps
```
Docker may report following forbidden error if you are using http proxy and the `$(minikube ip)` is not added to `no_proxy`/`NO_PROXY`:
```shell
error during connect: Get https://192.168.39.98:2376/v1.39/containers/json: Forbidden
```
On Centos 7, docker may report the following error:
```shell
Could not read CA certificate "/etc/docker/ca.pem": open /etc/docker/ca.pem: no such file or directory
```
The fix is to update /etc/sysconfig/docker to ensure that minikube's environment changes are respected:
```diff
< DOCKER_CERT_PATH=/etc/docker
---
> if [ -z "${DOCKER_CERT_PATH}" ]; then
> DOCKER_CERT_PATH=/etc/docker
> fi
```
Remember to turn off the _imagePullPolicy:Always_, as otherwise Kubernetes won't use images you built locally.
## Method 2: With minikube registry addon
Enable minikube registry addon and then push images directly into registry. Steps are as follows:
For illustration purpose, we will assume that minikube VM has one of the ip from `192.168.39.0/24` subnet. If you have not overridden these subnets as per [networking guide](https://github.com/kubernetes/minikube/blob/master/docs/networking.md), you can find out default subnet being used by minikube for a specific OS and driver combination [here](https://github.com/kubernetes/minikube/blob/dfd9b6b83d0ca2eeab55588a16032688bc26c348/pkg/minikube/cluster/cluster.go#L408) which is subject to change. Replace `192.168.39.0/24` with appropriate values for your environment wherever applicable.
Ensure that docker is configured to use `192.168.39.0/24` as insecure registry. Refer [here](https://docs.docker.com/registry/insecure/) for instructions.
Ensure that `192.168.39.0/24` is enabled as insecure registry in minikube. Refer [here](https://github.com/kubernetes/minikube/blob/master/docs/insecure_registry.md) for instructions..
Enable minikube registry addon:
```shell
minikube addons enable registry
```
Build docker image and tag it appropriately:
```shell
docker build --tag $(minikube ip):5000/test-img .
```
Push docker image to minikube registry:
```shell
docker push $(minikube ip):5000/test-img
```
Now run it in minikube:
```shell
kubectl run test-img --image=$(minikube ip):5000/test-img
```
Or if `192.168.39.0/24` is not enabled as insecure registry in minikube, then:
```shell
kubectl run test-img --image=localhost:5000/test-img
```

View File

@ -1,15 +1 @@
# minikube: Syncing files into the VM This document has moved to https://minikube.sigs.k8s.io/docs/tasks/sync/
## Syncing files during start up
As soon as a VM is created, minikube will populate the root filesystem with any files stored in $MINIKUBE_HOME (~/.minikube/files).
For example, running the following commands will result in `/etc/OMG` being added with the contents of `hello` into the minikube VM:
```shell
mkdir -p ~/.minikube/files/etc
echo hello > ~/.minikube/files/etc/OMG
minikube start
```
This method of file synchronization can be useful for adding configuration files for apiserver, or adding HTTPS certificates.

View File

@ -1,144 +1 @@
# Minikube Tunnel Design Doc This document has moved to https://minikube.sigs.k8s.io/docs/tasks/loadbalancer/
## Background
Minikube today only exposes a single IP address for all cluster and VM communication.
This effectively requires users to connect to any running Pods, Services or LoadBalancers over ClusterIPs, which can require modifications to workflows when compared to developing against a production cluster.
A main goal of Minikube is to minimize the differences required in code and configuration between development and production, so this is not ideal.
If all cluster IP addresses and Load Balancers were made available on the minikube host machine, these modifications would not be necessary and users would get the "magic" experience of developing from inside a cluster.
Tools like telepresence.io, sshuttle, and the OpenVPN chart provide similar capabilities already.
Also, Steve Sloka has provided a very detailed guide on how to setup a similar configuration [manually](https://stevesloka.com/access-minikube-service-from-linux-host/).
Elson Rodriguez has provided a similar guide, including a Minikube [external LB controller](https://github.com/elsonrodriguez/minikube-lb-patch).
## Example usage
```shell
$ minikube tunnel
Starting minikube tunnel process. Press Ctrl+C to exit.
All cluster IPs and load balancers are now available from your host machine.
```
## Overview
We will introduce a new command, `minikube tunnel`, that must be run with root permissions.
This command will:
* Establish networking routes from the host into the VM for all IP ranges used by Kubernetes.
* Enable a cluster controller that allocates IPs to services external `LoadBalancer` IPs.
* Clean up routes and IPs when stopped, or when `minikube` stops.
Additionally, we will introduce a Minikube LoadBalancer controller that manages a CIDR of IPs and assigns them to services of type `LoadBalancer`.
These IPs will also be made available on the host machine.
## Network Routes
Minikube drivers usually establish "host-only" IP addresses (192.168.1.1, for example) that route into the running VM
from the host.
The new `minikube tunnel` command will create a static routing table entry that maps the CIDRs used by Pods, Services and LoadBalancers to the host-only IP, obtainable via the `minikube ip` command.
The commands below detail adding routes for the entire `/8` block, we should probably add individual entries for each CIDR we manage instead.
### Linux
Route entries for the entire 10.* block can be added via:
```shell
sudo ip route add 10.0.0.0/8 via $(minikube ip)
```
and deleted via:
```shell
sudo ip route delete 10.0.0.0/8
```
The routing table can be queried with `netstat -nr -f inet`
### OSX
Route entries can be added via:
```shell
sudo route -n add 10.0.0.0/8 $(minikube ip)
```
and deleted via:
```shell
sudo route -n delete 10.0.0.0/8
```
The routing table can be queried with `netstat -nr -f inet`
### Windows
Route entries can be added via:
```shell
route ADD 10.0.0.0 MASK 255.0.0.0 <minikube ip>
```
and deleted via:
```shell
route DELETE 10.0.0.0
```
The routing table can be queried with `route print -4`
### Handling unclean shutdowns
Unclean shutdowns of the tunnel process can result in partially executed cleanup process, leaving network routes in the routing table.
We will keep track of the routes created by each tunnel in a centralized location in the main minikube config directory.
This list serves as a registry for tunnels containing information about
- machine profile
- process ID
- and the route that was created
The cleanup command cleans the routes from both the routing table and the registry for tunnels that are not running:
```shell
minikube tunnel --cleanup
```
Updating the tunnel registry and the routing table is an atomic transaction:
- create route in the routing table + create registry entry if both are successful, otherwise rollback
- delete route in the routing table + remove registry entry if both are successful, otherwise rollback
*Note*: because we don't support currently real multi cluster setup (due to overlapping CIDRs), the handling of running/not-running processes is not strictly required however it is forward looking.
### Handling routing table conflicts
A routing table conflict happens when a destination CIDR of the route required by the tunnel overlaps with an existing route.
Minikube tunnel will warn the user if this happens and should not create the rule.
There should not be any automated removal of conflicting routes.
*Note*: If the user removes the minikube config directory, this might leave conflicting rules in the network routing table that will have to be cleaned up manually.
## Load Balancer Controller
In addition to making IPs routable, minikube tunnel will assign an external IP (the ClusterIP) to all services of type `LoadBalancer`.
The logic of this controller will be, roughly:
```python
for service in services:
if service.type == "LoadBalancer" and len(service.ingress) == 0:
add_ip_to_service(ClusterIP, service)
sleep
```
Note that the Minikube ClusterIP can change over time (during system reboots) and this loop should also handle reconciliation of those changes.
## Handling multiple clusters
Multiple clusters are currently not supported due to our inability to specify ServiceCIDR.
This causes conflicting routes having the same destination CIDR.

View File

@ -1,119 +1 @@
# vm-driver=none This document has moved to https://minikube.sigs.k8s.io/docs/reference/drivers/none/
## Overview
This document is written for system integrators who are familiar with minikube, and wish to run it within a customized VM environment.
The `none` driver allows advanced minikube users to skip VM creation, allowing minikube to be run on a user-supplied VM.
## What operating systems are supported?
The `none` driver supports releases of Debian, Ubuntu, and Fedora that are less than 2 years old. In practice, any systemd-based modern distribution is likely to work, and we will accept pull requests which improve compatibility with other systems.
## Example: basic usage
`sudo minikube start --vm-driver=none`
NOTE: The none driver requires minikube to be run as root, until [#3760](https://github.com/kubernetes/minikube/issues/3760) can be addressed.
## Example: Using minikube for continuous integration testing
Most continuous integration environments are already running inside a VM, and may not supported nested virtualization. The `none` driver was designed for this use case. Here is an example, that runs minikube from a non-root user, and ensures that the latest stable kubectl is installed:
```shell
curl -Lo minikube \
https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 \
&& sudo install minikube /usr/local/bin/
kv=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)
curl -Lo kubectl \
https://storage.googleapis.com/kubernetes-release/release/$kv/bin/linux/amd64/kubectl \
&& sudo install kubectl /usr/local/bin/
export MINIKUBE_WANTUPDATENOTIFICATION=false
export MINIKUBE_WANTREPORTERRORPROMPT=false
export MINIKUBE_HOME=$HOME
export CHANGE_MINIKUBE_NONE_USER=true
export KUBECONFIG=$HOME/.kube/config
mkdir -p $HOME/.kube $HOME/.minikube
touch $KUBECONFIG
sudo -E minikube start --vm-driver=none
```
At this point, kubectl should be able to interact with the minikube cluster.
## Can the none driver be used outside of a VM?
Yes, *but please avoid doing so if at all possible.*
minikube was designed to run Kubernetes within a dedicated VM, and assumes that it has complete control over the machine it is executing on. With the `none` driver, minikube and Kubernetes run in an environment with very limited isolation, which could result in:
* Decreased security
* Decreased reliability
* Data loss
We'll cover these in detail below:
### Decreased security
* minikube starts services that may be available on the Internet. Please ensure that you have a firewall to protect your host from unexpected access. For instance:
* apiserver listens on TCP *:8443
* kubelet listens on TCP *:10250 and *:10255
* kube-scheduler listens on TCP *:10259
* kube-controller listens on TCP *:10257
* Containers may have full access to your filesystem.
* Containers may be able to execute arbitrary code on your host, by using container escape vulnerabilities such as [CVE-2019-5736](https://access.redhat.com/security/vulnerabilities/runcescape). Please keep your release of minikube up to date.
### Decreased reliability
* minikube with the none driver may be tricky to configure correctly at first, because there are many more chances for interference with other locally run services, such as dnsmasq.
* When run in `none` mode, minikube has no built-in resource limit mechanism, which means you could deploy pods which would consume all of the hosts resources.
* minikube and the Kubernetes services it starts may interfere with other running software on the system. For instance, minikube will start and stop container runtimes via systemd, such as docker, containerd, cri-o.
### Data loss
With the `none` driver, minikube will overwrite the following system paths:
* /usr/bin/kubeadm - Updated to match the exact version of Kubernetes selected
* /usr/bin/kubelet - Updated to match the exact version of Kubernetes selected
* /etc/kubernetes - configuration files
These paths will be erased when running `minikube delete`:
* /data/minikube
* /etc/kubernetes/manifests
* /var/lib/minikube
As Kubernetes has full access to both your filesystem as well as your docker images, it is possible that other unexpected data loss issues may arise.
## Environment variables
Some environment variables may be useful for using the `none` driver:
* **CHANGE_MINIKUBE_NONE_USER**: Sets file ownership to the user running sudo ($SUDO_USER)
* **MINIKUBE_HOME**: Saves all files to this directory instead of $HOME
* **MINIKUBE_WANTUPDATENOTIFICATION**: Toggles the notification that your version of minikube is obsolete
* **MINIKUBE_WANTREPORTERRORPROMPT**: Toggles the error reporting prompt
* **MINIKUBE_IN_STYLE**: Toggles color output and emoji usage
## Known Issues
* `systemctl` is required. [#2704](https://github.com/kubernetes/minikube/issues/2704)
* `-p` (profiles) are unsupported: It is not possible to run more than one `--vm-driver=none` instance
* Many `minikube` commands are not supported, such as: `dashboard`, `mount`, `ssh`
* minikube with the `none` driver has a confusing permissions model, as some commands need to be run as root ("start"), and others by a regular user ("dashboard")
* CoreDNS detects resolver loop, goes into CrashloopBackoff - [#3511](https://github.com/kubernetes/minikube/issues/3511)
* Some versions of Linux have a version of docker that is newer then what Kubernetes expects. To overwrite this, run minikube with the following parameters: `sudo -E minikube start --vm-driver=none --kubernetes-version v1.11.8 --extra-config kubeadm.ignore-preflight-errors=SystemVerification`
* On Ubuntu 18.04 (and probably others), because of how `systemd-resolve` is configured by default, one needs to bypass the default `resolv.conf` file and use a different one instead.
- In this case, you should use this file: `/run/systemd/resolve/resolv.conf`
- `sudo -E minikube --vm-driver=none start --extra-config=kubelet.resolv-conf=/run/systemd/resolve/resolv.conf`
- Apperently, though, if `resolve.conf` is too big (about 10 lines!!!), one gets the following error: `Waiting for pods: apiserver proxy! Error restarting cluster: wait: waiting for k8s-app=kube-proxy: timed out waiting for the condition`
- This error happens in Kubernetes 0.11.x, 0.12.x and 0.13.x, but *not* in 0.14.x
- If that's your case, try this:
- `grep -E "^nameserver" /run/systemd/resolve/resolv.conf |head -n 3 > /tmp/resolv.conf && sudo -E minikube --vm-driver=none start --extra-config=kubelet.resolv-conf=/tmp/resolv.conf`
* [Full list of open 'none' driver issues](https://github.com/kubernetes/minikube/labels/co%2Fnone-driver)

5
go.mod
View File

@ -9,12 +9,12 @@ require (
github.com/blang/semver v3.5.0+incompatible github.com/blang/semver v3.5.0+incompatible
github.com/c4milo/gotoolkit v0.0.0-20170318115440-bcc06269efa9 // indirect github.com/c4milo/gotoolkit v0.0.0-20170318115440-bcc06269efa9 // indirect
github.com/cenkalti/backoff v2.2.1+incompatible github.com/cenkalti/backoff v2.2.1+incompatible
github.com/cheggaaa/pb v1.0.27 github.com/cheggaaa/pb/v3 v3.0.1
github.com/cloudfoundry-attic/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 github.com/cloudfoundry-attic/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21
github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 // indirect github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 // indirect
github.com/docker/docker v1.13.1 // indirect github.com/docker/docker v1.13.1 // indirect
github.com/docker/go-units v0.3.3 github.com/docker/go-units v0.3.3
github.com/docker/machine v0.16.1-0.20190718054102-a555e4f7a8f5 github.com/docker/machine v0.7.1-0.20190718054102-a555e4f7a8f5 // version is 0.7.1 to pin to a555e4f7a8f5
github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f
github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f // indirect github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f // indirect
github.com/go-ole/go-ole v1.2.4 // indirect github.com/go-ole/go-ole v1.2.4 // indirect
@ -35,7 +35,6 @@ require (
github.com/johanneswuerbach/nfsexports v0.0.0-20181204082207-1aa528dcb345 github.com/johanneswuerbach/nfsexports v0.0.0-20181204082207-1aa528dcb345
github.com/libvirt/libvirt-go v3.4.0+incompatible github.com/libvirt/libvirt-go v3.4.0+incompatible
github.com/machine-drivers/docker-machine-driver-vmware v0.1.1 github.com/machine-drivers/docker-machine-driver-vmware v0.1.1
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/mattn/go-isatty v0.0.8 github.com/mattn/go-isatty v0.0.8
github.com/mitchellh/go-ps v0.0.0-20170309133038-4fdf99ab2936 github.com/mitchellh/go-ps v0.0.0-20170309133038-4fdf99ab2936
github.com/moby/hyperkit v0.0.0-20171020124204-a12cd7250bcd github.com/moby/hyperkit v0.0.0-20171020124204-a12cd7250bcd

8
go.sum
View File

@ -33,6 +33,8 @@ github.com/Sirupsen/logrus v0.0.0-20170822132746-89742aefa4b2 h1:k1A7eIeUk6rnX2y
github.com/Sirupsen/logrus v0.0.0-20170822132746-89742aefa4b2/go.mod h1:rmk17hk6i8ZSAJkSDa7nOxamrG+SP4P0mm+DAvExv4U= github.com/Sirupsen/logrus v0.0.0-20170822132746-89742aefa4b2/go.mod h1:rmk17hk6i8ZSAJkSDa7nOxamrG+SP4P0mm+DAvExv4U=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk= github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcM=
github.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA=
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
@ -59,6 +61,8 @@ github.com/cespare/prettybench v0.0.0-20150116022406-03b8cfe5406c/go.mod h1:Xe6Z
github.com/chai2010/gettext-go v0.0.0-20160711120539-c6fed771bfd5/go.mod h1:/iP1qXHoty45bqomnu2LM+VVyAEdWN+vtSHGlQgyxbw= github.com/chai2010/gettext-go v0.0.0-20160711120539-c6fed771bfd5/go.mod h1:/iP1qXHoty45bqomnu2LM+VVyAEdWN+vtSHGlQgyxbw=
github.com/cheggaaa/pb v1.0.27 h1:wIkZHkNfC7R6GI5w7l/PdAdzXzlrbcI3p8OAlnkTsnc= github.com/cheggaaa/pb v1.0.27 h1:wIkZHkNfC7R6GI5w7l/PdAdzXzlrbcI3p8OAlnkTsnc=
github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s=
github.com/cheggaaa/pb/v3 v3.0.1 h1:m0BngUk2LuSRYdx4fujDKNRXNDpbNCfptPfVT2m6OJY=
github.com/cheggaaa/pb/v3 v3.0.1/go.mod h1:SqqeMF/pMOIu3xgGoxtPYhMNQP258xE4x/XRTYua+KU=
github.com/client9/misspell v0.0.0-20170928000206-9ce5d979ffda/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.0.0-20170928000206-9ce5d979ffda/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/cfssl v0.0.0-20180726162950-56268a613adf/go.mod h1:yMWuSON2oQp+43nFtAV/uvKQIFpSPerB57DCt9t8sSA= github.com/cloudflare/cfssl v0.0.0-20180726162950-56268a613adf/go.mod h1:yMWuSON2oQp+43nFtAV/uvKQIFpSPerB57DCt9t8sSA=
@ -106,8 +110,8 @@ github.com/docker/go-connections v0.3.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5Xh
github.com/docker/go-units v0.3.3 h1:Xk8S3Xj5sLGlG5g67hJmYMmUgXv5N4PhkjJHHqrwnTk= github.com/docker/go-units v0.3.3 h1:Xk8S3Xj5sLGlG5g67hJmYMmUgXv5N4PhkjJHHqrwnTk=
github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/docker/libnetwork v0.0.0-20180830151422-a9cd636e3789/go.mod h1:93m0aTqz6z+g32wla4l4WxTrdtvBRmVzYRkYvasA5Z8= github.com/docker/libnetwork v0.0.0-20180830151422-a9cd636e3789/go.mod h1:93m0aTqz6z+g32wla4l4WxTrdtvBRmVzYRkYvasA5Z8=
github.com/docker/machine v0.16.1-0.20190718054102-a555e4f7a8f5 h1:5OiV/JwT55JRKNJsM9HZrTlJH/TRp97Ee89ahtB78+w= github.com/docker/machine v0.7.1-0.20190718054102-a555e4f7a8f5 h1:/2G2PrqxKga8hAVGPri/5NEv24rvDwXoH5pjPXUBCpA=
github.com/docker/machine v0.16.1-0.20190718054102-a555e4f7a8f5/go.mod h1:I8mPNDeK1uH+JTcUU7X0ZW8KiYz0jyAgNaeSJ1rCfDI= github.com/docker/machine v0.7.1-0.20190718054102-a555e4f7a8f5/go.mod h1:I8mPNDeK1uH+JTcUU7X0ZW8KiYz0jyAgNaeSJ1rCfDI=
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96 h1:cenwrSVm+Z7QLSV/BsnenAOcDXdX4cMv4wP0B/5QbPg= github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96 h1:cenwrSVm+Z7QLSV/BsnenAOcDXdX4cMv4wP0B/5QbPg=
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=

View File

@ -56,7 +56,7 @@ name: minikube
version: ${version} version: ${version}
website_url: https://github.com/kubernetes/minikube website_url: https://github.com/kubernetes/minikube
repo_url: https://github.com/kubernetes/minikube repo_url: https://github.com/kubernetes/minikube
documentation_url: https://github.com/kubernetes/minikube/blob/master/docs/README.md documentation_url: https://minikube.sigs.k8s.io/docs/
product_logo_url: https://raw.githubusercontent.com/kubernetes/minikube/master/images/logo/logo.svg product_logo_url: https://raw.githubusercontent.com/kubernetes/minikube/master/images/logo/logo.svg
type: installer type: installer
description: minikube runs a local Kubernetes cluster on macOS, Linux, and Windows. description: minikube runs a local Kubernetes cluster on macOS, Linux, and Windows.

View File

@ -49,8 +49,8 @@ git diff ${ghprbActualCommit} --name-only \
| grep -q deploy/iso/minikube && rebuild=1 || rebuild=0 | grep -q deploy/iso/minikube && rebuild=1 || rebuild=0
if [[ "${rebuild}" -eq 1 ]]; then if [[ "${rebuild}" -eq 1 ]]; then
echo "ISO changes detected ... rebuilding ISO" echo "ISO changes detected ... rebuilding ISO"
make release-iso make release-iso
fi fi
cp -r test/integration/testdata out/ cp -r test/integration/testdata out/

View File

@ -36,7 +36,7 @@ jobs=(
'Hyper-V_Windows' 'Hyper-V_Windows'
'VirtualBox_Linux' 'VirtualBox_Linux'
'VirtualBox_macOS' 'VirtualBox_macOS'
'VirtualBox_Windows' 'VirtualBox_Windows'
# 'KVM-GPU_Linux' - Disabled # 'KVM-GPU_Linux' - Disabled
'KVM_Linux' 'KVM_Linux'
'none_Linux' 'none_Linux'

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

View File

@ -40,9 +40,6 @@ import (
hyperkit "github.com/moby/hyperkit/go" hyperkit "github.com/moby/hyperkit/go"
"github.com/pkg/errors" "github.com/pkg/errors"
pkgdrivers "k8s.io/minikube/pkg/drivers" pkgdrivers "k8s.io/minikube/pkg/drivers"
"k8s.io/minikube/pkg/minikube/constants"
commonutil "k8s.io/minikube/pkg/util"
) )
const ( const (
@ -77,7 +74,6 @@ func NewDriver(hostName, storePath string) *Driver {
SSHUser: "docker", SSHUser: "docker",
}, },
CommonDriver: &pkgdrivers.CommonDriver{}, CommonDriver: &pkgdrivers.CommonDriver{},
DiskSize: commonutil.CalculateSizeInMB(constants.DefaultDiskSize),
} }
} }
@ -121,7 +117,7 @@ func (d *Driver) Create() error {
// DriverName returns the name of the driver // DriverName returns the name of the driver
func (d *Driver) DriverName() string { func (d *Driver) DriverName() string {
return constants.DriverHyperkit return "hyperkit"
} }
// GetSSHHostname returns hostname for use with ssh // GetSSHHostname returns hostname for use with ssh
@ -227,7 +223,7 @@ func (d *Driver) Start() error {
h.Memory = d.Memory h.Memory = d.Memory
h.UUID = d.UUID h.UUID = d.UUID
// This should stream logs from hyperkit, but doesn't seem to work. // This should stream logs from hyperkit, but doesn't seem to work.
logger := golog.New(os.Stderr, constants.DriverHyperkit, golog.LstdFlags) logger := golog.New(os.Stderr, "hyperkit", golog.LstdFlags)
h.SetLogger(logger) h.SetLogger(logger)
if vsockPorts, err := d.extractVSockPorts(); err != nil { if vsockPorts, err := d.extractVSockPorts(); err != nil {
@ -269,12 +265,25 @@ func (d *Driver) Start() error {
d.IPAddress, err = GetIPAddressByMACAddress(mac) d.IPAddress, err = GetIPAddressByMACAddress(mac)
if err != nil { if err != nil {
return &commonutil.RetriableError{Err: err} return &tempError{err}
} }
return nil return nil
} }
if err := commonutil.RetryAfter(30, getIP, 2*time.Second); err != nil { // Implement a retry loop without calling any minikube code
for i := 0; i < 30; i++ {
log.Debugf("Attempt %d", i)
err = getIP()
if err == nil {
break
}
if _, ok := err.(*tempError); !ok {
return err
}
time.Sleep(2 * time.Second)
}
if err != nil {
return fmt.Errorf("IP address never found in dhcp leases file %v", err) return fmt.Errorf("IP address never found in dhcp leases file %v", err)
} }
log.Debugf("IP: %s", d.IPAddress) log.Debugf("IP: %s", d.IPAddress)
@ -294,6 +303,14 @@ func (d *Driver) Start() error {
return nil return nil
} }
type tempError struct {
Err error
}
func (t tempError) Error() string {
return "Temporary error: " + t.Err.Error()
}
//recoverFromUncleanShutdown searches for an existing hyperkit.pid file in //recoverFromUncleanShutdown searches for an existing hyperkit.pid file in
//the machine directory. If it can't find it, a clean shutdown is assumed. //the machine directory. If it can't find it, a clean shutdown is assumed.
//If it finds the pid file, it checks for a running hyperkit process with that pid //If it finds the pid file, it checks for a running hyperkit process with that pid

View File

@ -110,7 +110,7 @@ func getPassthroughableNVIDIADevices() ([]string, error) {
return []string{}, fmt.Errorf("error reading %q: %v", sysKernelIOMMUGroupsPath, err) return []string{}, fmt.Errorf("error reading %q: %v", sysKernelIOMMUGroupsPath, err)
} }
if len(iommuGroups) == 0 { if len(iommuGroups) == 0 {
return []string{}, fmt.Errorf("no IOMMU groups found at %q. Make sure your host supports IOMMU. See instructions at https://github.com/kubernetes/minikube/blob/master/docs/gpu.md", sysKernelIOMMUGroupsPath) return []string{}, fmt.Errorf("no IOMMU groups found at %q. Make sure your host supports IOMMU. See instructions at https://minikube.sigs.k8s.io/docs/tutorials/nvidia_gpu/", sysKernelIOMMUGroupsPath)
} }
// Get list of PCI devices // Get list of PCI devices
@ -146,7 +146,7 @@ func getPassthroughableNVIDIADevices() ([]string, error) {
return []string{}, fmt.Errorf("no NVIDIA devices found") return []string{}, fmt.Errorf("no NVIDIA devices found")
} }
if len(unboundNVIDIADevices) == 0 { if len(unboundNVIDIADevices) == 0 {
return []string{}, fmt.Errorf("some NVIDIA devices were found but none of them were unbound. See instructions at https://github.com/kubernetes/minikube/blob/master/docs/gpu.md") return []string{}, fmt.Errorf("some NVIDIA devices were found but none of them were unbound. See instructions at https://minikube.sigs.k8s.io/docs/tutorials/nvidia_gpu/")
} }
// Make sure all the unbound devices are in IOMMU groups that only contain unbound devices. // Make sure all the unbound devices are in IOMMU groups that only contain unbound devices.
@ -161,7 +161,7 @@ func getPassthroughableNVIDIADevices() ([]string, error) {
} }
} }
if len(isolatedNVIDIADevices) == 0 { if len(isolatedNVIDIADevices) == 0 {
return []string{}, fmt.Errorf("some unbound NVIDIA devices were found but they had other devices in their IOMMU group that were bound. See instructoins at https://github.com/kubernetes/minikube/blob/master/docs/gpu.md") return []string{}, fmt.Errorf("some unbound NVIDIA devices were found but they had other devices in their IOMMU group that were bound. See instructoins at https://minikube.sigs.k8s.io/docs/tutorials/nvidia_gpu/")
} }
return isolatedNVIDIADevices, nil return isolatedNVIDIADevices, nil

View File

@ -25,10 +25,6 @@ import (
"syscall" "syscall"
"time" "time"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/util"
"github.com/docker/machine/libmachine/drivers" "github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log" "github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/state" "github.com/docker/machine/libmachine/state"
@ -102,14 +98,8 @@ func NewDriver(hostName, storePath string) *Driver {
SSHUser: "docker", SSHUser: "docker",
}, },
CommonDriver: &pkgdrivers.CommonDriver{}, CommonDriver: &pkgdrivers.CommonDriver{},
Boot2DockerURL: constants.DefaultISOURL,
CPU: constants.DefaultCPUS,
DiskSize: util.CalculateSizeInMB(constants.DefaultDiskSize),
Memory: util.CalculateSizeInMB(constants.DefaultMemorySize),
PrivateNetwork: defaultPrivateNetworkName, PrivateNetwork: defaultPrivateNetworkName,
Network: defaultNetworkName, Network: defaultNetworkName,
DiskPath: filepath.Join(constants.GetMinipath(), "machines", config.GetMachineName(), fmt.Sprintf("%s.rawdisk", config.GetMachineName())),
ISO: filepath.Join(constants.GetMinipath(), "machines", config.GetMachineName(), "boot2docker.iso"),
ConnectionURI: qemusystem, ConnectionURI: qemusystem,
} }
} }
@ -224,7 +214,7 @@ func (d *Driver) GetSSHHostname() (string, error) {
// DriverName returns the name of the driver // DriverName returns the name of the driver
func (d *Driver) DriverName() string { func (d *Driver) DriverName() string {
return constants.DriverKvm2 return "kvm2"
} }
// Kill stops a host forcefully, including any containers that we are managing. // Kill stops a host forcefully, including any containers that we are managing.

View File

@ -44,7 +44,7 @@ var cleanupPaths = []string{
} }
// Driver is a driver designed to run kubeadm w/o VM management, and assumes systemctl. // Driver is a driver designed to run kubeadm w/o VM management, and assumes systemctl.
// https://github.com/kubernetes/minikube/blob/master/docs/vmdriver-none.md // https://minikube.sigs.k8s.io/docs/reference/drivers/none/
type Driver struct { type Driver struct {
*drivers.BaseDriver *drivers.BaseDriver
*pkgdrivers.CommonDriver *pkgdrivers.CommonDriver

View File

@ -32,6 +32,7 @@ import (
"k8s.io/minikube/pkg/minikube/command" "k8s.io/minikube/pkg/minikube/command"
"k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/util" "k8s.io/minikube/pkg/util"
) )
@ -64,7 +65,7 @@ func SetupCerts(cmd command.Runner, k8s config.KubernetesConfig) error {
copyableFiles = append(copyableFiles, certFile) copyableFiles = append(copyableFiles, certFile)
} }
kubeCfgSetup := &util.KubeConfigSetup{ kcs := &kubeconfig.Settings{
ClusterName: k8s.NodeName, ClusterName: k8s.NodeName,
ClusterServerAddress: fmt.Sprintf("https://localhost:%d", k8s.NodePort), ClusterServerAddress: fmt.Sprintf("https://localhost:%d", k8s.NodePort),
ClientCertificate: path.Join(constants.GuestCertsDir, "apiserver.crt"), ClientCertificate: path.Join(constants.GuestCertsDir, "apiserver.crt"),
@ -74,7 +75,7 @@ func SetupCerts(cmd command.Runner, k8s config.KubernetesConfig) error {
} }
kubeCfg := api.NewConfig() kubeCfg := api.NewConfig()
err := util.PopulateKubeConfig(kubeCfgSetup, kubeCfg) err := kubeconfig.PopulateFromSettings(kcs, kubeCfg)
if err != nil { if err != nil {
return errors.Wrap(err, "populating kubeconfig") return errors.Wrap(err, "populating kubeconfig")
} }

View File

@ -587,7 +587,7 @@ func generateConfig(k8s config.KubernetesConfig, r cruntime.Manager) ([]byte, er
// In case of no port assigned, use util.APIServerPort // In case of no port assigned, use util.APIServerPort
nodePort := k8s.NodePort nodePort := k8s.NodePort
if nodePort <= 0 { if nodePort <= 0 {
nodePort = util.APIServerPort nodePort = constants.APIServerPort
} }
opts := struct { opts := struct {

View File

@ -414,7 +414,7 @@ func createHost(api libmachine.API, config cfg.MachineConfig) (*host.Host, error
if config.VMDriver == constants.DriverVmwareFusion && viper.GetBool(cfg.ShowDriverDeprecationNotification) { if config.VMDriver == constants.DriverVmwareFusion && viper.GetBool(cfg.ShowDriverDeprecationNotification) {
out.WarningT(`The vmwarefusion driver is deprecated and support for it will be removed in a future release. out.WarningT(`The vmwarefusion driver is deprecated and support for it will be removed in a future release.
Please consider switching to the new vmware unified driver, which is intended to replace the vmwarefusion driver. Please consider switching to the new vmware unified driver, which is intended to replace the vmwarefusion driver.
See https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#vmware-unified-driver for more information. See https://minikube.sigs.k8s.io/docs/reference/drivers/vmware/ for more information.
To disable this message, run [minikube config set ShowDriverDeprecationNotification false]`) To disable this message, run [minikube config set ShowDriverDeprecationNotification false]`)
} }
if !localDriver(config.VMDriver) { if !localDriver(config.VMDriver) {

View File

@ -21,9 +21,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"os"
"io/ioutil" "io/ioutil"
"os"
"github.com/spf13/viper" "github.com/spf13/viper"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
@ -152,10 +151,10 @@ type simpleConfigLoader struct{}
// DefaultLoader is the default config loader // DefaultLoader is the default config loader
var DefaultLoader Loader = &simpleConfigLoader{} var DefaultLoader Loader = &simpleConfigLoader{}
func (c *simpleConfigLoader) LoadConfigFromFile(profile string, miniHome ...string) (*Config, error) { func (c *simpleConfigLoader) LoadConfigFromFile(profileName string, miniHome ...string) (*Config, error) {
var cc Config var cc Config
// Move to profile package
path := constants.GetProfileFile(profile, miniHome...) path := profileFilePath(profileName, miniHome...)
if _, err := os.Stat(path); os.IsNotExist(err) { if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err return nil, err

View File

@ -17,9 +17,12 @@ limitations under the License.
package config package config
import ( import (
"encoding/json"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"github.com/golang/glog"
"k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/constants"
) )
@ -34,6 +37,76 @@ func (p *Profile) isValid() bool {
return true return true
} }
// ProfileExists returns true if there is a profile config (regardless of being valid)
func ProfileExists(name string, miniHome ...string) bool {
miniPath := constants.GetMinipath()
if len(miniHome) > 0 {
miniPath = miniHome[0]
}
p := profileFilePath(name, miniPath)
_, err := os.Stat(p)
return err == nil
}
// CreateProfile creates an empty profile stores in $MINIKUBE_HOME/profiles/<profilename>/config.json
func CreateEmptyProfile(name string, miniHome ...string) error {
cfg := &Config{}
return CreateProfile(name, cfg, miniHome...)
}
// CreateProfile creates an profile out of the cfg and stores in $MINIKUBE_HOME/profiles/<profilename>/config.json
func CreateProfile(name string, cfg *Config, miniHome ...string) error {
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
glog.Infof("Saving config:\n%s", data)
path := profileFilePath(name, miniHome...)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
// If no config file exists, don't worry about swapping paths
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := ioutil.WriteFile(path, data, 0600); err != nil {
return err
}
return nil
}
tf, err := ioutil.TempFile(filepath.Dir(path), "config.json.tmp")
if err != nil {
return err
}
defer os.Remove(tf.Name())
if err = ioutil.WriteFile(tf.Name(), data, 0600); err != nil {
return err
}
if err = tf.Close(); err != nil {
return err
}
if err = os.Remove(path); err != nil {
return err
}
if err = os.Rename(tf.Name(), path); err != nil {
return err
}
return nil
}
func DeleteProfile(profile string, miniHome ...string) error {
miniPath := constants.GetMinipath()
if len(miniHome) > 0 {
miniPath = miniHome[0]
}
return os.RemoveAll(profileFolderPath(profile, miniPath))
}
// ListProfiles returns all valid and invalid (if any) minikube profiles // 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 are the profiles that have a directory or config file but not usable
// invalidPs would be suggeted to be deleted // invalidPs would be suggeted to be deleted
@ -82,3 +155,22 @@ func profileDirs(miniHome ...string) (dirs []string, err error) {
} }
return dirs, err return dirs, err
} }
// profileFilePath returns the Minikube profile config file
func profileFilePath(profile string, miniHome ...string) string {
miniPath := constants.GetMinipath()
if len(miniHome) > 0 {
miniPath = miniHome[0]
}
return filepath.Join(miniPath, "profiles", profile, "config.json")
}
// profileFolderPath returns path of profile folder
func profileFolderPath(profile string, miniHome ...string) string {
miniPath := constants.GetMinipath()
if len(miniHome) > 0 {
miniPath = miniHome[0]
}
return filepath.Join(miniPath, "profiles", profile)
}

View File

@ -21,6 +21,7 @@ import (
"testing" "testing"
) )
// TestListProfiles uses a different uses different MINIKUBE_HOME with rest of tests since it relies on file list index
func TestListProfiles(t *testing.T) { func TestListProfiles(t *testing.T) {
miniDir, err := filepath.Abs("./testdata/.minikube") miniDir, err := filepath.Abs("./testdata/.minikube")
if err != nil { if err != nil {
@ -70,3 +71,124 @@ func TestListProfiles(t *testing.T) {
t.Errorf("error listing profiles %v", err) t.Errorf("error listing profiles %v", err)
} }
} }
func TestProfileExists(t *testing.T) {
miniDir, err := filepath.Abs("./testdata/.minikube2")
if err != nil {
t.Errorf("error getting dir path for ./testdata/.minikube : %v", err)
}
var testCases = []struct {
name string
expected bool
}{
{"p1", true},
{"p2", true},
{"p3_empty", true},
{"p4_invalid_file", true},
{"p5_partial_config", true},
{"p6_no_file", false},
}
for _, tt := range testCases {
got := ProfileExists(tt.name, miniDir)
if got != tt.expected {
t.Errorf("expected ProfileExists(%q,%q)=%t but got %t ", tt.name, miniDir, tt.expected, got)
}
}
}
func TestCreateEmptyProfile(t *testing.T) {
miniDir, err := filepath.Abs("./testdata/.minikube2")
if err != nil {
t.Errorf("error getting dir path for ./testdata/.minikube : %v", err)
}
var testCases = []struct {
name string
expectErr bool
}{
{"p13", false},
{"p_13", false},
}
for _, tc := range testCases {
n := tc.name // capturing loop variable
gotErr := CreateEmptyProfile(n, miniDir)
if gotErr != nil && tc.expectErr == false {
t.Errorf("expected CreateEmptyProfile not to error but got err=%v", gotErr)
}
defer func() { // tear down
err := DeleteProfile(n, miniDir)
if err != nil {
t.Errorf("error test tear down %v", err)
}
}()
}
}
func TestCreateProfile(t *testing.T) {
miniDir, err := filepath.Abs("./testdata/.minikube2")
if err != nil {
t.Errorf("error getting dir path for ./testdata/.minikube : %v", err)
}
var testCases = []struct {
name string
cfg *Config
expectErr bool
}{
{"p_empty_config", &Config{}, false},
{"p_partial_config", &Config{KubernetesConfig: KubernetesConfig{
ShouldLoadCachedImages: false}}, false},
{"p_partial_config2", &Config{MachineConfig: MachineConfig{
KeepContext: false}, KubernetesConfig: KubernetesConfig{
ShouldLoadCachedImages: false}}, false},
}
for _, tc := range testCases {
n := tc.name // capturing loop variable
gotErr := CreateProfile(n, tc.cfg, miniDir)
if gotErr != nil && tc.expectErr == false {
t.Errorf("expected CreateEmptyProfile not to error but got err=%v", gotErr)
}
defer func() { // tear down
err := DeleteProfile(n, miniDir)
if err != nil {
t.Errorf("error test tear down %v", err)
}
}()
}
}
func TestDeleteProfile(t *testing.T) {
miniDir, err := filepath.Abs("./testdata/.minikube2")
if err != nil {
t.Errorf("error getting dir path for ./testdata/.minikube : %v", err)
}
err = CreateEmptyProfile("existing_prof", miniDir)
if err != nil {
t.Errorf("error setting up TestDeleteProfile %v", err)
}
var testCases = []struct {
name string
expectErr bool
}{
{"existing_prof", false},
{"non_existing_prof", false},
}
for _, tc := range testCases {
gotErr := DeleteProfile(tc.name, miniDir)
if gotErr != nil && tc.expectErr == false {
t.Errorf("expected CreateEmptyProfile not to error but got err=%v", gotErr)
}
}
}

View File

@ -0,0 +1,50 @@
{
"MachineConfig": {
"KeepContext": false,
"MinikubeISO": "https://storage.googleapis.com/minikube/iso/minikube-v1.2.0.iso",
"Memory": 2000,
"CPUs": 2,
"DiskSize": 20000,
"VMDriver": "hyperkit",
"ContainerRuntime": "docker",
"HyperkitVpnKitSock": "",
"HyperkitVSockPorts": [],
"XhyveDiskDriver": "ahci-hd",
"DockerEnv": null,
"InsecureRegistry": null,
"RegistryMirror": null,
"HostOnlyCIDR": "192.168.99.1/24",
"HypervVirtualSwitch": "",
"KVMNetwork": "default",
"KVMQemuURI": "qemu:///system",
"KVMGPU": false,
"KVMHidden": false,
"DockerOpt": null,
"DisableDriverMounts": false,
"NFSShare": [],
"NFSSharesRoot": "/nfsshares",
"UUID": "",
"NoVTXCheck": false,
"DNSProxy": false,
"HostDNSResolver": true
},
"KubernetesConfig": {
"KubernetesVersion": "v1.15.0",
"NodeIP": "192.168.64.75",
"NodePort": 8443,
"NodeName": "minikube",
"APIServerName": "minikubeCA",
"APIServerNames": null,
"APIServerIPs": null,
"DNSDomain": "cluster.local",
"ContainerRuntime": "docker",
"CRISocket": "",
"NetworkPlugin": "",
"FeatureGates": "",
"ServiceCIDR": "10.96.0.0/12",
"ImageRepository": "",
"ExtraOptions": null,
"ShouldLoadCachedImages": true,
"EnableDefaultCNI": false
}
}

View File

@ -0,0 +1,49 @@
{
"MachineConfig": {
"KeepContext": false,
"MinikubeISO": "https://storage.googleapis.com/minikube/iso/minikube-v1.2.0.iso",
"Memory": 2000,
"CPUs": 2,
"DiskSize": 20000,
"VMDriver": "virtualbox",
"ContainerRuntime": "docker",
"HyperkitVpnKitSock": "",
"HyperkitVSockPorts": [],
"DockerEnv": null,
"InsecureRegistry": null,
"RegistryMirror": null,
"HostOnlyCIDR": "192.168.99.1/24",
"HypervVirtualSwitch": "",
"KVMNetwork": "default",
"KVMQemuURI": "qemu:///system",
"KVMGPU": false,
"KVMHidden": false,
"DockerOpt": null,
"DisableDriverMounts": false,
"NFSShare": [],
"NFSSharesRoot": "/nfsshares",
"UUID": "",
"NoVTXCheck": false,
"DNSProxy": false,
"HostDNSResolver": true
},
"KubernetesConfig": {
"KubernetesVersion": "v1.15.0",
"NodeIP": "192.168.99.136",
"NodePort": 8443,
"NodeName": "minikube",
"APIServerName": "minikubeCA",
"APIServerNames": null,
"APIServerIPs": null,
"DNSDomain": "cluster.local",
"ContainerRuntime": "docker",
"CRISocket": "",
"NetworkPlugin": "",
"FeatureGates": "",
"ServiceCIDR": "10.96.0.0/12",
"ImageRepository": "",
"ExtraOptions": null,
"ShouldLoadCachedImages": true,
"EnableDefaultCNI": false
}
}

View File

@ -0,0 +1 @@
invalid json file :)

View File

@ -0,0 +1,47 @@
{
"MachineConfig": {
"KeepContext": false,
"MinikubeISO": "https://storage.googleapis.com/minikube/iso/minikube-v1.2.0.iso",
"Memory": 2000,
"CPUs": 2,
"DiskSize": 20000,
"ContainerRuntime": "docker",
"HyperkitVpnKitSock": "",
"HyperkitVSockPorts": [],
"XhyveDiskDriver": "ahci-hd",
"DockerEnv": null,
"InsecureRegistry": null,
"RegistryMirror": null,
"HostOnlyCIDR": "192.168.99.1/24",
"HypervVirtualSwitch": "",
"KVMNetwork": "default",
"KVMQemuURI": "qemu:///system",
"KVMGPU": false,
"KVMHidden": false,
"DockerOpt": null,
"DisableDriverMounts": false,
"NFSShare": [],
"NFSSharesRoot": "/nfsshares",
"UUID": "",
"NoVTXCheck": false,
"DNSProxy": false,
"HostDNSResolver": true
},
"KubernetesConfig": {
"NodePort": 8443,
"NodeName": "minikube",
"APIServerName": "minikubeCA",
"APIServerNames": null,
"APIServerIPs": null,
"DNSDomain": "cluster.local",
"ContainerRuntime": "docker",
"CRISocket": "",
"NetworkPlugin": "",
"FeatureGates": "",
"ServiceCIDR": "10.96.0.0/12",
"ImageRepository": "",
"ExtraOptions": null,
"ShouldLoadCachedImages": true,
"EnableDefaultCNI": false
}
}

View File

@ -37,6 +37,7 @@ type Config struct {
// MachineConfig contains the parameters used to start a cluster. // MachineConfig contains the parameters used to start a cluster.
type MachineConfig struct { type MachineConfig struct {
KeepContext bool // used by start and profile command to or not to switch kubectl's current context KeepContext bool // used by start and profile command to or not to switch kubectl's current context
EmbedCerts bool // used by kubeconfig.Setup
MinikubeISO string MinikubeISO string
Memory int Memory int
CPUs int CPUs int

View File

@ -31,8 +31,8 @@ import (
minikubeVersion "k8s.io/minikube/pkg/version" minikubeVersion "k8s.io/minikube/pkg/version"
) )
// APIServerPort is the port that the API server should listen on.
const ( const (
APIServerPort = 8443
APIServerName = "minikubeCA" APIServerName = "minikubeCA"
ClusterDNSDomain = "cluster.local" ClusterDNSDomain = "cluster.local"
) )
@ -129,6 +129,8 @@ func MakeMiniPath(fileName ...string) string {
var MountProcessFileName = ".mount-process" var MountProcessFileName = ".mount-process"
const ( const (
// DefaultEmbedCerts is if the certs should be embedded in the kubeconfig file
DefaultEmbedCerts = false
// DefaultKeepContext is if we should keep context by default // DefaultKeepContext is if we should keep context by default
DefaultKeepContext = false DefaultKeepContext = false
// SHASuffix is the suffix of a SHA-256 checksum file // SHASuffix is the suffix of a SHA-256 checksum file
@ -208,6 +210,12 @@ func GetProfilePath(profile string, miniHome ...string) string {
return filepath.Join(miniPath, "profiles", profile) return filepath.Join(miniPath, "profiles", profile)
} }
// AddonsPath is the default path of the addons configuration
const AddonsPath = "/etc/kubernetes/addons"
// FilesPath is the default path of files
const FilesPath = "/files"
const ( const (
// KubeletServiceFile is the path to the kubelet systemd service // KubeletServiceFile is the path to the kubelet systemd service
KubeletServiceFile = "/lib/systemd/system/kubelet.service" KubeletServiceFile = "/lib/systemd/system/kubelet.service"
@ -421,5 +429,5 @@ const (
const ( const (
// DriverDocumentation the documentation of the KVM driver // DriverDocumentation the documentation of the KVM driver
DriverDocumentation = "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md" DriverDocumentation = "https://minikube.sigs.k8s.io/docs/reference/drivers/"
) )

View File

@ -35,16 +35,15 @@ import (
// blacklist is a list of strings to explicitly omit from translation files. // blacklist is a list of strings to explicitly omit from translation files.
var blacklist = []string{ var blacklist = []string{
"%s: %v", "{{.error}}",
"%s.%s=%s", "{{.url}}",
"%s/%d", "{{.msg}}: {{.err}}",
"%s=%s", "{{.key}}={{.value}}",
"%v", "opt {{.docker_option}}",
"GID: %s", "kube-system",
"MSize: %d", "env {{.docker_env}}",
"UID: %s", "\\n",
"env %s", "==\u003e {{.name}} \u003c==",
"opt %s",
} }
// ErrMapFile is a constant to refer to the err_map file, which contains the Advice strings. // ErrMapFile is a constant to refer to the err_map file, which contains the Advice strings.
@ -194,6 +193,11 @@ func checkNode(stmt ast.Node, e *state) {
if expr, ok := stmt.(*ast.CallExpr); ok { if expr, ok := stmt.(*ast.CallExpr); ok {
checkCallExpression(expr, e) checkCallExpression(expr, e)
} }
// Check all key value pairs for possible help text
if kvp, ok := stmt.(*ast.KeyValueExpr); ok {
checkKeyValueExpression(kvp, e)
}
} }
// checkCallExpression takes a function call, and checks its arguments for strings // checkCallExpression takes a function call, and checks its arguments for strings
@ -216,6 +220,10 @@ func checkCallExpression(s *ast.CallExpr, e *state) {
// Parse out the package of the call // Parse out the package of the call
sfi, ok := sf.X.(*ast.Ident) sfi, ok := sf.X.(*ast.Ident)
if !ok { if !ok {
if sfc, ok := sf.X.(*ast.CallExpr); ok {
extractFlagHelpText(s, sfc, e)
return
}
return return
} }
packageName = sfi.Name packageName = sfi.Name
@ -242,12 +250,14 @@ func checkCallExpression(s *ast.CallExpr, e *state) {
checkArguments(s, e) checkArguments(s, e)
} }
// checkArguments checks the arguments of a function call for strings
func checkArguments(s *ast.CallExpr, e *state) { func checkArguments(s *ast.CallExpr, e *state) {
matched := false matched := false
for _, arg := range s.Args { for _, arg := range s.Args {
// This argument is an identifier. // This argument is an identifier.
if i, ok := arg.(*ast.Ident); ok { if i, ok := arg.(*ast.Ident); ok {
if checkIdentForStringValue(i, e) { if s := checkIdentForStringValue(i); s != "" {
e.translations[s] = ""
matched = true matched = true
break break
} }
@ -255,13 +265,15 @@ func checkArguments(s *ast.CallExpr, e *state) {
// This argument is a string. // This argument is a string.
if argString, ok := arg.(*ast.BasicLit); ok { if argString, ok := arg.(*ast.BasicLit); ok {
if addStringToList(argString.Value, e) { if s := checkString(argString.Value); s != "" {
e.translations[s] = ""
matched = true matched = true
break break
} }
} }
} }
// No string arguments were found, check everything the calls this function for strings
if !matched { if !matched {
addParentFuncToList(e) addParentFuncToList(e)
} }
@ -269,38 +281,47 @@ func checkArguments(s *ast.CallExpr, e *state) {
} }
// checkIdentForStringValye takes a identifier and sees if it's a variable assigned to a string // checkIdentForStringValye takes a identifier and sees if it's a variable assigned to a string
func checkIdentForStringValue(i *ast.Ident, e *state) bool { func checkIdentForStringValue(i *ast.Ident) string {
// This identifier is nil // This identifier is nil
if i.Obj == nil { if i.Obj == nil {
return false return ""
} }
as, ok := i.Obj.Decl.(*ast.AssignStmt) var s string
// This identifier was directly assigned a value
if as, ok := i.Obj.Decl.(*ast.AssignStmt); ok {
if rhs, ok := as.Rhs[0].(*ast.BasicLit); ok {
s = rhs.Value
}
// This identifier wasn't assigned anything
if !ok {
return false
} }
rhs, ok := as.Rhs[0].(*ast.BasicLit) // This Identifier is part of the const or var declaration
if vs, ok := i.Obj.Decl.(*ast.ValueSpec); ok {
// This identifier was not assigned a string/basic value for j, n := range vs.Names {
if !ok { if n.Name == i.Name {
return false if len(vs.Values) < j+1 {
// There's no way anything was assigned here, abort
return ""
}
if v, ok := vs.Values[j].(*ast.BasicLit); ok {
s = v.Value
break
}
}
}
} }
if addStringToList(rhs.Value, e) { return checkString(s)
return true
}
return false
} }
// addStringToList takes a string, makes sure it's meant to be translated then adds it to the list if so // checkString checks if a string is meant to be translated
func addStringToList(s string, e *state) bool { func checkString(s string) string {
// Empty strings don't need translating // Empty strings don't need translating
if len(s) <= 2 { if len(s) <= 2 {
return false return ""
} }
// Parse out quote marks // Parse out quote marks
@ -308,29 +329,108 @@ func addStringToList(s string, e *state) bool {
// Don't translate integers // Don't translate integers
if _, err := strconv.Atoi(stringToTranslate); err == nil { if _, err := strconv.Atoi(stringToTranslate); err == nil {
return false return ""
} }
// Don't translate URLs // Don't translate URLs
if u, err := url.Parse(stringToTranslate); err == nil && u.Scheme != "" && u.Host != "" { if u, err := url.Parse(stringToTranslate); err == nil && u.Scheme != "" && u.Host != "" {
return false return ""
} }
// Don't translate commands // Don't translate commands
if strings.HasPrefix(stringToTranslate, "sudo ") { if strings.HasPrefix(stringToTranslate, "sudo ") {
return false return ""
} }
// Don't translate blacklisted strings // Don't translate blacklisted strings
for _, b := range blacklist { for _, b := range blacklist {
if b == stringToTranslate { if b == stringToTranslate {
return false return ""
} }
} }
// Hooray, we can translate the string! // Hooray, we can translate the string!
e.translations[stringToTranslate] = "" return stringToTranslate
return true }
// checkKeyValueExpression checks all kvps for help text
func checkKeyValueExpression(kvp *ast.KeyValueExpr, e *state) {
// The key must be an identifier
i, ok := kvp.Key.(*ast.Ident)
if !ok {
return
}
// Specifically, it needs to be "Short" or "Long"
if i.Name == "Short" || i.Name == "Long" {
// The help text is directly a string, the most common case
if help, ok := kvp.Value.(*ast.BasicLit); ok {
s := checkString(help.Value)
if s != "" {
e.translations[s] = ""
}
}
// The help text is assigned to a variable, only happens if it's very long
if help, ok := kvp.Value.(*ast.Ident); ok {
s := checkIdentForStringValue(help)
if s != "" {
e.translations[s] = ""
}
}
// Ok now this is just a mess
if help, ok := kvp.Value.(*ast.BinaryExpr); ok {
s := checkBinaryExpression(help, e)
if s != "" {
e.translations[s] = ""
}
}
}
}
// checkBinaryExpression checks binary expressions, stuff of the form x + y, for strings and concats them
func checkBinaryExpression(b *ast.BinaryExpr, e *state) string {
// Check the left side
var s string
if l, ok := b.X.(*ast.BasicLit); ok {
if x := checkString(l.Value); x != "" {
s += x
}
}
if i, ok := b.X.(*ast.Ident); ok {
if x := checkIdentForStringValue(i); x != "" {
s += x
}
}
if b1, ok := b.X.(*ast.BinaryExpr); ok {
if x := checkBinaryExpression(b1, e); x != "" {
s += x
}
}
//Check the right side
if l, ok := b.Y.(*ast.BasicLit); ok {
if x := checkString(l.Value); x != "" {
s += x
}
}
if i, ok := b.Y.(*ast.Ident); ok {
if x := checkIdentForStringValue(i); x != "" {
s += x
}
}
if b1, ok := b.Y.(*ast.BinaryExpr); ok {
if x := checkBinaryExpression(b1, e); x != "" {
s += x
}
}
return s
} }
// writeStringsToFiles writes translations to all translation files in output // writeStringsToFiles writes translations to all translation files in output
@ -411,10 +511,37 @@ func extractAdvice(f ast.Node, e *state) error {
if i.Name == "Advice" { if i.Name == "Advice" {
// At this point we know the value in the kvp is guaranteed to be a string // At this point we know the value in the kvp is guaranteed to be a string
advice, _ := kvp.Value.(*ast.BasicLit) advice, _ := kvp.Value.(*ast.BasicLit)
addStringToList(advice.Value, e) s := checkString(advice.Value)
if s != "" {
e.translations[s] = ""
}
} }
return true return true
}) })
return nil return nil
} }
// extractFlagHelpText finds usage text for all command flags and adds them to the list to translate
func extractFlagHelpText(c *ast.CallExpr, sfc *ast.CallExpr, e *state) {
// We're looking for calls of the form cmd.Flags().VarP()
flags, ok := sfc.Fun.(*ast.SelectorExpr)
if !ok {
return
}
if flags.Sel.Name != "Flags" || len(c.Args) == 1 {
return
}
// The usage text for flags is always the final argument in the Flags() call
usage, ok := c.Args[len(c.Args)-1].(*ast.BasicLit)
if !ok {
// Something has gone wrong, abort
return
}
s := checkString(usage.Value)
if s != "" {
e.translations[s] = ""
}
}

View File

@ -0,0 +1,93 @@
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubeconfig
import (
"github.com/golang/glog"
"github.com/pkg/errors"
"k8s.io/client-go/tools/clientcmd/api"
)
// UnsetCurrentContext unsets the current-context from minikube to "" on minikube stop
func UnsetCurrentContext(machineName string, configPath ...string) error {
fPath := PathFromEnv()
if configPath != nil {
fPath = configPath[0]
}
kCfg, err := readOrNew(fPath)
if err != nil {
return errors.Wrap(err, "Error getting kubeconfig status")
}
// Unset current-context only if profile is the current-context
if kCfg.CurrentContext == machineName {
kCfg.CurrentContext = ""
if err := writeToFile(kCfg, fPath); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}
return nil
}
// SetCurrentContext sets the kubectl's current-context
func SetCurrentContext(name string, configPath ...string) error {
fPath := PathFromEnv()
if configPath != nil {
fPath = configPath[0]
}
kcfg, err := readOrNew(fPath)
if err != nil {
return errors.Wrap(err, "Error getting kubeconfig status")
}
kcfg.CurrentContext = name
if err := writeToFile(kcfg, fPath); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}
// DeleteContext deletes the specified machine's kubeconfig context
func DeleteContext(machineName string, configPath ...string) error {
fPath := PathFromEnv()
if configPath != nil {
fPath = configPath[0]
}
kcfg, err := readOrNew(fPath)
if err != nil {
return errors.Wrap(err, "Error getting kubeconfig status")
}
if kcfg == nil || api.IsConfigEmpty(kcfg) {
glog.V(2).Info("kubeconfig is empty")
return nil
}
delete(kcfg.Clusters, machineName)
delete(kcfg.AuthInfos, machineName)
delete(kcfg.Contexts, machineName)
if kcfg.CurrentContext == machineName {
kcfg.CurrentContext = ""
}
if err := writeToFile(kcfg, fPath); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}

View File

@ -0,0 +1,147 @@
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubeconfig
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestDeleteContext(t *testing.T) {
fn := tempFile(t, fakeKubeCfg)
if err := DeleteContext("la-croix", fn); err != nil {
t.Fatal(err)
}
cfg, err := readOrNew(fn)
if err != nil {
t.Fatal(err)
}
if len(cfg.AuthInfos) != 0 {
t.Fail()
}
if len(cfg.Clusters) != 0 {
t.Fail()
}
if len(cfg.Contexts) != 0 {
t.Fail()
}
}
func TestSetCurrentContext(t *testing.T) {
f, err := ioutil.TempFile("/tmp", "kubeconfig")
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
defer os.Remove(f.Name())
kcfg, err := readOrNew(f.Name())
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if kcfg.CurrentContext != "" {
t.Errorf("Expected empty context but got %v", kcfg.CurrentContext)
}
contextName := "minikube"
err = SetCurrentContext(contextName, f.Name())
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
defer func() {
err := UnsetCurrentContext(contextName, f.Name())
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
}()
kcfg, err = readOrNew(f.Name())
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if kcfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %v : ", contextName, kcfg.CurrentContext)
}
}
func TestUnsetCurrentContext(t *testing.T) {
fn := filepath.Join("testdata", "kubeconfig", "config1")
contextName := "minikube"
cfg, err := readOrNew(fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
err = UnsetCurrentContext(contextName, fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
defer func() {
err := SetCurrentContext(contextName, fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
}()
cfg, err = readOrNew(fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != "" {
t.Errorf("Expected empty context but got %v", cfg.CurrentContext)
}
}
func TestUnsetCurrentContextOnlyChangesIfProfileIsTheCurrentContext(t *testing.T) {
contextName := "minikube"
fn := filepath.Join("testdata", "kubeconfig", "config2")
cfg, err := readOrNew(fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
err = UnsetCurrentContext("differentContextName", fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
cfg, err = readOrNew(fn)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
}

View File

@ -0,0 +1,241 @@
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubeconfig
import (
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"github.com/golang/glog"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/tools/clientcmd/api/latest"
"k8s.io/minikube/pkg/minikube/constants"
pkgutil "k8s.io/minikube/pkg/util"
)
// IsClusterInConfig verifies the ip stored in kubeconfig.
func IsClusterInConfig(ip net.IP, clusterName string, configPath ...string) (bool, error) {
path := PathFromEnv()
if configPath != nil {
path = configPath[0]
}
if ip == nil {
return false, fmt.Errorf("error, empty ip passed")
}
kip, err := extractIP(clusterName, path)
if err != nil {
return false, err
}
if kip.Equal(ip) {
return true, nil
}
// Kubeconfig IP misconfigured
return false, nil
}
// Port returns the Port number stored for minikube in the kubeconfig specified
func Port(clusterName string, configPath ...string) (int, error) {
path := PathFromEnv()
if configPath != nil {
path = configPath[0]
}
cfg, err := readOrNew(path)
if err != nil {
return 0, errors.Wrap(err, "Error getting kubeconfig status")
}
cluster, ok := cfg.Clusters[clusterName]
if !ok {
return 0, errors.Errorf("Kubeconfig does not have a record of the machine cluster")
}
kurl, err := url.Parse(cluster.Server)
if err != nil {
return constants.APIServerPort, nil
}
_, kport, err := net.SplitHostPort(kurl.Host)
if err != nil {
return constants.APIServerPort, nil
}
port, err := strconv.Atoi(kport)
return port, err
}
// PathFromEnv() gets the path to the first kubeconfig
func PathFromEnv() string {
kubeConfigEnv := os.Getenv(constants.KubeconfigEnvVar)
if kubeConfigEnv == "" {
return constants.KubeconfigPath
}
return filepath.SplitList(kubeConfigEnv)[0]
}
// extractIP returns the IP address stored for minikube in the kubeconfig specified
func extractIP(machineName string, configPath ...string) (net.IP, error) {
path := PathFromEnv()
if configPath != nil {
path = configPath[0]
}
apiCfg, err := readOrNew(path)
if err != nil {
return nil, errors.Wrap(err, "Error getting kubeconfig status")
}
cluster, ok := apiCfg.Clusters[machineName]
if !ok {
return nil, errors.Errorf("Kubeconfig does not have a record of the machine cluster")
}
kurl, err := url.Parse(cluster.Server)
if err != nil {
return net.ParseIP(cluster.Server), nil
}
kip, _, err := net.SplitHostPort(kurl.Host)
if err != nil {
return net.ParseIP(kurl.Host), nil
}
ip := net.ParseIP(kip)
return ip, nil
}
// UpdateIP overwrites the IP stored in kubeconfig with the provided IP.
func UpdateIP(ip net.IP, machineName string, configPath ...string) (bool, error) {
path := PathFromEnv()
if configPath != nil {
path = configPath[0]
}
if ip == nil {
return false, fmt.Errorf("error, empty ip passed")
}
kip, err := extractIP(machineName, path)
if err != nil {
return false, err
}
if kip.Equal(ip) {
return false, nil
}
kport, err := Port(machineName, path)
if err != nil {
return false, err
}
cfg, err := readOrNew(path)
if err != nil {
return false, errors.Wrap(err, "Error getting kubeconfig status")
}
// Safe to lookup server because if field non-existent getIPFromKubeconfig would have given an error
cfg.Clusters[machineName].Server = "https://" + ip.String() + ":" + strconv.Itoa(kport)
err = writeToFile(cfg, path)
if err != nil {
return false, err
}
// Kubeconfig IP reconfigured
return true, nil
}
// writeToFile encodes the configuration and writes it to the given file.
// If the file exists, it's contents will be overwritten.
func writeToFile(config runtime.Object, configPath ...string) error {
fPath := PathFromEnv()
if configPath != nil {
fPath = configPath[0]
}
if config == nil {
glog.Errorf("could not write to '%s': config can't be nil", fPath)
}
// encode config to YAML
data, err := runtime.Encode(latest.Codec, config)
if err != nil {
return errors.Errorf("could not write to '%s': failed to encode config: %v", fPath, err)
}
// create parent dir if doesn't exist
dir := filepath.Dir(fPath)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0755); err != nil {
return errors.Wrapf(err, "Error creating directory: %s", dir)
}
}
// write with restricted permissions
if err := ioutil.WriteFile(fPath, data, 0600); err != nil {
return errors.Wrapf(err, "Error writing file %s", fPath)
}
if err := pkgutil.MaybeChownDirRecursiveToMinikubeUser(dir); err != nil {
return errors.Wrapf(err, "Error recursively changing ownership for dir: %s", dir)
}
return nil
}
// readOrNew retrieves Kubernetes client configuration from a file.
// If no files exists, an empty configuration is returned.
func readOrNew(configPath ...string) (*api.Config, error) {
fPath := PathFromEnv()
if configPath != nil {
fPath = configPath[0]
}
data, err := ioutil.ReadFile(fPath)
if os.IsNotExist(err) {
return api.NewConfig(), nil
} else if err != nil {
return nil, errors.Wrapf(err, "Error reading file %q", fPath)
}
// decode config, empty if no bytes
kcfg, err := decode(data)
if err != nil {
return nil, errors.Errorf("could not read config: %v", err)
}
// initialize nil maps
if kcfg.AuthInfos == nil {
kcfg.AuthInfos = map[string]*api.AuthInfo{}
}
if kcfg.Clusters == nil {
kcfg.Clusters = map[string]*api.Cluster{}
}
if kcfg.Contexts == nil {
kcfg.Contexts = map[string]*api.Context{}
}
return kcfg, nil
}
// decode reads a Config object from bytes.
// Returns empty config if no bytes.
func decode(data []byte) (*api.Config, error) {
// if no data, return empty config
if len(data) == 0 {
return api.NewConfig(), nil
}
kcfg, _, err := latest.Codec.Decode(data, nil, nil)
if err != nil {
return nil, errors.Wrapf(err, "Error decoding config from data: %s", string(data))
}
return kcfg.(*api.Config), nil
}

View File

@ -1,5 +1,5 @@
/* /*
Copyright 2016 The Kubernetes Authors All rights reserved. Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
package util package kubeconfig
import ( import (
"io/ioutil" "io/ioutil"
@ -25,6 +25,9 @@ import (
"testing" "testing"
"k8s.io/client-go/tools/clientcmd/api" "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/client-go/tools/clientcmd"
) )
var fakeKubeCfg = []byte(` var fakeKubeCfg = []byte(`
@ -93,8 +96,8 @@ users:
client-key: /home/la-croix/apiserver.key client-key: /home/la-croix/apiserver.key
`) `)
func TestSetupKubeConfig(t *testing.T) { func TestUpdate(t *testing.T) {
setupCfg := &KubeConfigSetup{ setupCfg := &Settings{
ClusterName: "test", ClusterName: "test",
ClusterServerAddress: "192.168.1.1:8080", ClusterServerAddress: "192.168.1.1:8080",
ClientCertificate: "/home/apiserver.crt", ClientCertificate: "/home/apiserver.crt",
@ -105,7 +108,7 @@ func TestSetupKubeConfig(t *testing.T) {
var tests = []struct { var tests = []struct {
description string description string
cfg *KubeConfigSetup cfg *Settings
existingCfg []byte existingCfg []byte
expected api.Config expected api.Config
err bool err bool
@ -125,7 +128,7 @@ func TestSetupKubeConfig(t *testing.T) {
}, },
{ {
description: "keep context", description: "keep context",
cfg: &KubeConfigSetup{ cfg: &Settings{
ClusterName: "test", ClusterName: "test",
ClusterServerAddress: "192.168.1.1:8080", ClusterServerAddress: "192.168.1.1:8080",
ClientCertificate: "/home/apiserver.crt", ClientCertificate: "/home/apiserver.crt",
@ -144,20 +147,20 @@ func TestSetupKubeConfig(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Error making temp directory %v", err) t.Fatalf("Error making temp directory %v", err)
} }
test.cfg.SetKubeConfigFile(filepath.Join(tmpDir, "kubeconfig")) test.cfg.SetPath(filepath.Join(tmpDir, "kubeconfig"))
if len(test.existingCfg) != 0 { if len(test.existingCfg) != 0 {
if err := ioutil.WriteFile(test.cfg.GetKubeConfigFile(), test.existingCfg, 0600); err != nil { if err := ioutil.WriteFile(test.cfg.filePath(), test.existingCfg, 0600); err != nil {
t.Fatalf("WriteFile: %v", err) t.Fatalf("WriteFile: %v", err)
} }
} }
err = SetupKubeConfig(test.cfg) err = Update(test.cfg)
if err != nil && !test.err { if err != nil && !test.err {
t.Errorf("Got unexpected error: %v", err) t.Errorf("Got unexpected error: %v", err)
} }
if err == nil && test.err { if err == nil && test.err {
t.Errorf("Expected error but got none") t.Errorf("Expected error but got none")
} }
config, err := ReadConfigOrNew(test.cfg.GetKubeConfigFile()) config, err := readOrNew(test.cfg.filePath())
if err != nil { if err != nil {
t.Errorf("Error reading kubeconfig file: %v", err) t.Errorf("Error reading kubeconfig file: %v", err)
} }
@ -174,7 +177,7 @@ func TestSetupKubeConfig(t *testing.T) {
} }
} }
func TestGetKubeConfigStatus(t *testing.T) { func TestIsClusterInConfig(t *testing.T) {
var tests = []struct { var tests = []struct {
description string description string
@ -212,7 +215,7 @@ func TestGetKubeConfigStatus(t *testing.T) {
t.Run(test.description, func(t *testing.T) { t.Run(test.description, func(t *testing.T) {
t.Parallel() t.Parallel()
configFilename := tempFile(t, test.existing) configFilename := tempFile(t, test.existing)
statusActual, err := GetKubeConfigStatus(test.ip, configFilename, "minikube") statusActual, err := IsClusterInConfig(test.ip, "minikube", configFilename)
if err != nil && !test.err { if err != nil && !test.err {
t.Errorf("Got unexpected error: %v", err) t.Errorf("Got unexpected error: %v", err)
} }
@ -227,7 +230,7 @@ func TestGetKubeConfigStatus(t *testing.T) {
} }
} }
func TestUpdateKubeconfigIP(t *testing.T) { func TestUpdateIP(t *testing.T) {
var tests = []struct { var tests = []struct {
description string description string
@ -269,7 +272,7 @@ func TestUpdateKubeconfigIP(t *testing.T) {
t.Run(test.description, func(t *testing.T) { t.Run(test.description, func(t *testing.T) {
t.Parallel() t.Parallel()
configFilename := tempFile(t, test.existing) configFilename := tempFile(t, test.existing)
statusActual, err := UpdateKubeconfigIP(test.ip, configFilename, "minikube") statusActual, err := UpdateIP(test.ip, "minikube", configFilename)
if err != nil && !test.err { if err != nil && !test.err {
t.Errorf("Got unexpected error: %v", err) t.Errorf("Got unexpected error: %v", err)
} }
@ -288,7 +291,7 @@ func TestEmptyConfig(t *testing.T) {
tmp := tempFile(t, []byte{}) tmp := tempFile(t, []byte{})
defer os.Remove(tmp) defer os.Remove(tmp)
cfg, err := ReadConfigOrNew(tmp) cfg, err := readOrNew(tmp)
if err != nil { if err != nil {
t.Fatalf("could not read config: %v", err) t.Fatalf("could not read config: %v", err)
} }
@ -319,12 +322,12 @@ func TestNewConfig(t *testing.T) {
// write actual // write actual
filename := filepath.Join(dir, "config") filename := filepath.Join(dir, "config")
err = WriteConfig(expected, filename) err = writeToFile(expected, filename)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
actual, err := ReadConfigOrNew(filename) actual, err := readOrNew(filename)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -334,7 +337,7 @@ func TestNewConfig(t *testing.T) {
} }
} }
func TestGetIPFromKubeConfig(t *testing.T) { func Test_extractIP(t *testing.T) {
var tests = []struct { var tests = []struct {
description string description string
@ -356,7 +359,7 @@ func TestGetIPFromKubeConfig(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(test.description, func(t *testing.T) { t.Run(test.description, func(t *testing.T) {
configFilename := tempFile(t, test.cfg) configFilename := tempFile(t, test.cfg)
ip, err := getIPFromKubeConfig(configFilename, "minikube") ip, err := extractIP("minikube", configFilename)
if err != nil && !test.err { if err != nil && !test.err {
t.Errorf("Got unexpected error: %v", err) t.Errorf("Got unexpected error: %v", err)
} }
@ -370,131 +373,6 @@ func TestGetIPFromKubeConfig(t *testing.T) {
} }
} }
func TestDeleteKubeConfigContext(t *testing.T) {
configFilename := tempFile(t, fakeKubeCfg)
if err := DeleteKubeConfigContext(configFilename, "la-croix"); err != nil {
t.Fatal(err)
}
cfg, err := ReadConfigOrNew(configFilename)
if err != nil {
t.Fatal(err)
}
if len(cfg.AuthInfos) != 0 {
t.Fail()
}
if len(cfg.Clusters) != 0 {
t.Fail()
}
if len(cfg.Contexts) != 0 {
t.Fail()
}
}
func TestSetCurrentContext(t *testing.T) {
contextName := "minikube"
kubeConfigFile, err := ioutil.TempFile("/tmp", "kubeconfig")
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
defer os.Remove(kubeConfigFile.Name())
cfg, err := ReadConfigOrNew(kubeConfigFile.Name())
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != "" {
t.Errorf("Expected empty context but got %v", cfg.CurrentContext)
}
err = SetCurrentContext(kubeConfigFile.Name(), contextName)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
defer func() {
err := UnsetCurrentContext(kubeConfigFile.Name(), contextName)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
}()
cfg, err = ReadConfigOrNew(kubeConfigFile.Name())
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
}
func TestUnsetCurrentContext(t *testing.T) {
kubeConfigFile := "./testdata/kubeconfig/config1"
contextName := "minikube"
cfg, err := ReadConfigOrNew(kubeConfigFile)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
err = UnsetCurrentContext(kubeConfigFile, contextName)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
defer func() {
err := SetCurrentContext(kubeConfigFile, contextName)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
}()
cfg, err = ReadConfigOrNew(kubeConfigFile)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != "" {
t.Errorf("Expected empty context but got %v", cfg.CurrentContext)
}
}
func TestUnsetCurrentContextOnlyChangesIfProfileIsTheCurrentContext(t *testing.T) {
contextName := "minikube"
kubeConfigFile := "./testdata/kubeconfig/config2"
cfg, err := ReadConfigOrNew(kubeConfigFile)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
err = UnsetCurrentContext(kubeConfigFile, "differentContextName")
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
cfg, err = ReadConfigOrNew(kubeConfigFile)
if err != nil {
t.Fatalf("Error not expected but got %v", err)
}
if cfg.CurrentContext != contextName {
t.Errorf("Expected context name %s but got %s", contextName, cfg.CurrentContext)
}
}
// tempFile creates a temporary with the provided bytes as its contents. // tempFile creates a temporary with the provided bytes as its contents.
// The caller is responsible for deleting file after use. // The caller is responsible for deleting file after use.
func tempFile(t *testing.T, data []byte) string { func tempFile(t *testing.T, data []byte) string {
@ -521,7 +399,7 @@ func minikubeConfig(config *api.Config) {
// cluster // cluster
clusterName := "minikube" clusterName := "minikube"
cluster := api.NewCluster() cluster := api.NewCluster()
cluster.Server = "https://192.168.99.100:" + strconv.Itoa(APIServerPort) cluster.Server = "https://192.168.99.100:" + strconv.Itoa(constants.APIServerPort)
cluster.CertificateAuthority = "/home/tux/.minikube/apiserver.crt" cluster.CertificateAuthority = "/home/tux/.minikube/apiserver.crt"
config.Clusters[clusterName] = cluster config.Clusters[clusterName] = cluster
@ -663,3 +541,26 @@ func contextEquals(aContext, bContext *api.Context) bool {
} }
return true return true
} }
func TestGetKubeConfigPath(t *testing.T) {
var tests = []struct {
input string
want string
}{
{
input: "/home/fake/.kube/.kubeconfig",
want: "/home/fake/.kube/.kubeconfig",
},
{
input: "/home/fake/.kube/.kubeconfig:/home/fake2/.kubeconfig",
want: "/home/fake/.kube/.kubeconfig",
},
}
for _, test := range tests {
os.Setenv(clientcmd.RecommendedConfigPathEnvVar, test.input)
if result := PathFromEnv(); result != test.want {
t.Errorf("Expected first splitted chunk, got: %s", result)
}
}
}

View File

@ -0,0 +1,137 @@
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubeconfig
import (
"io/ioutil"
"sync/atomic"
"github.com/golang/glog"
"github.com/pkg/errors"
"k8s.io/client-go/tools/clientcmd/api"
)
// Settings is the minikubes settings for kubeconfig
type Settings struct {
// The name of the cluster for this context
ClusterName string
// ClusterServerAddress is the address of the kubernetes cluster
ClusterServerAddress string
// ClientCertificate is the path to a client cert file for TLS.
ClientCertificate string
// CertificateAuthority is the path to a cert file for the certificate authority.
CertificateAuthority string
// ClientKey is the path to a client key file for TLS.
ClientKey string
// Should the current context be kept when setting up this one
KeepContext bool
// Should the certificate files be embedded instead of referenced by path
EmbedCerts bool
// kubeConfigFile is the path where the kube config is stored
// Only access this with atomic ops
kubeConfigFile atomic.Value
}
// SetPath sets the setting for kubeconfig filepath
func (k *Settings) SetPath(kubeConfigFile string) {
k.kubeConfigFile.Store(kubeConfigFile)
}
// filePath gets the kubeconfig file
func (k *Settings) filePath() string {
return k.kubeConfigFile.Load().(string)
}
// Populate populates an api.Config object with values from *Settings
func PopulateFromSettings(cfg *Settings, apiCfg *api.Config) error {
var err error
clusterName := cfg.ClusterName
cluster := api.NewCluster()
cluster.Server = cfg.ClusterServerAddress
if cfg.EmbedCerts {
cluster.CertificateAuthorityData, err = ioutil.ReadFile(cfg.CertificateAuthority)
if err != nil {
return errors.Wrapf(err, "reading CertificateAuthority %s", cfg.CertificateAuthority)
}
} else {
cluster.CertificateAuthority = cfg.CertificateAuthority
}
apiCfg.Clusters[clusterName] = cluster
// user
userName := cfg.ClusterName
user := api.NewAuthInfo()
if cfg.EmbedCerts {
user.ClientCertificateData, err = ioutil.ReadFile(cfg.ClientCertificate)
if err != nil {
return errors.Wrapf(err, "reading ClientCertificate %s", cfg.ClientCertificate)
}
user.ClientKeyData, err = ioutil.ReadFile(cfg.ClientKey)
if err != nil {
return errors.Wrapf(err, "reading ClientKey %s", cfg.ClientKey)
}
} else {
user.ClientCertificate = cfg.ClientCertificate
user.ClientKey = cfg.ClientKey
}
apiCfg.AuthInfos[userName] = user
// context
contextName := cfg.ClusterName
context := api.NewContext()
context.Cluster = cfg.ClusterName
context.AuthInfo = userName
apiCfg.Contexts[contextName] = context
// Only set current context to minikube if the user has not used the keepContext flag
if !cfg.KeepContext {
apiCfg.CurrentContext = cfg.ClusterName
}
return nil
}
// update reads config from disk, adds the minikube settings, and writes it back.
// activeContext is true when minikube is the CurrentContext
// If no CurrentContext is set, the given name will be used.
func Update(kcs *Settings) error {
glog.Infoln("Using kubeconfig: ", kcs.filePath())
// read existing config or create new if does not exist
kcfg, err := readOrNew(kcs.filePath())
if err != nil {
return err
}
err = PopulateFromSettings(kcs, kcfg)
if err != nil {
return err
}
// write back to disk
if err := writeToFile(kcfg, kcs.filePath()); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}

View File

@ -87,7 +87,7 @@ var styles = map[StyleEnum]style{
Caching: {Prefix: "🤹 "}, Caching: {Prefix: "🤹 "},
StartingVM: {Prefix: "🔥 "}, StartingVM: {Prefix: "🔥 "},
StartingNone: {Prefix: "🤹 "}, StartingNone: {Prefix: "🤹 "},
Provisioner: {Prefix: " "}, Provisioner: {Prefix: " "},
Resetting: {Prefix: "🔄 "}, Resetting: {Prefix: "🔄 "},
DeletingHost: {Prefix: "🔥 "}, DeletingHost: {Prefix: "🔥 "},
Copying: {Prefix: "✨ "}, Copying: {Prefix: "✨ "},

View File

@ -33,7 +33,7 @@ var vmProblems = map[string]match{
"HYPERKIT_NO_IP": { "HYPERKIT_NO_IP": {
Regexp: re(`IP address never found in dhcp leases file Temporary Error: Could not find an IP address for`), Regexp: re(`IP address never found in dhcp leases file Temporary Error: Could not find an IP address for`),
Advice: "Install the latest minikube hyperkit driver, and run 'minikube delete'", Advice: "Install the latest minikube hyperkit driver, and run 'minikube delete'",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#hyperkit-driver", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/hyperkit/",
Issues: []int{1926, 4206}, Issues: []int{1926, 4206},
}, },
"VBOX_NOT_FOUND": { "VBOX_NOT_FOUND": {
@ -89,12 +89,12 @@ var vmProblems = map[string]match{
"KVM2_NOT_FOUND": { "KVM2_NOT_FOUND": {
Regexp: re(`Driver "kvm2" not found. Do you have the plugin binary .* accessible in your PATH`), Regexp: re(`Driver "kvm2" not found. Do you have the plugin binary .* accessible in your PATH`),
Advice: "Please install the minikube kvm2 VM driver, or select an alternative --vm-driver", Advice: "Please install the minikube kvm2 VM driver, or select an alternative --vm-driver",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#kvm2-driver", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/kvm2/",
}, },
"HYPERKIT_NOT_FOUND": { "HYPERKIT_NOT_FOUND": {
Regexp: re(`Driver "hyperkit" not found. Do you have the plugin binary .* accessible in your PATH?`), Regexp: re(`Driver "hyperkit" not found. Do you have the plugin binary .* accessible in your PATH?`),
Advice: "Please install the minikube hyperkit VM driver, or select an alternative --vm-driver", Advice: "Please install the minikube hyperkit VM driver, or select an alternative --vm-driver",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#hyperkit-driver", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/hyperkit/",
}, },
"KVM2_RESTART_NO_IP": { "KVM2_RESTART_NO_IP": {
Regexp: re(`Error starting stopped host: Machine didn't return an IP after 120 seconds`), Regexp: re(`Error starting stopped host: Machine didn't return an IP after 120 seconds`),
@ -104,7 +104,7 @@ var vmProblems = map[string]match{
"KVM2_START_NO_IP": { "KVM2_START_NO_IP": {
Regexp: re(`Error in driver during machine creation: Machine didn't return an IP after 120 seconds`), Regexp: re(`Error in driver during machine creation: Machine didn't return an IP after 120 seconds`),
Advice: "Install the latest kvm2 driver and run 'virt-host-validate'", Advice: "Install the latest kvm2 driver and run 'virt-host-validate'",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#kvm2-driver", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/kvm2/",
Issues: []int{4249, 3566}, Issues: []int{4249, 3566},
}, },
"KVM2_NETWORK_DEFINE_XML": { "KVM2_NETWORK_DEFINE_XML": {
@ -127,17 +127,17 @@ var vmProblems = map[string]match{
"KVM_CONNECTION_ERROR": { "KVM_CONNECTION_ERROR": {
Regexp: re(`error connecting to libvirt socket`), Regexp: re(`error connecting to libvirt socket`),
Advice: "Have you set up libvirt correctly?", Advice: "Have you set up libvirt correctly?",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#kvm2-driver", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/kvm2/",
}, },
"DRIVER_CRASHED": { "DRIVER_CRASHED": {
Regexp: re(`Error attempting to get plugin server address for RPC`), Regexp: re(`Error attempting to get plugin server address for RPC`),
Advice: "The VM driver exited with an error, and may be corrupt. Run 'minikube start' with --alsologtostderr -v=8 to see the error", Advice: "The VM driver exited with an error, and may be corrupt. Run 'minikube start' with --alsologtostderr -v=8 to see the error",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/",
}, },
"DRIVER_EXITED": { "DRIVER_EXITED": {
Regexp: re(`Unable to start VM: create: creating: exit status 1`), Regexp: re(`Unable to start VM: create: creating: exit status 1`),
Advice: "Re-run 'minikube start' with --alsologtostderr -v=8 to see the VM driver error message", Advice: "Re-run 'minikube start' with --alsologtostderr -v=8 to see the VM driver error message",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#troubleshooting", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/#troubleshooting",
}, },
"VM_BOOT_FAILED_HYPERV_ENABLED": { "VM_BOOT_FAILED_HYPERV_ENABLED": {
Regexp: re(`VirtualBox won't boot a 64bits VM when Hyper-V is activated`), Regexp: re(`VirtualBox won't boot a 64bits VM when Hyper-V is activated`),
@ -173,7 +173,7 @@ var vmProblems = map[string]match{
} }
// proxyDoc is the URL to proxy documentation // proxyDoc is the URL to proxy documentation
const proxyDoc = "https://github.com/kubernetes/minikube/blob/master/docs/http_proxy.md" const proxyDoc = "https://minikube.sigs.k8s.io/docs/reference/networking/proxy/"
// netProblems are network related problems. // netProblems are network related problems.
var netProblems = map[string]match{ var netProblems = map[string]match{
@ -262,7 +262,7 @@ var osProblems = map[string]match{
"SYSTEMCTL_EXIT_1": { "SYSTEMCTL_EXIT_1": {
Regexp: re(`Failed to enable container runtime: .*sudo systemctl start docker: exit status 1`), Regexp: re(`Failed to enable container runtime: .*sudo systemctl start docker: exit status 1`),
Advice: "If using the none driver, ensure that systemctl is installed", Advice: "If using the none driver, ensure that systemctl is installed",
URL: "https://github.com/kubernetes/minikube/blob/master/docs/vmdriver-none.md", URL: "https://minikube.sigs.k8s.io/docs/reference/drivers/none/",
Issues: []int{2704}, Issues: []int{2704},
}, },
} }

View File

@ -1,372 +0,0 @@
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"sync/atomic"
"github.com/golang/glog"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/tools/clientcmd/api/latest"
)
// KubeConfigSetup is the kubeconfig setup
type KubeConfigSetup struct {
// The name of the cluster for this context
ClusterName string
// ClusterServerAddress is the address of the kubernetes cluster
ClusterServerAddress string
// ClientCertificate is the path to a client cert file for TLS.
ClientCertificate string
// CertificateAuthority is the path to a cert file for the certificate authority.
CertificateAuthority string
// ClientKey is the path to a client key file for TLS.
ClientKey string
// Should the current context be kept when setting up this one
KeepContext bool
// Should the certificate files be embedded instead of referenced by path
EmbedCerts bool
// kubeConfigFile is the path where the kube config is stored
// Only access this with atomic ops
kubeConfigFile atomic.Value
}
// SetKubeConfigFile sets the kubeconfig file
func (k *KubeConfigSetup) SetKubeConfigFile(kubeConfigFile string) {
k.kubeConfigFile.Store(kubeConfigFile)
}
// GetKubeConfigFile gets the kubeconfig file
func (k *KubeConfigSetup) GetKubeConfigFile() string {
return k.kubeConfigFile.Load().(string)
}
// PopulateKubeConfig populates an api.Config object.
func PopulateKubeConfig(cfg *KubeConfigSetup, kubecfg *api.Config) error {
var err error
clusterName := cfg.ClusterName
cluster := api.NewCluster()
cluster.Server = cfg.ClusterServerAddress
if cfg.EmbedCerts {
cluster.CertificateAuthorityData, err = ioutil.ReadFile(cfg.CertificateAuthority)
if err != nil {
return err
}
} else {
cluster.CertificateAuthority = cfg.CertificateAuthority
}
kubecfg.Clusters[clusterName] = cluster
// user
userName := cfg.ClusterName
user := api.NewAuthInfo()
if cfg.EmbedCerts {
user.ClientCertificateData, err = ioutil.ReadFile(cfg.ClientCertificate)
if err != nil {
return err
}
user.ClientKeyData, err = ioutil.ReadFile(cfg.ClientKey)
if err != nil {
return err
}
} else {
user.ClientCertificate = cfg.ClientCertificate
user.ClientKey = cfg.ClientKey
}
kubecfg.AuthInfos[userName] = user
// context
contextName := cfg.ClusterName
context := api.NewContext()
context.Cluster = cfg.ClusterName
context.AuthInfo = userName
kubecfg.Contexts[contextName] = context
// Only set current context to minikube if the user has not used the keepContext flag
if !cfg.KeepContext {
kubecfg.CurrentContext = cfg.ClusterName
}
return nil
}
// SetupKubeConfig reads config from disk, adds the minikube settings, and writes it back.
// activeContext is true when minikube is the CurrentContext
// If no CurrentContext is set, the given name will be used.
func SetupKubeConfig(cfg *KubeConfigSetup) error {
glog.Infoln("Using kubeconfig: ", cfg.GetKubeConfigFile())
// read existing config or create new if does not exist
config, err := ReadConfigOrNew(cfg.GetKubeConfigFile())
if err != nil {
return err
}
err = PopulateKubeConfig(cfg, config)
if err != nil {
return err
}
// write back to disk
if err := WriteConfig(config, cfg.GetKubeConfigFile()); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}
// ReadConfigOrNew retrieves Kubernetes client configuration from a file.
// If no files exists, an empty configuration is returned.
func ReadConfigOrNew(filename string) (*api.Config, error) {
data, err := ioutil.ReadFile(filename)
if os.IsNotExist(err) {
return api.NewConfig(), nil
} else if err != nil {
return nil, errors.Wrapf(err, "Error reading file %q", filename)
}
// decode config, empty if no bytes
config, err := decode(data)
if err != nil {
return nil, errors.Errorf("could not read config: %v", err)
}
// initialize nil maps
if config.AuthInfos == nil {
config.AuthInfos = map[string]*api.AuthInfo{}
}
if config.Clusters == nil {
config.Clusters = map[string]*api.Cluster{}
}
if config.Contexts == nil {
config.Contexts = map[string]*api.Context{}
}
return config, nil
}
// WriteConfig encodes the configuration and writes it to the given file.
// If the file exists, it's contents will be overwritten.
func WriteConfig(config *api.Config, filename string) error {
if config == nil {
glog.Errorf("could not write to '%s': config can't be nil", filename)
}
// encode config to YAML
data, err := runtime.Encode(latest.Codec, config)
if err != nil {
return errors.Errorf("could not write to '%s': failed to encode config: %v", filename, err)
}
// create parent dir if doesn't exist
dir := filepath.Dir(filename)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0755); err != nil {
return errors.Wrapf(err, "Error creating directory: %s", dir)
}
}
// write with restricted permissions
if err := ioutil.WriteFile(filename, data, 0600); err != nil {
return errors.Wrapf(err, "Error writing file %s", filename)
}
if err := MaybeChownDirRecursiveToMinikubeUser(dir); err != nil {
return errors.Wrapf(err, "Error recursively changing ownership for dir: %s", dir)
}
return nil
}
// decode reads a Config object from bytes.
// Returns empty config if no bytes.
func decode(data []byte) (*api.Config, error) {
// if no data, return empty config
if len(data) == 0 {
return api.NewConfig(), nil
}
config, _, err := latest.Codec.Decode(data, nil, nil)
if err != nil {
return nil, errors.Wrapf(err, "Error decoding config from data: %s", string(data))
}
return config.(*api.Config), nil
}
// GetKubeConfigStatus verifies the ip stored in kubeconfig.
func GetKubeConfigStatus(ip net.IP, filename string, machineName string) (bool, error) {
if ip == nil {
return false, fmt.Errorf("Error, empty ip passed")
}
kip, err := getIPFromKubeConfig(filename, machineName)
if err != nil {
return false, err
}
if kip.Equal(ip) {
return true, nil
}
// Kubeconfig IP misconfigured
return false, nil
}
// UpdateKubeconfigIP overwrites the IP stored in kubeconfig with the provided IP.
func UpdateKubeconfigIP(ip net.IP, filename string, machineName string) (bool, error) {
if ip == nil {
return false, fmt.Errorf("Error, empty ip passed")
}
kip, err := getIPFromKubeConfig(filename, machineName)
if err != nil {
return false, err
}
if kip.Equal(ip) {
return false, nil
}
kport, err := GetPortFromKubeConfig(filename, machineName)
if err != nil {
return false, err
}
con, err := ReadConfigOrNew(filename)
if err != nil {
return false, errors.Wrap(err, "Error getting kubeconfig status")
}
// Safe to lookup server because if field non-existent getIPFromKubeconfig would have given an error
con.Clusters[machineName].Server = "https://" + ip.String() + ":" + strconv.Itoa(kport)
err = WriteConfig(con, filename)
if err != nil {
return false, err
}
// Kubeconfig IP reconfigured
return true, nil
}
// getIPFromKubeConfig returns the IP address stored for minikube in the kubeconfig specified
func getIPFromKubeConfig(filename, machineName string) (net.IP, error) {
con, err := ReadConfigOrNew(filename)
if err != nil {
return nil, errors.Wrap(err, "Error getting kubeconfig status")
}
cluster, ok := con.Clusters[machineName]
if !ok {
return nil, errors.Errorf("Kubeconfig does not have a record of the machine cluster")
}
kurl, err := url.Parse(cluster.Server)
if err != nil {
return net.ParseIP(cluster.Server), nil
}
kip, _, err := net.SplitHostPort(kurl.Host)
if err != nil {
return net.ParseIP(kurl.Host), nil
}
ip := net.ParseIP(kip)
return ip, nil
}
// GetPortFromKubeConfig returns the Port number stored for minikube in the kubeconfig specified
func GetPortFromKubeConfig(filename, machineName string) (int, error) {
con, err := ReadConfigOrNew(filename)
if err != nil {
return 0, errors.Wrap(err, "Error getting kubeconfig status")
}
cluster, ok := con.Clusters[machineName]
if !ok {
return 0, errors.Errorf("Kubeconfig does not have a record of the machine cluster")
}
kurl, err := url.Parse(cluster.Server)
if err != nil {
return APIServerPort, nil
}
_, kport, err := net.SplitHostPort(kurl.Host)
if err != nil {
return APIServerPort, nil
}
port, err := strconv.Atoi(kport)
return port, err
}
// UnsetCurrentContext unsets the current-context from minikube to "" on minikube stop
func UnsetCurrentContext(filename, machineName string) error {
confg, err := ReadConfigOrNew(filename)
if err != nil {
return errors.Wrap(err, "Error getting kubeconfig status")
}
// Unset current-context only if profile is the current-context
if confg.CurrentContext == machineName {
confg.CurrentContext = ""
if err := WriteConfig(confg, filename); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}
return nil
}
// SetCurrentContext sets the kubectl's current-context
func SetCurrentContext(kubeCfgPath, name string) error {
kcfg, err := ReadConfigOrNew(kubeCfgPath)
if err != nil {
return errors.Wrap(err, "Error getting kubeconfig status")
}
kcfg.CurrentContext = name
if err := WriteConfig(kcfg, kubeCfgPath); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}
// DeleteKubeConfigContext deletes the specified machine's kubeconfig context
func DeleteKubeConfigContext(kubeCfgPath, machineName string) error {
kcfg, err := ReadConfigOrNew(kubeCfgPath)
if err != nil {
return errors.Wrap(err, "Error getting kubeconfig status")
}
if kcfg == nil || api.IsConfigEmpty(kcfg) {
glog.V(2).Info("kubeconfig is empty")
return nil
}
delete(kcfg.Clusters, machineName)
delete(kcfg.AuthInfos, machineName)
delete(kcfg.Contexts, machineName)
if kcfg.CurrentContext == machineName {
kcfg.CurrentContext = ""
}
if err := WriteConfig(kcfg, kubeCfgPath); err != nil {
return errors.Wrap(err, "writing kubeconfig")
}
return nil
}

View File

@ -21,22 +21,19 @@ limitations under the License.
package util package util
import ( import (
"fmt"
"io" "io"
"path/filepath" "path/filepath"
"sync" "sync"
"github.com/cheggaaa/pb" "github.com/cheggaaa/pb/v3"
"github.com/golang/glog"
"github.com/hashicorp/go-getter" "github.com/hashicorp/go-getter"
) )
var defaultProgressBar getter.ProgressTracker = &progressBar{} var defaultProgressBar getter.ProgressTracker = &progressBar{}
type progressBar struct { type progressBar struct {
lock sync.Mutex lock sync.Mutex
pool *pb.Pool progress *pb.ProgressBar
pbs int
} }
// TrackProgress instantiates a new progress bar that will // TrackProgress instantiates a new progress bar that will
@ -45,38 +42,24 @@ type progressBar struct {
func (cpb *progressBar) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { func (cpb *progressBar) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser {
cpb.lock.Lock() cpb.lock.Lock()
defer cpb.lock.Unlock() defer cpb.lock.Unlock()
if cpb.progress == nil {
if cpb.pool == nil { cpb.progress = pb.New64(totalSize)
cpb.pool = pb.NewPool()
if err := cpb.pool.Start(); err != nil {
glog.Errorf("pool start: %v", err)
}
} }
p := pb.Full.Start64(totalSize)
p.Set("prefix", filepath.Base(src+": "))
p.SetCurrent(currentSize)
p.Set(pb.Bytes, true)
p := pb.New64(totalSize)
p.Set64(currentSize)
p.SetUnits(pb.U_BYTES)
p.Prefix(fmt.Sprintf(" %s:", filepath.Base(src)))
// Just a hair less than 80 (standard terminal width) for aesthetics & pasting into docs // Just a hair less than 80 (standard terminal width) for aesthetics & pasting into docs
p.SetWidth(78) p.SetWidth(79)
cpb.pool.Add(p) barReader := p.NewProxyReader(stream)
reader := p.NewProxyReader(stream)
cpb.pbs++
return &readCloser{ return &readCloser{
Reader: reader, Reader: barReader,
close: func() error { close: func() error {
cpb.lock.Lock() cpb.lock.Lock()
defer cpb.lock.Unlock() defer cpb.lock.Unlock()
p.Finish() p.Finish()
cpb.pbs--
if cpb.pbs <= 0 {
if err := cpb.pool.Stop(); err != nil {
glog.Errorf("pool stop: %v", err)
}
cpb.pool = nil
}
return nil return nil
}, },
} }

View File

@ -36,7 +36,7 @@ $medium: $mk-medium;
// Navigation bar // Navigation bar
$navbar-dark-color: $mk-dark; $navbar-dark-color: $mk-dark;
$navbar-dark-hover-color: $mk-light !default; $navbar-dark-hover-color: $mk-light !default;
$navbar-dark-active-color: $mk-light !default; $navbar-dark-active-color: $primary !default;
$navbar-dark-disabled-color: rgba($white, 0.25) !default; $navbar-dark-disabled-color: rgba($white, 0.25) !default;
.td-navbar { .td-navbar {
background: $white !important; background: $white !important;
@ -148,4 +148,18 @@ footer.bg-dark {
// Reduce section padding by 1rem // Reduce section padding by 1rem
section.td-box--height-auto { section.td-box--height-auto {
padding-bottom: 3rem !important; padding-bottom: 3rem !important;
} }
div.td-content {
// Allow code tags to span most of a window length (default is 80%)
pre {
max-width: 99% !important;
}
h2 {
font-size: 1.4rem !important;
}
h3 {
font-size: 1.3rem !important;
}
}

View File

@ -46,6 +46,12 @@ resampleFilter = "CatmullRom"
quality = 75 quality = 75
anchor = "smart" anchor = "smart"
# Additional menu items
[[menu.main]]
name = "GitHub"
weight = 50
url = "https://github.com/kubernetes/minikube"
[services] [services]
[services.googleAnalytics] [services.googleAnalytics]
# Comment out the next line to disable GA tracking. Also disables the feature described in [params.ui.feedback]. # Comment out the next line to disable GA tracking. Also disables the feature described in [params.ui.feedback].
@ -62,7 +68,7 @@ weight = 1
[params] [params]
copyright = "The Kubernetes Authors -- " copyright = "The Kubernetes Authors -- "
# The latest release of minikube # The latest release of minikube
latest_release = "1.3.0" latest_release = "1.3.1"
privacy_policy = "" privacy_policy = ""
@ -71,12 +77,12 @@ privacy_policy = ""
version_menu = "Releases" version_menu = "Releases"
# Repository configuration (URLs for in-page links to opening issues and suggesting changes) # Repository configuration (URLs for in-page links to opening issues and suggesting changes)
github_repo = "http://github.com/minikube/kubernetes" github_repo = "http://github.com/kubernetes/minikube"
# An optional link to a related project repo. For example, the sibling repository where your product code lives. # An optional link to a related project repo. For example, the sibling repository where your product code lives.
github_project_repo = "" github_project_repo = ""
# Specify a value here if your content directory is not in your repo's root directory # Specify a value here if your content directory is not in your repo's root directory
github_subdir = "/site/content" github_subdir = "site"
# Google Custom Search Engine ID. Remove or comment out to disable search. # Google Custom Search Engine ID. Remove or comment out to disable search.
gcs_engine_id = "005331096405080631692:s7c4yfpw9sy" gcs_engine_id = "005331096405080631692:s7c4yfpw9sy"
@ -84,7 +90,7 @@ gcs_engine_id = "005331096405080631692:s7c4yfpw9sy"
# User interface configuration # User interface configuration
[params.ui] [params.ui]
# Enable to show the side bar menu in its compact state. # Enable to show the side bar menu in its compact state.
sidebar_menu_compact = false sidebar_menu_compact = true
# Set to true to disable breadcrumb navigation. # Set to true to disable breadcrumb navigation.
breadcrumb_disable = false breadcrumb_disable = false
# Set to true to hide the sidebar search box (the top nav search box will still be displayed if search is enabled) # Set to true to hide the sidebar search box (the top nav search box will still be displayed if search is enabled)
@ -99,8 +105,8 @@ navbar_logo = true
[params.ui.feedback] [params.ui.feedback]
enable = true enable = true
# The responses that the user sees after clicking "yes" (the page was helpful) or "no" (the page was not helpful). # The responses that the user sees after clicking "yes" (the page was helpful) or "no" (the page was not helpful).
yes = 'Glad to hear it! Please <a href="https://github.com/kubernetes/minikube/issues/new">tell us how we can improve</a>.' yes = 'Glad to hear it! Please <a href="https://github.com/kubernetes/minikube/issues/new/choose">tell us how we can improve</a>.'
no = 'Sorry to hear that. Please <a href="https://github.com/kubernetes/minikube/issues/new">tell us how we can improve</a>.' no = 'Sorry to hear that. Please <a href="https://github.com/kubernetes/minikube/issues/new/choose">tell us how we can improve</a>.'
[params.links] [params.links]
# End user relevant links. These will show up on left side of footer and in the community page if you have one. # End user relevant links. These will show up on left side of footer and in the community page if you have one.

View File

@ -4,7 +4,7 @@ resources:
- src: "logo.png" - src: "logo.png"
title: "logo" title: "logo"
- src: "start.jpg" - src: "start.png"
title: "start" title: "start"
--- ---
@ -15,7 +15,7 @@ resources:
<div class="col-sm-8"> <div class="col-sm-8">
<h1>Welcome to minikube!</h1> <h1>Welcome to minikube!</h1>
<p class="lead mt-5" style="text: nowrap">Local Kubernetes, focused on application development &amp; education</p> <p class="lead mt-5" style="text: nowrap">Local Kubernetes, focused on application development &amp; education</p>
<a class="btn btn-lg btn-primary mr-3 mb-4" href="/docs/getting-started"> <a class="btn btn-lg btn-primary mr-3 mb-4" href="/docs/start">
Get Started <i class="fas fa-arrow-alt-circle-right ml-2"></i> Get Started <i class="fas fa-arrow-alt-circle-right ml-2"></i>
</a> </a>
<a class="btn btn-lg btn-secondary mr-3 mb-4" href="https://github.com/kubernetes/minikube"> <a class="btn btn-lg btn-secondary mr-3 mb-4" href="https://github.com/kubernetes/minikube">
@ -57,10 +57,10 @@ A single command away from reproducing your production environment, from the com
{{< blocks/section color="white" >}} {{< blocks/section color="white" >}}
{{% blocks/feature icon="fa-star" title="Developer focused" %}} {{% blocks/feature icon="fa-star" title="Developer focused" %}}
- [LoadBalancer emulation](https://github.com/kubernetes/minikube/blob/master/docs/tunnel.md) - [LoadBalancer emulation](https://minikube.sigs.k8s.io/docs/tasks/loadbalancer/)
- [Addons Marketplace](https://github.com/kubernetes/minikube/blob/master/docs/addons.md) - [Addons Marketplace](https://minikube.sigs.k8s.io/docs/tasks/addons/)
- [Integrated Dashboard](https://github.com/kubernetes/minikube/blob/master/docs/dashboard.md) - [Integrated Dashboard](https://minikube.sigs.k8s.io/docs/tasks/dashboard/)
- [GPU support](https://github.com/kubernetes/minikube/blob/master/docs/gpu.md) - [GPU support](https://minikube.sigs.k8s.io/docs/tutorials/nvidia_gpu/)
- Reusable Docker daemon - Reusable Docker daemon
{{% /blocks/feature %}} {{% /blocks/feature %}}
@ -82,7 +82,7 @@ A single command away from reproducing your production environment, from the com
{{< blocks/section color="light" >}} {{< blocks/section color="light" >}}
{{% blocks/feature icon="fab fa-slack" title="Chat with us on Slack" %}} {{% blocks/feature icon="fab fa-slack" title="Chat with us on Slack" %}}
<a class="text-white" href="http://slack.kubernetes.io"> <a class="text-white" href="https://slack.kubernetes.io">
<button type="button" class="btn btn-secondary" style="width:150px; margin-top: 12px;">Chat</button> <button type="button" class="btn btn-secondary" style="width:150px; margin-top: 12px;">Chat</button>
</a> </a>
@ -90,7 +90,7 @@ The #minikube channel is ready to answer your questions.
{{% /blocks/feature %}} {{% /blocks/feature %}}
{{% blocks/feature icon="fab fa-github" title="Contributions welcome" %}} {{% blocks/feature icon="fab fa-github" title="Contributions welcome" %}}
<a class="text-white" href="/docs/contribute"> <a class="text-white" href="/docs/contributing">
<button type="button" class="btn btn-secondary" style="width:150px; margin-top: 12px;">Contribute</button> <button type="button" class="btn btn-secondary" style="width:150px; margin-top: 12px;">Contribute</button>
</a> </a>

View File

@ -1,6 +1,6 @@
--- ---
title: "Docsy Blog" title: "Docsy Blog"
linkTitle: "Blog" linkTitle: "News"
menu: menu:
main: main:
weight: 30 weight: 30

Binary file not shown.

Before

Width:  |  Height:  |  Size: 378 KiB

View File

@ -1,46 +0,0 @@
---
date: 2018-10-06
title: "Easy documentation with Docsy"
linkTitle: "Announcing Docsy"
description: "The Docsy Hugo theme lets project maintainers and contributors focus on content, not on reinventing a website infrastructure from scratch"
author: Riona MacNamara ([@rionam](https://twitter.com/bepsays))
resources:
- src: "**.{png,jpg}"
title: "Image #:counter"
params:
byline: "Photo: Riona MacNamara / CC-BY-CA"
---
**This is a typical blog post that includes images.**
The front matter specifies the date of the blog post, its title, a short description that will be displayed on the blog landing page, and its author.
## Including images
Here's an image (`featured-sunset-get.png`) that includes a byline and a caption.
{{< imgproc sunset Fill "600x300" >}}
Fetch and scale an image in the upcoming Hugo 0.43.
{{< /imgproc >}}
The front matter of this post specifies properties to be assigned to all image resources:
```
resources:
- src: "**.{png,jpg}"
title: "Image #:counter"
params:
byline: "Photo: Riona MacNamara / CC-BY-CA"
```
To include the image in a page, specify its details like this:
```
{{< imgproc sunset Fill "600x300" >}}
Fetch and scale an image in the upcoming Hugo 0.43.
{{< /imgproc >}}
```
The image will be rendered at the size and byline specified in the front matter.

View File

@ -0,0 +1,12 @@
---
title: "New website launched"
date: 2019-08-13
description: >
About the new minikube website
---
As you may have noticed, minikube has a brand new website.
As part of our [2019 roadmap](https://minikube.sigs.k8s.io/docs/contributing/roadmap/), we identified the need for a user-focused website for documentation, and this is it. It's based on the [Hugo Website Framework](https://gohugo.io/) and uses the [Docsy Templates for Technical Documentation](https://github.com/google/docsy).
We have more work to do with organizing the documentation and making it more useful, but we hope you are able to enjoy the fruits of our labor. PR's welcome!

View File

@ -1,241 +0,0 @@
---
title: "The second blog post"
linkTitle: "Second blog post"
date: 2018-10-06
description: >
A short lead descripton about this content page. Text here can also be **bold** or _italic_ and can even be split over multiple paragraphs.
---
Text can be **bold**, _italic_, or ~~strikethrough~~. [Links](https://github.com) should be blue with no underlines (unless hovered over).
There should be whitespace between paragraphs. There should be whitespace between paragraphs. There should be whitespace between paragraphs. There should be whitespace between paragraphs.
There should be whitespace between paragraphs. There should be whitespace between paragraphs. There should be whitespace between paragraphs. There should be whitespace between paragraphs.
> There should be no margin above this first sentence.
>
> Blockquotes should be a lighter gray with a border along the left side in the secondary color.
>
> There should be no margin below this final sentence.
## First Header
This is a normal paragraph following a header. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
On big screens, paragraphs and headings should not take up the full container width, but we want tables, code blocks and similar to take the full width.
Lorem markdownum tuta hospes stabat; idem saxum facit quaterque repetito
occumbere, oves novem gestit haerebat frena; qui. Respicit recurvam erat:
pignora hinc reppulit nos **aut**, aptos, ipsa.
Meae optatos *passa est* Epiros utiliter *Talibus niveis*, hoc lata, edidit.
Dixi ad aestum.
## Header 2
> This is a blockquote following a header. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### Header 3
```
This is a code block following a header.
```
#### Header 4
* This is an unordered list following a header.
* This is an unordered list following a header.
* This is an unordered list following a header.
##### Header 5
1. This is an ordered list following a header.
2. This is an ordered list following a header.
3. This is an ordered list following a header.
###### Header 6
| What | Follows |
|-----------|-----------------|
| A table | A header |
| A table | A header |
| A table | A header |
----------------
There's a horizontal rule above and below this.
----------------
Here is an unordered list:
* Salt-n-Pepa
* Bel Biv DeVoe
* Kid 'N Play
And an ordered list:
1. Michael Jackson
2. Michael Bolton
3. Michael Bublé
And an unordered task list:
- [x] Create a sample markdown document
- [x] Add task lists to it
- [ ] Take a vacation
And a "mixed" task list:
- [ ] Steal underpants
- ?
- [ ] Profit!
And a nested list:
* Jackson 5
* Michael
* Tito
* Jackie
* Marlon
* Jermaine
* TMNT
* Leonardo
* Michelangelo
* Donatello
* Raphael
Definition lists can be used with Markdown syntax. Definition terms are bold.
Name
: Godzilla
Born
: 1952
Birthplace
: Japan
Color
: Green
----------------
Tables should have bold headings and alternating shaded rows.
| Artist | Album | Year |
|-------------------|-----------------|------|
| Michael Jackson | Thriller | 1982 |
| Prince | Purple Rain | 1984 |
| Beastie Boys | License to Ill | 1986 |
If a table is too wide, it should scroll horizontally.
| Artist | Album | Year | Label | Awards | Songs |
|-------------------|-----------------|------|-------------|----------|-----------|
| Michael Jackson | Thriller | 1982 | Epic Records | Grammy Award for Album of the Year, American Music Award for Favorite Pop/Rock Album, American Music Award for Favorite Soul/R&B Album, Brit Award for Best Selling Album, Grammy Award for Best Engineered Album, Non-Classical | Wanna Be Startin' Somethin', Baby Be Mine, The Girl Is Mine, Thriller, Beat It, Billie Jean, Human Nature, P.Y.T. (Pretty Young Thing), The Lady in My Life |
| Prince | Purple Rain | 1984 | Warner Brothers Records | Grammy Award for Best Score Soundtrack for Visual Media, American Music Award for Favorite Pop/Rock Album, American Music Award for Favorite Soul/R&B Album, Brit Award for Best Soundtrack/Cast Recording, Grammy Award for Best Rock Performance by a Duo or Group with Vocal | Let's Go Crazy, Take Me With U, The Beautiful Ones, Computer Blue, Darling Nikki, When Doves Cry, I Would Die 4 U, Baby I'm a Star, Purple Rain |
| Beastie Boys | License to Ill | 1986 | Mercury Records | noawardsbutthistablecelliswide | Rhymin & Stealin, The New Style, She's Crafty, Posse in Effect, Slow Ride, Girls, (You Gotta) Fight for Your Right, No Sleep Till Brooklyn, Paul Revere, Hold It Now, Hit It, Brass Monkey, Slow and Low, Time to Get Ill |
----------------
Code snippets like `var foo = "bar";` can be shown inline.
Also, `this should vertically align` ~~`with this`~~ ~~and this~~.
Code can also be shown in a block element.
```
foo := "bar";
bar := "foo";
```
Code can also use syntax highlighting.
```go
func main() {
input := `var foo = "bar";`
lexer := lexers.Get("javascript")
iterator, _ := lexer.Tokenise(nil, input)
style := styles.Get("github")
formatter := html.New(html.WithLineNumbers())
var buff bytes.Buffer
formatter.Format(&buff, style, iterator)
fmt.Println(buff.String())
}
```
```
Long, single-line code blocks should not wrap. They should horizontally scroll if they are too long. This line should be long enough to demonstrate this.
```
Inline code inside table cells should still be distinguishable.
| Language | Code |
|-------------|--------------------|
| Javascript | `var foo = "bar";` |
| Ruby | `foo = "bar"{` |
----------------
Small images should be shown at their actual size.
Large images should always scale down and fit in the content container.
## Components
### Alerts
{{< alert >}}This is an alert.{{< /alert >}}
{{< alert title="Note:" >}}This is an alert with a title.{{< /alert >}}
{{< alert type="success" >}}This is a successful alert.{{< /alert >}}
{{< alert type="warning" >}}This is a warning!{{< /alert >}}
{{< alert type="warning" title="Warning!" >}}This is a warning with a title!{{< /alert >}}
## Sizing
Add some sections here to see how the ToC looks like. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### Parameters available
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### Using pixels
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### Using rem
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
## Memory
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### RAM to use
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### More is better
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
### Used RAM
Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
```
This is the final element on the page and there should be no margin below this.
```

Some files were not shown because too many files have changed in this diff Show More