Skip to content

Implement schedule stop for unix #9503

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

Merged
merged 25 commits into from
Nov 12, 2020
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
28 changes: 26 additions & 2 deletions cmd/minikube/cmd/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ limitations under the License.
package cmd

import (
"log"
"runtime"
"time"

"github.com/docker/machine/libmachine"
Expand All @@ -35,13 +37,15 @@ import (
"k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/minikube/out/register"
"k8s.io/minikube/pkg/minikube/reason"
"k8s.io/minikube/pkg/minikube/schedule"
"k8s.io/minikube/pkg/minikube/style"
"k8s.io/minikube/pkg/util/retry"
)

var (
stopAll bool
keepActive bool
stopAll bool
keepActive bool
scheduledStopDuration time.Duration
)

// stopCmd represents the stop command
Expand All @@ -55,6 +59,10 @@ var stopCmd = &cobra.Command{
func init() {
stopCmd.Flags().BoolVar(&stopAll, "all", false, "Set flag to stop all profiles (clusters)")
stopCmd.Flags().BoolVar(&keepActive, "keep-context-active", false, "keep the kube-context active after cluster is stopped. Defaults to false.")
stopCmd.Flags().DurationVar(&scheduledStopDuration, "schedule", 0*time.Second, "Set flag to stop cluster after a set amount of time (e.g. --schedule=5m)")
if err := stopCmd.Flags().MarkHidden("schedule"); err != nil {
klog.Info("unable to mark --schedule flag as hidden")
}
stopCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "Format to print stdout in. Options include: [text,json]")

if err := viper.GetViper().BindPFlags(stopCmd.Flags()); err != nil {
Expand Down Expand Up @@ -83,6 +91,22 @@ func runStop(cmd *cobra.Command, args []string) {
profilesToStop = append(profilesToStop, cname)
}

// Kill any existing scheduled stops
if err := schedule.KillExisting(profilesToStop); err != nil {
log.Printf("error killing existing scheduled stops: %v", err)
}

if scheduledStopDuration != 0 {
if runtime.GOOS == "windows" {
exit.Message(reason.Usage, "the --schedule flag is currently not supported on windows")
}
if err := schedule.Daemonize(profilesToStop, scheduledStopDuration); err != nil {
exit.Message(reason.DaemonizeError, "unable to daemonize: {{.err}}", out.V{"err": err.Error()})
}
klog.Infof("sleeping %s before completing stop...", scheduledStopDuration.String())
time.Sleep(scheduledStopDuration)
}

stoppedNodes := 0
for _, profile := range profilesToStop {
stoppedNodes = stopProfile(profile)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5 // indirect
github.com/Parallels/docker-machine-parallels/v2 v2.0.1
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
github.com/VividCortex/godaemon v0.0.0-20201030160542-15e3f4925a21
github.com/blang/semver v3.5.0+incompatible
github.com/c4milo/gotoolkit v0.0.0-20170318115440-bcc06269efa9 // indirect
github.com/cenkalti/backoff v2.2.1+incompatible
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUW
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/VividCortex/godaemon v0.0.0-20201030160542-15e3f4925a21 h1:Pgxfz/g+XyfRjYqRjKUFpDh5IciFncmA/Uio6AU/z9g=
github.com/VividCortex/godaemon v0.0.0-20201030160542-15e3f4925a21/go.mod h1:Y8CJ3IwPIAkMhv/rRUWIlczaeqd9ty9yrl+nc2AbaL4=
github.com/afbjorklund/go-containerregistry v0.0.0-20200902152226-fbad78ec2813 h1:0tskN1ipU/BBrpoEIy0rdZS9jf5+wdP6IMRak8Iu/YE=
github.com/afbjorklund/go-containerregistry v0.0.0-20200902152226-fbad78ec2813/go.mod h1:npTSyywOeILcgWqd+rvtzGWflIPPcBQhYoOONaY4ltM=
github.com/afbjorklund/go-getter v1.4.1-0.20201020145846-c0da14b4bffe h1:TdcuDqk4ArmYI8cbeeL/RM5BPciDOaWpGZoPoT3OziQ=
Expand Down
8 changes: 8 additions & 0 deletions pkg/minikube/config/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ type ClusterConfig struct {
Addons map[string]bool
VerifyComponents map[string]bool // map of components to verify and wait for after start.
StartHostTimeout time.Duration
ScheduledStop *ScheduledStopConfig
ExposedPorts []string // Only used by the docker and podman driver
}

Expand Down Expand Up @@ -138,3 +139,10 @@ type VersionedExtraOption struct {
// flag is applied to
GreaterThanOrEqual semver.Version
}

// ScheduledStopConfig contains information around scheduled stop
// not yet used, will be used to show status of scheduled stop
type ScheduledStopConfig struct {
InitiationTime int64
Duration time.Duration
}
6 changes: 6 additions & 0 deletions pkg/minikube/localpath/localpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package localpath
import (
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
Expand Down Expand Up @@ -86,6 +87,11 @@ func ClientCert(name string) string {
return new
}

// PID returns the path to the pid file used by profile for scheduled stop
func PID(profile string) string {
return path.Join(Profile(profile), "pid")
}

// ClientKey returns client certificate path, used by kubeconfig
func ClientKey(name string) string {
new := filepath.Join(Profile(name), "client.key")
Expand Down
1 change: 1 addition & 0 deletions pkg/minikube/reason/reason.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ var (
InternalYamlMarshal = Kind{ID: "MK_YAML_MARSHAL", ExitCode: ExProgramError}
InternalCredsNotFound = Kind{ID: "MK_CREDENTIALS_NOT_FOUND", ExitCode: ExProgramNotFound, Style: style.Shrug}
InternalSemverParse = Kind{ID: "MK_SEMVER_PARSE", ExitCode: ExProgramError}
DaemonizeError = Kind{ID: "MK_DAEMONIZE", ExitCode: ExProgramError}

RsrcInsufficientCores = Kind{ID: "RSRC_INSUFFICIENT_CORES", ExitCode: ExInsufficientCores, Style: style.UnmetRequirement}
RsrcInsufficientDarwinDockerCores = Kind{
Expand Down
80 changes: 80 additions & 0 deletions pkg/minikube/schedule/daemonize_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// +build !windows

/*
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 schedule

import (
"fmt"
"io/ioutil"
"os"
"strconv"
"time"

"github.com/VividCortex/godaemon"
"github.com/pkg/errors"
"k8s.io/klog/v2"
"k8s.io/minikube/pkg/minikube/localpath"
)

// KillExisting kills existing scheduled stops
func KillExisting(profiles []string) error {
for _, profile := range profiles {
file := localpath.PID(profile)
f, err := ioutil.ReadFile(file)
if os.IsNotExist(err) {
return nil
}
defer os.Remove(file)
if err != nil {
return errors.Wrapf(err, "reading %s", file)
}
pid, err := strconv.Atoi(string(f))
if err != nil {
return errors.Wrapf(err, "converting %v to int", string(f))
}
p, err := os.FindProcess(pid)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check that the pid is minikube process before killing it. Otherwise this will kill random processes.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When minikube stop daemonizes, it saves its own PID via os.Getpid() to a file, and that is the PID that is being killed here.

I'm not sure how a random process could be killed from this code, could you explain if you still think that's the case?

if err != nil {
return errors.Wrap(err, "finding process")
}
klog.Infof("killing process %v as it is an old scheduled stop", pid)
if err := p.Kill(); err != nil {
return errors.Wrapf(err, "killing %v", pid)
}
}
return nil
}

func daemonize(profiles []string, duration time.Duration) error {
_, _, err := godaemon.MakeDaemon(&godaemon.DaemonAttr{})
if err != nil {
return err
}
// now that this process has daemonized, it has a new PID
pid := os.Getpid()
return savePIDs(pid, profiles)
}

func savePIDs(pid int, profiles []string) error {
for _, p := range profiles {
file := localpath.PID(p)
if err := ioutil.WriteFile(file, []byte(fmt.Sprintf("%v", pid)), 0644); err != nil {
return err
}
}
return nil
}
33 changes: 33 additions & 0 deletions pkg/minikube/schedule/daemonize_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// +build windows

/*
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 schedule

import (
"fmt"
"time"
)

// KillExisting kills existing scheduled stops
func KillExisting(profiles []string) error {
return fmt.Errorf("not yet implemented for windows")
}

func daemonize(profiles []string, duration time.Duration) error {
return fmt.Errorf("not yet implemented for windows")
}
51 changes: 51 additions & 0 deletions pkg/minikube/schedule/schedule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
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 schedule

import (
"time"

"github.com/pkg/errors"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/driver"
"k8s.io/minikube/pkg/minikube/mustload"
"k8s.io/minikube/pkg/minikube/out"
)

// Daemonize daemonizes minikube so that scheduled stop happens as expected
func Daemonize(profiles []string, duration time.Duration) error {
// save current time and expected duration in config
scheduledStop := &config.ScheduledStopConfig{
InitiationTime: time.Now().Unix(),
Duration: duration,
}
var daemonizeProfiles []string
for _, p := range profiles {
_, cc := mustload.Partial(p)
if driver.BareMetal(cc.Driver) {
out.WarningT("scheduled stop is not supported on the none driver, skipping scheduling")
continue
}
daemonizeProfiles = append(daemonizeProfiles, p)
cc.ScheduledStop = scheduledStop
if err := config.SaveProfile(p, cc); err != nil {
return errors.Wrap(err, "saving profile")
}
}

return daemonize(daemonizeProfiles, duration)
}
Loading