traefik/pkg/safe/routine.go

81 lines
1.7 KiB
Go
Raw Normal View History

package safe
import (
"context"
2016-12-08 12:32:12 +00:00
"fmt"
"runtime/debug"
"sync"
2020-02-26 09:36:05 +00:00
"github.com/cenkalti/backoff/v4"
"github.com/traefik/traefik/v2/pkg/log"
)
type routineCtx func(ctx context.Context)
2020-05-11 10:06:07 +00:00
// Pool is a pool of go routines.
type Pool struct {
waitGroup sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
}
2020-05-11 10:06:07 +00:00
// NewPool creates a Pool.
func NewPool(parentCtx context.Context) *Pool {
ctx, cancel := context.WithCancel(parentCtx)
return &Pool{
ctx: ctx,
cancel: cancel,
}
}
2020-05-11 10:06:07 +00:00
// GoCtx starts a recoverable goroutine with a context.
func (p *Pool) GoCtx(goroutine routineCtx) {
p.waitGroup.Add(1)
Go(func() {
defer p.waitGroup.Done()
goroutine(p.ctx)
})
}
2020-05-11 10:06:07 +00:00
// Stop stops all started routines, waiting for their termination.
func (p *Pool) Stop() {
p.cancel()
p.waitGroup.Wait()
2016-11-15 19:14:11 +00:00
}
2020-05-11 10:06:07 +00:00
// Go starts a recoverable goroutine.
func Go(goroutine func()) {
GoWithRecover(goroutine, defaultRecoverGoroutine)
}
2020-05-11 10:06:07 +00:00
// GoWithRecover starts a recoverable goroutine using given customRecover() function.
func GoWithRecover(goroutine func(), customRecover func(err interface{})) {
go func() {
defer func() {
if err := recover(); err != nil {
customRecover(err)
}
}()
goroutine()
}()
}
func defaultRecoverGoroutine(err interface{}) {
2019-09-13 17:28:04 +00:00
logger := log.WithoutContext()
logger.Errorf("Error in Go routine: %s", err)
logger.Errorf("Stack: %s", debug.Stack())
}
2016-12-08 12:32:12 +00:00
2020-05-11 10:06:07 +00:00
// OperationWithRecover wrap a backoff operation in a Recover.
2016-12-08 12:32:12 +00:00
func OperationWithRecover(operation backoff.Operation) backoff.Operation {
return func() (err error) {
defer func() {
if res := recover(); res != nil {
defaultRecoverGoroutine(res)
2020-05-11 10:06:07 +00:00
err = fmt.Errorf("panic in operation: %w", err)
2016-12-08 12:32:12 +00:00
}
}()
return operation()
2016-12-08 12:32:12 +00:00
}
}