trigger the OnTerminate hook and use a buffered chan instead of wg

This commit is contained in:
Gani Georgiev 2023-05-04 15:12:28 +03:00
parent 4c57968d89
commit 92f21e3355
1 changed files with 12 additions and 17 deletions

View File

@ -5,7 +5,6 @@ import (
"os/signal" "os/signal"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"syscall" "syscall"
"github.com/fatih/color" "github.com/fatih/color"
@ -155,37 +154,33 @@ func (pb *PocketBase) Execute() error {
} }
} }
var wg sync.WaitGroup done := make(chan bool, 1)
wg.Add(1)
// wait for interrupt signal to gracefully shutdown the application // wait for interrupt signal to gracefully shutdown the application
go func() { go func() {
defer wg.Done() sigch := make(chan os.Signal, 1)
quit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked signal.Notify(sigch, os.Interrupt, syscall.SIGTERM)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM) <-sigch
<-quit done <- true
}() }()
// execute the root command // execute the root command
go func() { go func() {
defer wg.Done()
if err := pb.RootCmd.Execute(); err != nil { if err := pb.RootCmd.Execute(); err != nil {
// @todo replace with db log once generalized logs are added // @todo replace with db log once generalized logs are added
// (note may need to update the existing commands to not silence errors) // (note may need to update the existing commands to not silence errors)
color.Red(err.Error()) color.Red(err.Error())
} }
done <- true
}() }()
wg.Wait() <-done
// cleanup // trigger app cleanups
return pb.onTerminate() return pb.OnTerminate().Trigger(&core.TerminateEvent{
} App: pb,
})
// onTerminate tries to release the app resources on app termination.
func (pb *PocketBase) onTerminate() error {
return pb.ResetBootstrapState()
} }
// eagerParseFlags parses the global app flags before calling pb.RootCmd.Execute(). // eagerParseFlags parses the global app flags before calling pb.RootCmd.Execute().