Skip to content

Commit

Permalink
Add signal for exit
Browse files Browse the repository at this point in the history
  • Loading branch information
wzshiming committed Jan 21, 2025
1 parent f2f0b28 commit fb32247
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 2 deletions.
5 changes: 3 additions & 2 deletions cmd/crproxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/daocloud/crproxy/cmd/crproxy/cluster"
csync "github.com/daocloud/crproxy/cmd/crproxy/sync"
"github.com/daocloud/crproxy/internal/signals"
"github.com/spf13/cobra"

_ "github.com/daocloud/crproxy/storage/driver/obs"
Expand All @@ -26,11 +27,11 @@ var (
return cmd.Usage()
},
}
pflag = cmd.Flags()
)

func main() {
err := cmd.Execute()
ctx := signals.SetupSignalContext()
err := cmd.ExecuteContext(ctx)
if err != nil {
slog.Error("execute failed", "error", err)
os.Exit(1)
Expand Down
32 changes: 32 additions & 0 deletions internal/signals/signals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package signals

import (
"context"
"os"
"os/signal"
)

var (
onlyOneSignalHandler = make(chan struct{})
shutdownHandler chan os.Signal
)

// SetupSignalContext is same as SetupSignalHandler, but a context.Context is returned.
// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
// be called once.
func SetupSignalContext() context.Context {
close(onlyOneSignalHandler) // panics when called twice

shutdownHandler = make(chan os.Signal, 2)

ctx, cancel := context.WithCancel(context.Background())
signal.Notify(shutdownHandler, shutdownSignals...)
go func() {
<-shutdownHandler
cancel()
<-shutdownHandler
os.Exit(1) // second signal. Exit directly.
}()

return ctx
}
10 changes: 10 additions & 0 deletions internal/signals/signals_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//go:build !windows

package signals

import (
"os"
"syscall"
)

var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
9 changes: 9 additions & 0 deletions internal/signals/signals_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//go:build windows

package signals

import (
"os"
)

var shutdownSignals = []os.Signal{os.Interrupt}

0 comments on commit fb32247

Please sign in to comment.