Skip to content

Commit

Permalink
vetu run: support graceful termination (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
edigaryev authored Sep 18, 2024
1 parent b05dddc commit 5a5130e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
3 changes: 2 additions & 1 deletion cmd/vetu/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/cirruslabs/vetu/internal/command"
"github.com/cirruslabs/vetu/internal/version"
"github.com/getsentry/sentry-go"
"golang.org/x/sys/unix"
"log"
"os"
"os/signal"
Expand Down Expand Up @@ -54,7 +55,7 @@ func main() {
})

// Set up a signal-interruptible context
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
ctx, cancel := signal.NotifyContext(context.Background(), unix.SIGINT, unix.SIGTERM)

// Disable log timestamping
log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime))
Expand Down
26 changes: 25 additions & 1 deletion internal/command/run/run.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package run

import (
"context"
"errors"
"fmt"
"github.com/cirruslabs/vetu/internal/externalcommand/cloudhypervisor"
"github.com/cirruslabs/vetu/internal/filelock"
Expand All @@ -16,10 +18,12 @@ import (
"github.com/cirruslabs/vetu/internal/vmdirectory"
"github.com/samber/lo"
"github.com/spf13/cobra"
"golang.org/x/sys/unix"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)

var netBridged string
Expand Down Expand Up @@ -182,5 +186,25 @@ func runRun(cmd *cobra.Command, args []string) error {
hv.Stderr = os.Stderr
hv.Stdin = os.Stdin

return hv.Run()
// Graceful Cloud Hypervisor termination[1]
//
// [1]: https://www.cloudhypervisor.org/blog/cloud-hypervisor-v0.11.0-released/#sigtermsigint-interrupt-signal-handling
hv.Cancel = func() error {
return hv.Process.Signal(unix.SIGTERM)
}

// If Cancel() fails to terminate the Cloud Hypervisor for some reason,
// ensure that it will eventually be killed after some time.
hv.WaitDelay = 30 * time.Second

if err := hv.Run(); err != nil {
// Context cancellation is not an error
if errors.Is(err, context.Canceled) {
return nil
}

return err
}

return nil
}
1 change: 1 addition & 0 deletions internal/command/stop/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ func runStop(cmd *cobra.Command, args []string) error {

return fmt.Errorf("VM is still running")
}, retry.Context(gracefulTerminationCtx),
retry.Attempts(0),
retry.DelayType(retry.FixedDelay),
retry.Delay(100*time.Millisecond),
)
Expand Down

0 comments on commit 5a5130e

Please sign in to comment.