simplify signal handling for cobra context

Signed-off-by: Tonis Tiigi <tonistiigi@gmail.com>
This commit is contained in:
Tonis Tiigi
2024-01-19 16:44:30 -08:00
parent 650a7af0ae
commit 147c7135b0
16 changed files with 33 additions and 95 deletions

View File

@@ -1,13 +1,6 @@
package cobrautil
import (
"context"
"os"
"os/signal"
"github.com/moby/buildkit/util/bklog"
detect "github.com/moby/buildkit/util/tracing/env"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@@ -58,35 +51,3 @@ func MarkCommandExperimental(c *cobra.Command) {
c.Annotations[annotationExperimentalCLI] = ""
c.Short += " (EXPERIMENTAL)"
}
// ConfigureContext sets up signal handling and hooks into the command's
// context so that it will be cancelled when signalled, as well as implementing
// the "hard exit after 3 signals" logic. It also configures OTEL tracing
// for the relevant context.
func ConfigureContext(fn func(*cobra.Command, []string) error) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
ctx := detect.InitContext(cmd.Context())
cancellableCtx, cancel := context.WithCancelCause(ctx)
ctx = cancellableCtx
signalLimit := 3
s := make(chan os.Signal, signalLimit)
signal.Notify(s, interruptSignals...)
go func() {
retries := 0
for {
<-s
retries++
err := errors.Errorf("got %d SIGTERM/SIGINTs, forcing shutdown", retries)
cancel(err)
if retries >= signalLimit {
bklog.G(ctx).Errorf(err.Error())
os.Exit(1)
}
}
}()
cmd.SetContext(ctx)
return fn(cmd, args)
}
}

View File

@@ -1,10 +0,0 @@
//go:build !windows
package cobrautil
import (
"golang.org/x/sys/unix"
"os"
)
var interruptSignals = []os.Signal{unix.SIGTERM, unix.SIGINT}

View File

@@ -1,9 +0,0 @@
//go:build windows
package cobrautil
import (
"os"
)
var interruptSignals = []os.Signal{os.Interrupt}