Skip to content

Commit

Permalink
Merge pull request #2296 from FabianKramm/main
Browse files Browse the repository at this point in the history
refactor: improve sleep mode exit
  • Loading branch information
FabianKramm authored Sep 9, 2022
2 parents fbff37e + 5cea0e2 commit 8c393e2
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 37 deletions.
8 changes: 8 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"flag"
"fmt"
"github.com/loft-sh/devspace/pkg/devspace/kill"
"io/ioutil"
"os"
"strings"
Expand Down Expand Up @@ -209,6 +210,13 @@ func BuildRoot(f factory.Factory, excludePlugins bool) *cobra.Command {
})
persistentFlags := rootCmd.PersistentFlags()
globalFlags = flags.SetGlobalFlags(persistentFlags)
kill.SetStopFunction(func(message string) {
if message == "" {
os.Exit(1)
} else {
f.GetLog().Fatal(message)
}
})

rootCmd.SetUsageTemplate(`Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
Expand Down
20 changes: 20 additions & 0 deletions cmd/run_pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/loft-sh/devspace/pkg/devspace/dev"
"github.com/loft-sh/devspace/pkg/devspace/devpod"
"github.com/loft-sh/devspace/pkg/devspace/hook"
"github.com/loft-sh/devspace/pkg/devspace/kill"
"github.com/loft-sh/devspace/pkg/devspace/kubectl"
"github.com/loft-sh/devspace/pkg/devspace/pipeline"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/types"
Expand All @@ -24,6 +25,7 @@ import (
"github.com/loft-sh/devspace/pkg/util/interrupt"
"github.com/loft-sh/devspace/pkg/util/log"
"github.com/loft-sh/devspace/pkg/util/message"
"github.com/mgutz/ansi"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -459,6 +461,16 @@ func runPipeline(ctx devspacecontext.Context, args []string, options *CommandOpt

// get deploy pipeline
pipe := pipeline.NewPipeline(ctx.Config().Config().Name, devPodManager, dependencyRegistry, configPipeline, options.Options)
kill.SetStopFunction(func(message string) {
if message != "" {
ctx.Log().WriteString(logrus.FatalLevel, "\n"+ansi.Color("fatal", "red+b")+" "+message+"\n")
}

err = pipe.Close()
if err != nil {
ctx.Log().Debugf("Error closing pipeline: %v", err)
}
})

// start ui & open
serv, err := dev.UI(ctx, options.UIPort, options.ShowUI, pipe)
Expand All @@ -478,13 +490,21 @@ func runPipeline(ctx devspacecontext.Context, args []string, options *CommandOpt
// start pipeline
err = pipe.Run(ctx.WithLogger(log.NewStreamLoggerWithFormat(stdoutWriter, stderrWriter, ctx.Log().GetLevel(), log.TimeFormat)), args)
if err != nil {
if err == context.Canceled {
return nil
}

return err
}
ctx.Log().Debugf("Wait for dev to finish")

// wait for dev
err = pipe.WaitDev()
if err != nil {
if err == context.Canceled {
return nil
}

return err
}

Expand Down
9 changes: 5 additions & 4 deletions pkg/devspace/devpod/devpod.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"fmt"
"github.com/loft-sh/devspace/pkg/devspace/kill"
"io"
"net/http"
"os"
Expand Down Expand Up @@ -420,8 +421,8 @@ func (d *devPod) startAttach(ctx devspacecontext.Context, devContainer *latest.D
}

// kill ourselves here
if !opts.ContinueOnTerminalExit && opts.KillApplication != nil {
go opts.KillApplication()
if !opts.ContinueOnTerminalExit {
kill.StopDevSpace("")
} else {
parent.Kill(nil)
}
Expand Down Expand Up @@ -460,8 +461,8 @@ func (d *devPod) startTerminal(ctx devspacecontext.Context, devContainer *latest
}

// kill ourselves here
if !opts.ContinueOnTerminalExit && opts.KillApplication != nil {
go opts.KillApplication()
if !opts.ContinueOnTerminalExit {
kill.StopDevSpace("")
} else {
parent.Kill(nil)
}
Expand Down
3 changes: 0 additions & 3 deletions pkg/devspace/devpod/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ type Options struct {
DisablePortForwarding bool `long:"disable-port-forwarding" description:"If enabled will not start any port forwarding configuration"`
DisablePodReplace bool `long:"disable-pod-replace" description:"If enabled will not replace any pods"`
DisableOpen bool `long:"disable-open" description:"If enabled will not replace any pods"`

// KillApplication kills the whole pipeline including all dev pods
KillApplication func()
}

type Manager interface {
Expand Down
22 changes: 22 additions & 0 deletions pkg/devspace/kill/kill.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package kill

import "sync"

// stopDevSpace can be used to stop DevSpace globally
var stopDevSpace func(message string)
var stopDevSpaceMutex sync.Mutex

func StopDevSpace(message string) {
stopDevSpaceMutex.Lock()
defer stopDevSpaceMutex.Unlock()

// don't block here
go stopDevSpace(message)
}

func SetStopFunction(stopFn func(message string)) {
stopDevSpaceMutex.Lock()
defer stopDevSpaceMutex.Unlock()

stopDevSpace = stopFn
}
20 changes: 14 additions & 6 deletions pkg/devspace/kubectl/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"github.com/loft-sh/devspace/pkg/devspace/config/localcache"
"github.com/loft-sh/devspace/pkg/devspace/kill"
"github.com/loft-sh/devspace/pkg/devspace/kubectl/util"
"github.com/loft-sh/devspace/pkg/devspace/upgrade"
"github.com/loft-sh/devspace/pkg/util/idle"
Expand Down Expand Up @@ -118,7 +119,7 @@ func NewClientFromContext(context, namespace string, switchContext bool, kubeLoa
requestType: "Regular",
callback: func(response *http.Response) {
if response.Header.Get("X-DevSpace-Response-Type") == "Blocked" {
log.GetInstance().Fatalf("Targeted Kubernetes environment has begun sleeping. Please restart DevSpace to wake up the environment")
kill.StopDevSpace("Targeted Kubernetes environment has begun sleeping. Please restart DevSpace to wake up the environment")
}
},
}
Expand Down Expand Up @@ -329,7 +330,7 @@ func wakeUpAndPing(ctx context.Context, client Client, log log.Logger) error {
requestType: "Ping",
callback: func(response *http.Response) {
if response.Header.Get("X-DevSpace-Response-Type") == "Blocked" {
log.Fatalf("Targeted Kubernetes environment has begun sleeping. Please restart DevSpace to wake up the environment")
kill.StopDevSpace("Targeted Kubernetes environment has begun sleeping. Please restart DevSpace to wake up the environment")
}
},
}
Expand All @@ -356,7 +357,7 @@ func wakeUpAndPing(ctx context.Context, client Client, log log.Logger) error {
if err != nil {
log.Debugf("Error pinging Kubernetes environment: %v", err)
}
}, time.Minute*3)
}, time.Minute)
}()

return nil
Expand Down Expand Up @@ -416,9 +417,16 @@ func wakeUp(ctx context.Context, client Client, log log.Logger) error {
log.Infof("DevSpace is waking up the Kubernetes environment, please wait a moment...")

// wake up the environment
_, err = kubeClient.CoreV1().Pods(client.Namespace()).List(ctx, metav1.ListOptions{LabelSelector: "devspace=wakeup"})
if err != nil {
return errors.Wrap(err, "error waking up the environment")
waitErr := wait.PollImmediate(time.Second, time.Second*30, func() (done bool, err error) {
_, err = kubeClient.CoreV1().Pods(client.Namespace()).List(ctx, metav1.ListOptions{LabelSelector: "devspace=wakeup"})
if err != nil {
return false, nil
}

return true, nil
})
if waitErr != nil {
return errors.Wrap(err, "wake up environment")
}

return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package commands

import (
"fmt"
"github.com/jessevdk/go-flags"
"github.com/loft-sh/devspace/pkg/util/yamlutil"
"github.com/pkg/errors"
"strings"

devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
Expand All @@ -11,23 +13,28 @@ import (
"mvdan.cc/sh/v3/interp"
)

type GetConfigValueOptions struct{}

func GetConfigValue(ctx devspacecontext.Context, args []string) error {
ctx = ctx.WithLogger(ctx.Log().ErrorStreamOnly())
ctx.Log().Debugf("get_config_value %s", strings.Join(args, " "))
if len(args) != 1 {
options := &GetConfigValueOptions{}
args, err := flags.ParseArgs(options, args)
if err != nil {
return errors.Wrap(err, "parse args")
} else if len(args) != 1 {
return fmt.Errorf("usage: get_config_value deployments.my-deployment.helm.chart.name")
}

hc := interp.HandlerCtx(ctx.Context())
rawConfig := ctx.Config().Raw()

config := ctx.Config().RawBeforeConversion()
nodePath, err := yamlpath.NewPath(args[0])
if err != nil {
ctx.Log().Debugf("%v", err)
return nil
}

out, err := yaml.Marshal(rawConfig)
out, err := yaml.Marshal(config)
if err != nil {
ctx.Log().Debugf("%v", err)
return nil
Expand All @@ -45,11 +52,19 @@ func GetConfigValue(ctx devspacecontext.Context, args []string) error {
ctx.Log().Debugf("%v", err)
return nil
}

if len(nodes) < 1 {
return nil
}

_, _ = hc.Stdout.Write([]byte(nodes[0].Value))
if nodes[0].Kind == yaml.ScalarNode {
_, _ = hc.Stdout.Write([]byte(nodes[0].Value))
return nil
}

out, err = yaml.Marshal(nodes[0])
if err != nil {
return err
}
_, _ = hc.Stdout.Write(out)
return nil
}
15 changes: 0 additions & 15 deletions pkg/devspace/pipeline/engine/pipelinehandler/commands/start_dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
"github.com/loft-sh/devspace/pkg/devspace/devpod"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/types"
logpkg "github.com/loft-sh/devspace/pkg/util/log"
"github.com/loft-sh/devspace/pkg/util/stringutil"
"github.com/pkg/errors"
"strings"
Expand Down Expand Up @@ -72,19 +71,5 @@ func StartDev(ctx devspacecontext.Context, pipeline types.Pipeline, args []strin
} else {
return fmt.Errorf("either specify 'start_dev --all' or 'dev devConfig1 devConfig2'")
}
options.Options.KillApplication = func() {
killApplication(pipeline)
}
return pipeline.DevPodManager().StartMultiple(ctx, args, options.Options)
}

func killApplication(pipeline types.Pipeline) {
for pipeline.Parent() != nil {
pipeline = pipeline.Parent()
}

err := pipeline.Close()
if err != nil {
logpkg.GetInstance().Errorf("error closing pipeline: %v", err)
}
}
3 changes: 1 addition & 2 deletions pkg/util/extract/unzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"compress/gzip"
"fmt"
"io"
"log"
"os"
"path/filepath"
)
Expand Down Expand Up @@ -34,7 +33,7 @@ func (e *extractor) UntarGz(src, dest string) error {

uncompressedStream, err := gzip.NewReader(gzipStream)
if err != nil {
log.Fatal("ExtractTarGz: NewReader failed")
return fmt.Errorf("ExtractTarGz: NewReader failed")
}

tarReader := tar.NewReader(uncompressedStream)
Expand Down
4 changes: 3 additions & 1 deletion pkg/util/idle/idle.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package idle

import (
"fmt"
"github.com/loft-sh/devspace/pkg/devspace/kill"
"time"

"github.com/loft-sh/devspace/pkg/util/log"
Expand Down Expand Up @@ -48,7 +50,7 @@ func (m *monitor) Start(timeout time.Duration, log log.Logger) {
return
} else if duration > timeout {
// we exit here
log.Fatalf("Automatically exit DevSpace, because the user is inactive for %s. To disable automatic exiting, run with --inactivity-timeout=0", duration.String())
kill.StopDevSpace(fmt.Sprintf("Automatically exit DevSpace, because the user is inactive for %s. To disable automatic exiting, run with --inactivity-timeout=0", duration.String()))
}
}, time.Second*10)
}()
Expand Down

0 comments on commit 8c393e2

Please sign in to comment.