2022-05-05 01:56:21 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
2022-06-30 05:48:04 +00:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2022-05-05 01:56:21 +00:00
|
|
|
)
|
|
|
|
|
2022-07-19 09:13:35 +00:00
|
|
|
type ShutdownHandler func(ctx context.Context, wg *sync.WaitGroup)
|
|
|
|
|
2022-10-02 11:34:52 +00:00
|
|
|
//go:generate callbackgen -type GracefulShutdown
|
|
|
|
type GracefulShutdown struct {
|
2022-07-19 09:13:35 +00:00
|
|
|
shutdownCallbacks []ShutdownHandler
|
2022-05-05 01:56:21 +00:00
|
|
|
}
|
|
|
|
|
2022-06-30 05:48:04 +00:00
|
|
|
// Shutdown is a blocking call to emit all shutdown callbacks at the same time.
|
2022-10-11 06:22:46 +00:00
|
|
|
// The context object here should not be canceled context, you need to create a todo context.
|
|
|
|
func (g *GracefulShutdown) Shutdown(shutdownCtx context.Context) {
|
2022-05-05 01:56:21 +00:00
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(len(g.shutdownCallbacks))
|
2022-10-11 06:22:46 +00:00
|
|
|
go g.EmitShutdown(shutdownCtx, &wg)
|
2022-05-05 01:56:21 +00:00
|
|
|
wg.Wait()
|
2022-06-30 05:48:04 +00:00
|
|
|
}
|
|
|
|
|
2024-02-23 08:56:30 +00:00
|
|
|
// OnShutdown helps you register your shutdown handler
|
|
|
|
// the first context object is where you want to register your shutdown handler, where the context has the isolated storage.
|
|
|
|
// in your handler, you will get another context for the timeout context.
|
2022-10-03 08:01:08 +00:00
|
|
|
func OnShutdown(ctx context.Context, f ShutdownHandler) {
|
2022-10-04 09:23:43 +00:00
|
|
|
isolatedContext := GetIsolationFromContext(ctx)
|
2022-10-03 08:01:08 +00:00
|
|
|
isolatedContext.gracefulShutdown.OnShutdown(f)
|
2022-06-30 05:48:04 +00:00
|
|
|
}
|
|
|
|
|
2022-10-11 06:22:46 +00:00
|
|
|
func Shutdown(shutdownCtx context.Context) {
|
2023-02-08 09:39:02 +00:00
|
|
|
|
2023-02-08 09:30:33 +00:00
|
|
|
isolatedContext := GetIsolationFromContext(shutdownCtx)
|
2023-02-08 09:39:02 +00:00
|
|
|
if isolatedContext == defaultIsolation {
|
|
|
|
logrus.Infof("bbgo shutting down...")
|
|
|
|
} else {
|
|
|
|
logrus.Infof("bbgo shutting down (custom isolation)...")
|
|
|
|
}
|
|
|
|
|
2023-02-08 09:30:33 +00:00
|
|
|
isolatedContext.gracefulShutdown.Shutdown(shutdownCtx)
|
2022-05-05 01:56:21 +00:00
|
|
|
}
|