Skip to content

Commit

Permalink
Merge pull request #5962 from tstromberg/pause
Browse files Browse the repository at this point in the history
Add 'pause' command to freeze Kubernetes cluster
  • Loading branch information
tstromberg authored Jan 24, 2020
2 parents 5fa7935 + a9bc13b commit 34e4c19
Show file tree
Hide file tree
Showing 21 changed files with 938 additions and 249 deletions.
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
103 changes: 103 additions & 0 deletions cmd/minikube/cmd/pause.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
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)
}

cr, err := cruntime.New(cruntime.Config{Type: cc.ContainerRuntime, Runner: r})
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")
}

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

if namespaces == nil {
out.T(out.Unpause, "Paused kubelet and {{.count}} containers", out.V{"count": len(ids)})
} else {
out.T(out.Unpause, "Paused kubelet and {{.count}} containers in: {{.namespaces}}", out.V{"count": len(ids), "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
179 changes: 96 additions & 83 deletions cmd/minikube/cmd/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ package cmd
import (
"encoding/json"
"fmt"
"io"
"os"
"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 +43,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" // analogous to state.Saved
Misconfigured = "Misconfigured" // analogous to state.Error
)

// Status represents the status
// Status holds string representations of component states
type Status struct {
Host string
Kubelet string
Expand Down Expand Up @@ -81,87 +81,99 @@ 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)
glog.Errorf("status error: %v", 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)
switch strings.ToLower(output) {
case "text":
if err := statusText(st, os.Stdout); err != nil {
exit.WithError("status text failure", err)
}
kubeletSt, err = clusterBootstrapper.GetKubeletStatus()
if err != nil {
glog.Warningf("kubelet err: %v", err)
returnCode |= clusterNotRunningStatusFlag
} else if kubeletSt != state.Running.String() {
returnCode |= clusterNotRunningStatusFlag
case "json":
if err := statusJSON(st, os.Stdout); err != nil {
exit.WithError("status json failure", err)
}
default:
exit.WithCodeT(exit.BadUsage, fmt.Sprintf("invalid output format: %s. Valid values: 'text', 'json'", output))
}

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

apiserverPort, err := kubeconfig.Port(machineName)
if err != nil {
// Fallback to presuming default apiserver port
apiserverPort = constants.APIServerPort
}
func exitCode(st *Status) int {
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
}

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

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
}
bs, err := getClusterBootstrapper(api, viper.GetString(cmdcfg.Bootstrapper))
if err != nil {
return st, errors.Wrap(err, "bootstrapper")
}

status := Status{
Host: hostSt,
Kubelet: kubeletSt,
APIServer: apiserverSt,
Kubeconfig: kubeconfigSt,
}
st.Kubelet, err = bs.GetKubeletStatus()
if err != nil {
glog.Warningf("kubelet err: %v", err)
st.Kubelet = state.Error.String()
}

switch strings.ToLower(output) {
case "text":
printStatusText(status)
case "json":
printStatusJSON(status)
default:
exit.WithCodeT(exit.BadUsage, fmt.Sprintf("invalid output format: %s. Valid values: 'text', 'json'", output))
}
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
}

os.Exit(returnCode)
},
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()
}

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

func init() {
Expand All @@ -172,25 +184,26 @@ For the list accessible variables for the template, see the struct values here:
`minikube status --output OUTPUT. json, text`)
}

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

var printStatusJSON = func(status Status) {

jsonString, err := json.Marshal(status)
func statusJSON(st *Status, w io.Writer) error {
js, err := json.Marshal(st)
if err != nil {
exit.WithError("Error converting status to json", err)
return err
}
out.String(string(jsonString))
_, err = w.Write(js)
return err
}
Loading

0 comments on commit 34e4c19

Please sign in to comment.