Configure signals for graceful shutdown
All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 37s

Signed-off-by: Jan Tytgat <jan.tytgat@corelayer.eu>
This commit is contained in:
Jan Tytgat
2025-04-23 12:52:11 +02:00
parent 4fab7c8554
commit b153b7f837
2 changed files with 57 additions and 9 deletions

View File

@ -3,6 +3,7 @@ package application
import (
"context"
"fmt"
"os/signal"
"github.com/spf13/cobra"
)
@ -21,18 +22,62 @@ func New(c Config) (Application, error) {
return &application{
cmd: cmd,
config: c,
}, nil
}
type application struct {
cmd *cobra.Command
config Config
}
func (a *application) Start(ctx context.Context) error {
return a.cmd.ExecuteContext(ctx)
sigCtx, sigStop := signal.NotifyContext(ctx, a.config.ShutdownSignals...)
defer sigStop() // Ensure that this gets called.
// Result channel for command
chExe := make(chan error)
go a.execute(sigCtx, chExe)
select {
// sigCtx.Done() returns a channel that will have a message
// when the context is cancelled. We wait for that signal, which means
// we received the signal, or our context was cancelled for some other reason.
case <-sigCtx.Done():
sigStop()
return a.Shutdown()
case err := <-chExe:
return err
}
}
func (a *application) Shutdown() error {
fmt.Println("Shutdown")
switch a.config.EnableGracefulShutdown {
case true:
return a.gracefulShutdown()
case false:
return a.shutdown()
// default:
// return a.shutdown()
}
return nil
}
func (a *application) execute(ctx context.Context, chErr chan error) {
chErr <- a.cmd.ExecuteContext(ctx)
}
func (a *application) gracefulShutdown() error {
fmt.Println("graceful shutdown")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), a.config.ShutdownTimeout)
defer shutdownCancel()
<-shutdownCtx.Done()
return nil
}
func (a *application) shutdown() error {
fmt.Println("shutdown")
return nil
}

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
@ -20,15 +21,17 @@ func main() {
Title: "Main Test",
Banner: "",
Version: "0.1.0-alpha.0+metadata.20101112",
EnableGracefulShutdown: false,
EnableGracefulShutdown: true,
OverrideRunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("overrideRunE")
time.Sleep(5 * time.Second)
fmt.Println("overrideRunE done")
return nil
},
PersistentPreRunE: nil,
PersistentPostRunE: nil,
ShutdownSignals: nil,
ShutdownTimeout: 0,
// ShutdownSignals: []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT},
ShutdownTimeout: 1 * time.Second,
SubCommands: nil,
SubCommandInitializeFunc: nil,
ValidArgs: nil,