Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 'pause' command to freeze Kubernetes cluster #5962

Merged
merged 21 commits into from
Jan 24, 2020
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion cmd/minikube/cmd/mount.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ var mountCmd = &cobra.Command{
exit.WithError("Error getting config", err)
}
host, err := api.Load(cc.Name)

if err != nil {
exit.WithError("Error loading api", err)
}
Expand Down
106 changes: 106 additions & 0 deletions cmd/minikube/cmd/pause.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
Copyright 2020 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 cmd

import (
"os"
"strings"

"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"k8s.io/minikube/pkg/minikube/cluster"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/cruntime"
"k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/out"
)

var (
namespaces []string
allNamespaces bool
)

// pauseCmd represents the docker-pause command
var pauseCmd = &cobra.Command{
Use: "pause",
Short: "pause containers",
Run: runPause,
}

func runPause(cmd *cobra.Command, args []string) {
cname := viper.GetString(config.MachineProfile)
api, err := machine.NewAPIClient()
if err != nil {
exit.WithError("Error getting client", err)
}
defer api.Close()
cc, err := config.Load(cname)

if err != nil && !os.IsNotExist(err) {
exit.WithError("Error loading profile config", err)
}

if err != nil {
out.ErrT(out.Meh, `"{{.name}}" profile does not exist`, out.V{"name": cname})
os.Exit(1)
}

glog.Infof("config: %+v", cc)
host, err := cluster.CheckIfHostExistsAndLoad(api, cname)
if err != nil {
exit.WithError("Error getting host", err)
}

r, err := machine.CommandRunner(host)
if err != nil {
exit.WithError("Failed to get command runner", err)
}

config := cruntime.Config{Type: cc.ContainerRuntime, Runner: r}
tstromberg marked this conversation as resolved.
Show resolved Hide resolved
cr, err := cruntime.New(config)
if err != nil {
exit.WithError("Failed runtime", err)
}

glog.Infof("namespaces: %v keys: %v", namespaces, viper.AllSettings())
if allNamespaces {
namespaces = nil //all
} else {
if len(namespaces) == 0 {
exit.WithCodeT(exit.BadUsage, "Use -A to specify all namespaces")
}
}

err = cluster.Pause(cr, r, namespaces)
if err != nil {
exit.WithError("Pause", err)
}

if namespaces == nil {
out.T(out.Pause, "Paused all namespaces in the '{{.name}}' cluster", out.V{"name": cc.Name})
} else {
out.T(out.Pause, "Paused the following namespaces in '{{.name}}': {{.namespaces}}", out.V{"name": cc.Name, "namespaces": strings.Join(namespaces, ", ")})
}
}

func init() {
pauseCmd.Flags().StringSliceVarP(&namespaces, "--namespaces", "n", cluster.DefaultNamespaces, "namespaces to pause")
pauseCmd.Flags().BoolVarP(&allNamespaces, "all-namespaces", "A", false, "If set, pause all namespaces")
}
2 changes: 2 additions & 0 deletions cmd/minikube/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ func init() {
stopCmd,
deleteCmd,
dashboardCmd,
pauseCmd,
unpauseCmd,
},
},
{
Expand Down
165 changes: 86 additions & 79 deletions cmd/minikube/cmd/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ import (
"strings"
"text/template"

"github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/state"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
Expand All @@ -40,16 +42,13 @@ import (
var statusFormat string
var output string

// KubeconfigStatus represents the kubeconfig status
var KubeconfigStatus = struct {
Configured string
Misconfigured string
}{
Configured: `Configured`,
Misconfigured: `Misconfigured`,
}
const (
// Additional states used by kubeconfig
Configured = "Configured" // analagous to state.Saved
Misconfigured = "Misconfigured" // analagous to state.Error
)

// Status represents the status
// Status holds string representations of libmachine.state.State
tstromberg marked this conversation as resolved.
Show resolved Hide resolved
type Status struct {
Host string
Kubelet string
Expand Down Expand Up @@ -81,89 +80,98 @@ var statusCmd = &cobra.Command{
exit.UsageT("Cannot use both --output and --format options")
}

var returnCode = 0
api, err := machine.NewAPIClient()
if err != nil {
exit.WithCodeT(exit.Unavailable, "Error getting client: {{.error}}", out.V{"error": err})
}
defer api.Close()

machineName := viper.GetString(config.MachineProfile)

hostSt, err := cluster.GetHostStatus(api, machineName)
st, err := status(api, machineName)
if err != nil {
exit.WithError("Error getting host status", err)
}

kubeletSt := state.None.String()
kubeconfigSt := state.None.String()
apiserverSt := state.None.String()

if hostSt == state.Running.String() {
clusterBootstrapper, err := getClusterBootstrapper(api, viper.GetString(cmdcfg.Bootstrapper))
if err != nil {
exit.WithError("Error getting bootstrapper", err)
}
kubeletSt, err = clusterBootstrapper.GetKubeletStatus()
if err != nil {
glog.Warningf("kubelet err: %v", err)
returnCode |= clusterNotRunningStatusFlag
} else if kubeletSt != state.Running.String() {
returnCode |= clusterNotRunningStatusFlag
}

ip, err := cluster.GetHostDriverIP(api, machineName)
if err != nil {
glog.Errorln("Error host driver ip status:", err)
}

apiserverPort, err := kubeconfig.Port(machineName)
if err != nil {
// Fallback to presuming default apiserver port
apiserverPort = constants.APIServerPort
}

apiserverSt, err = clusterBootstrapper.GetAPIServerStatus(ip, apiserverPort)
if err != nil {
glog.Errorln("Error apiserver status:", err)
} else if apiserverSt != state.Running.String() {
returnCode |= clusterNotRunningStatusFlag
}

ks, err := kubeconfig.IsClusterInConfig(ip, machineName)
if err != nil {
glog.Errorln("Error kubeconfig status:", err)
}
if ks {
kubeconfigSt = KubeconfigStatus.Configured
} else {
kubeconfigSt = KubeconfigStatus.Misconfigured
returnCode |= k8sNotRunningStatusFlag
}
} else {
returnCode |= minikubeNotRunningStatusFlag
}

status := Status{
Host: hostSt,
Kubelet: kubeletSt,
APIServer: apiserverSt,
Kubeconfig: kubeconfigSt,
glog.Errorf("status error: %v", err)
}

switch strings.ToLower(output) {
case "text":
printStatusText(status)
printStatusText(st)
case "json":
printStatusJSON(status)
printStatusJSON(st)
default:
exit.WithCodeT(exit.BadUsage, fmt.Sprintf("invalid output format: %s. Valid values: 'text', 'json'", output))
}

os.Exit(returnCode)
os.Exit(exitCode(st))
},
}

func exitCode(st *Status) int {
tstromberg marked this conversation as resolved.
Show resolved Hide resolved
c := 0
if st.Host != state.Running.String() {
c |= minikubeNotRunningStatusFlag
}
if st.APIServer != state.Running.String() || st.Kubelet != state.Running.String() {
c |= clusterNotRunningStatusFlag
}
if st.Kubeconfig != Configured {
c |= k8sNotRunningStatusFlag
}
return c
}

func status(api libmachine.API, name string) (*Status, error) {
st := &Status{}
hs, err := cluster.GetHostStatus(api, name)
if err != nil {
return st, errors.Wrap(err, "host")
}
st.Host = hs
if st.Host != state.Running.String() {
return st, nil
}

bs, err := getClusterBootstrapper(api, viper.GetString(cmdcfg.Bootstrapper))
if err != nil {
return st, errors.Wrap(err, "bootstrapper")
}

st.Kubelet, err = bs.GetKubeletStatus()
if err != nil {
glog.Warningf("kubelet err: %v", err)
st.Kubelet = state.Error.String()
}

ip, err := cluster.GetHostDriverIP(api, name)
if err != nil {
glog.Errorln("Error host driver ip status:", err)
st.APIServer = state.Error.String()
return st, err
}

port, err := kubeconfig.Port(name)
if err != nil {
glog.Warningf("unable to get port: %v", err)
port = constants.APIServerPort
}

st.APIServer, err = bs.GetAPIServerStatus(ip, port)
if err != nil {
glog.Errorln("Error apiserver status:", err)
st.APIServer = state.Error.String()
}

ks, err := kubeconfig.IsClusterInConfig(ip, name)
if err != nil {
glog.Errorln("Error kubeconfig status:", err)
}
if ks {
st.Kubeconfig = Configured
} else {
st.Kubeconfig = Misconfigured
}
return st, nil
}

func init() {
statusCmd.Flags().StringVarP(&statusFormat, "format", "f", defaultStatusFormat,
`Go template format string for the status output. The format for Go templates can be found here: https://golang.org/pkg/text/template/
Expand All @@ -172,25 +180,24 @@ For the list accessible variables for the template, see the struct values here:
`minikube status --output OUTPUT. json, text`)
}

var printStatusText = func(status Status) {
var printStatusText = func(st *Status) {
tmpl, err := template.New("status").Parse(statusFormat)
if err != nil {
exit.WithError("Error creating status template", err)
}
err = tmpl.Execute(os.Stdout, status)
err = tmpl.Execute(os.Stdout, st)
if err != nil {
exit.WithError("Error executing status template", err)
}
if status.Kubeconfig == KubeconfigStatus.Misconfigured {
if st.Kubeconfig == Misconfigured {
out.WarningT("Warning: Your kubectl is pointing to stale minikube-vm.\nTo fix the kubectl context, run `minikube update-context`")
}
}

var printStatusJSON = func(status Status) {

jsonString, err := json.Marshal(status)
var printStatusJSON = func(st *Status) {
js, err := json.Marshal(st)
if err != nil {
exit.WithError("Error converting status to json", err)
}
out.String(string(jsonString))
out.String(string(js))
}
Loading