-
Notifications
You must be signed in to change notification settings - Fork 5k
/
routine.go
80 lines (69 loc) · 1.7 KB
/
routine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package safe
import (
"context"
"fmt"
"runtime/debug"
"sync"
"github.com/cenkalti/backoff/v4"
"github.com/containous/traefik/v2/pkg/log"
)
type routineCtx func(ctx context.Context)
// Pool is a pool of go routines.
type Pool struct {
waitGroup sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
}
// NewPool creates a Pool.
func NewPool(parentCtx context.Context) *Pool {
ctx, cancel := context.WithCancel(parentCtx)
return &Pool{
ctx: ctx,
cancel: cancel,
}
}
// 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)
})
}
// Stop stops all started routines, waiting for their termination.
func (p *Pool) Stop() {
p.cancel()
p.waitGroup.Wait()
}
// Go starts a recoverable goroutine.
func Go(goroutine func()) {
GoWithRecover(goroutine, defaultRecoverGoroutine)
}
// 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{}) {
logger := log.WithoutContext()
logger.Errorf("Error in Go routine: %s", err)
logger.Errorf("Stack: %s", debug.Stack())
}
// OperationWithRecover wrap a backoff operation in a Recover.
func OperationWithRecover(operation backoff.Operation) backoff.Operation {
return func() (err error) {
defer func() {
if res := recover(); res != nil {
defaultRecoverGoroutine(res)
err = fmt.Errorf("panic in operation: %w", err)
}
}()
return operation()
}
}