2022-05-05 01:56:21 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
2022-06-30 05:48:04 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"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-02 11:34:52 +00:00
|
|
|
func (g *GracefulShutdown) Shutdown(ctx context.Context) {
|
2022-05-05 01:56:21 +00:00
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(len(g.shutdownCallbacks))
|
|
|
|
|
2022-06-30 05:48:04 +00:00
|
|
|
// for each shutdown callback, we give them 10 second
|
|
|
|
shtCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
|
|
|
|
|
|
go g.EmitShutdown(shtCtx, &wg)
|
2022-05-05 01:56:21 +00:00
|
|
|
|
|
|
|
wg.Wait()
|
2022-06-30 05:48:04 +00:00
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
|
2022-10-03 08:01:08 +00:00
|
|
|
func OnShutdown(ctx context.Context, f ShutdownHandler) {
|
|
|
|
isolatedContext := NewIsolationFromContext(ctx)
|
|
|
|
isolatedContext.gracefulShutdown.OnShutdown(f)
|
2022-06-30 05:48:04 +00:00
|
|
|
}
|
|
|
|
|
2022-10-03 08:01:08 +00:00
|
|
|
func Shutdown(ctx context.Context) {
|
2022-06-30 05:48:04 +00:00
|
|
|
logrus.Infof("shutting down...")
|
|
|
|
|
2022-10-03 08:01:08 +00:00
|
|
|
isolatedContext := NewIsolationFromContext(ctx)
|
|
|
|
todo := context.WithValue(context.TODO(), IsolationContextKey, isolatedContext)
|
|
|
|
|
|
|
|
timeoutCtx, cancel := context.WithTimeout(todo, 30*time.Second)
|
2022-10-03 08:22:41 +00:00
|
|
|
defaultIsolation.gracefulShutdown.Shutdown(timeoutCtx)
|
2022-06-30 05:48:04 +00:00
|
|
|
cancel()
|
2022-05-05 01:56:21 +00:00
|
|
|
}
|