-
Notifications
You must be signed in to change notification settings - Fork 8
/
run.go
257 lines (225 loc) · 4.91 KB
/
run.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package run
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/cuigh/auxo/data"
"github.com/cuigh/auxo/log"
"github.com/cuigh/auxo/util/debug"
)
const PkgPath = "auxo.util.run"
var (
ErrTimeout = errors.New("timeout")
ErrPoolShutdown = errors.New("pool is shut down")
ErrPoolFull = errors.New("pool reach max queue size")
)
type Recovery func(e interface{})
type Canceler interface {
Cancel()
}
func handlePanic(r Recovery, e interface{}) {
if r == nil {
log.Get(PkgPath).Errorf("PANIC: %v, stack: %s", e, debug.StackSkip(1))
} else {
r(e)
}
}
// Safe call fn with recover.
func Safe(fn func(), r Recovery) {
defer func() {
if e := recover(); e != nil {
handlePanic(r, e)
}
}()
fn()
}
// Count call fn with recover, and process WaitGroup automatically.
func Count(g *sync.WaitGroup, fn func(), r Recovery) {
g.Add(1)
defer func() {
g.Done()
if e := recover(); e != nil {
handlePanic(r, e)
}
}()
fn()
}
// Pipeline calls all functions in order. If a function returns an error, Pipeline will return this error immediately.
func Pipeline(fns ...func() error) error {
for _, fn := range fns {
if err := fn(); err != nil {
return err
}
}
return nil
}
// Schedule call fn with recover continuously. It returns a Canceler that can
// be used to cancel the call using its Cancel method.
func Schedule(d time.Duration, fn func(), r Recovery) Canceler {
s := &scheduler{
d: d,
fn: fn,
r: r,
state: 1,
}
s.timer = time.AfterFunc(d, s.schedule)
return s
}
type scheduler struct {
d time.Duration
fn func()
r Recovery
timer *time.Timer
state int32
}
func (s *scheduler) schedule() {
if s.state == 1 {
Safe(s.fn, s.r)
s.timer = time.AfterFunc(s.d, s.schedule)
}
}
func (s *scheduler) Cancel() {
if atomic.CompareAndSwapInt32(&s.state, 1, 0) && s.timer != nil {
s.timer.Stop()
}
}
// Pool is a simple goroutine pool.
type Pool struct {
Min, Max int32
Backlog int
Idle time.Duration
Debug bool
state int32
current int32 // running goroutines
busy int32 // busy goroutines
jobs chan func()
stopper data.Chan // stop all goroutine
closer data.Chan // close idle goroutine
canceler Canceler // control canceler
logger log.Logger
}
// Start start the pool
func (p *Pool) Start() {
if atomic.CompareAndSwapInt32(&p.state, 0, 1) {
if p.Min <= 0 {
p.Min = 1
}
if p.Max <= 0 {
p.Max = 100000
} else if p.Max < p.Min {
p.Max = p.Min
}
if p.Backlog <= 0 {
p.Backlog = 10000
}
if p.Idle <= 0 {
p.Idle = time.Minute
}
p.logger = log.Get(PkgPath)
p.jobs = make(chan func(), p.Backlog)
p.stopper = make(data.Chan)
p.closer = make(data.Chan)
for i := int32(0); i < p.Min; i++ {
go p.long()
}
p.control()
}
}
// Stop shuts down the pool. Stop won't interrupt the running jobs.
func (p *Pool) Stop() {
if atomic.CompareAndSwapInt32(&p.state, 1, 0) {
close(p.stopper)
if p.canceler != nil {
p.canceler.Cancel()
}
}
}
// Wait waits the running jobs to finish.
func (p *Pool) Wait(timeout time.Duration) error {
const waitPollInterval = 500 * time.Millisecond
ctx := context.Background()
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), timeout)
defer cancel()
}
ticker := time.NewTicker(waitPollInterval)
defer ticker.Stop()
for {
if p.busy == 0 {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
// Put submits the job to pool.
func (p *Pool) Put(job func()) error {
if atomic.LoadInt32(&p.state) != 1 {
return ErrPoolShutdown
}
select {
case p.jobs <- job:
if p.busy >= p.current && p.current < p.Max {
go p.short()
}
return nil
default:
return ErrPoolFull
}
}
func (p *Pool) long() {
atomic.AddInt32(&p.current, 1)
defer atomic.AddInt32(&p.current, -1)
for {
select {
case job := <-p.jobs:
p.call(job)
case <-p.stopper:
return
}
}
}
func (p *Pool) short() {
atomic.AddInt32(&p.current, 1)
defer atomic.AddInt32(&p.current, -1)
t := time.NewTimer(p.Idle)
defer t.Stop()
for {
select {
case job := <-p.jobs:
p.call(job)
t.Reset(p.Idle)
case <-p.stopper:
return
case <-p.closer:
//log.Get(PkgPath).Debugf("run > Pool: Close goroutine by scheduler[%d/%d]", p.busy, p.current)
return
case <-t.C:
//log.Get(PkgPath).Debugf("run > Pool: Close goroutine for idle timeout[%d/%d]", p.busy, p.current)
return
}
}
}
// Adjust the number of goroutines to conserve resources.
func (p *Pool) control() {
p.canceler = Schedule(5*time.Second, func() {
if p.Debug {
p.logger.Infof("run > Pool: {min: %d, max: %d, backlog: %d, busy: %d, current: %d, jobs: %d}",
p.Min, p.Max, p.Backlog, p.busy, p.current, len(p.jobs))
}
if p.busy < p.current/2 && p.current > p.Min {
p.closer.TrySend()
}
}, nil)
}
func (p *Pool) call(fn func()) {
atomic.AddInt32(&p.busy, 1)
defer atomic.AddInt32(&p.busy, -1)
fn()
}