-
Notifications
You must be signed in to change notification settings - Fork 269
/
pool_impl.go
466 lines (391 loc) · 11.5 KB
/
pool_impl.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package workerpool
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/log"
cerrors "github.com/pingcap/tiflow/pkg/errors"
"github.com/pingcap/tiflow/pkg/notify"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"golang.org/x/time/rate"
)
const (
workerPoolDefaultClockSourceInterval = time.Millisecond * 100
)
type defaultPoolImpl struct {
// assume the hasher to be the trivial hasher for now
hasher Hasher
// do not resize this slice after creating the pool
workers []*worker
// used to generate handler IDs, must be accessed atomically
nextHandlerID int64
}
// NewDefaultWorkerPool creates a new WorkerPool that uses the default implementation
func NewDefaultWorkerPool(numWorkers int) WorkerPool {
return newDefaultPoolImpl(&defaultHasher{}, numWorkers)
}
func newDefaultPoolImpl(hasher Hasher, numWorkers int) *defaultPoolImpl {
workers := make([]*worker, numWorkers)
for i := 0; i < numWorkers; i++ {
workers[i] = newWorker()
}
return &defaultPoolImpl{
hasher: hasher,
workers: workers,
}
}
func (p *defaultPoolImpl) Run(ctx context.Context) error {
errg, ctx := errgroup.WithContext(ctx)
for _, worker := range p.workers {
workerFinal := worker
errg.Go(func() error {
err := workerFinal.run(ctx)
if err != nil {
return errors.Trace(err)
}
return nil
})
}
return errg.Wait()
}
func (p *defaultPoolImpl) RegisterEvent(f func(ctx context.Context, event interface{}) error) EventHandle {
handler := &defaultEventHandle{
f: f,
errCh: make(chan error, 1),
id: atomic.AddInt64(&p.nextHandlerID, 1) - 1,
}
workerID := p.hasher.Hash(handler) % int64(len(p.workers))
p.workers[workerID].addHandle(handler)
handler.worker = p.workers[workerID]
return handler
}
type handleStatus = int32
const (
handleRunning = handleStatus(iota)
handleCancelling
handleCancelled
)
type defaultEventHandle struct {
// the function to be run each time the event is triggered
f func(ctx context.Context, event interface{}) error
// must be accessed atomically
status handleStatus
// channel for the error returned by f
errCh chan error
// the worker that the handle is associated with
worker *worker
// identifier for this handle. No significant usage for now.
// Might be used to support consistent hashing in the future,
// so that the pool can be resized efficiently.
id int64
// whether there is a valid timer handler, must be accessed atomically
hasTimer int32
// the time when timer was triggered the last time
lastTimer time.Time
// minimum interval between two timer calls
timerInterval time.Duration
// the handler for the timer
timerHandler func(ctx context.Context) error
// whether this is a valid errorHandler, must be accessed atomically
hasErrorHandler int32
// the error handler, called when the handle meets an error (which is returned by f)
errorHandler func(err error)
}
func (h *defaultEventHandle) AddEvent(ctx context.Context, event interface{}) error {
status := atomic.LoadInt32(&h.status)
if status != handleRunning {
return cerrors.ErrWorkerPoolHandleCancelled.GenWithStackByArgs()
}
failpoint.Inject("addEventDelayPoint", func() {})
task := task{
handle: h,
f: func(ctx1 context.Context) error {
return h.f(ctx, event)
},
}
select {
case <-ctx.Done():
return errors.Trace(ctx.Err())
case h.worker.taskCh <- task:
}
return nil
}
func (h *defaultEventHandle) AddEvents(ctx context.Context, events []interface{}) error {
status := atomic.LoadInt32(&h.status)
if status != handleRunning {
return cerrors.ErrWorkerPoolHandleCancelled.GenWithStackByArgs()
}
failpoint.Inject("addEventDelayPoint", func() {})
task := task{
handle: h,
f: func(ctx1 context.Context) error {
for _, event := range events {
err := h.f(ctx, event)
if err != nil {
return err
}
}
return nil
},
}
select {
case <-ctx.Done():
return errors.Trace(ctx.Err())
case h.worker.taskCh <- task:
}
return nil
}
func (h *defaultEventHandle) SetTimer(ctx context.Context, interval time.Duration, f func(ctx context.Context) error) EventHandle {
// mark the timer handler function as invalid
atomic.StoreInt32(&h.hasTimer, 0)
// wait for `hasTimer` to take effect, otherwise we might have a data race, if there was a previous handler.
h.worker.synchronize()
h.timerInterval = interval
h.timerHandler = func(ctx1 context.Context) error {
return f(ctx)
}
// mark the timer handler function as valid
atomic.StoreInt32(&h.hasTimer, 1)
return h
}
func (h *defaultEventHandle) Unregister() {
if !atomic.CompareAndSwapInt32(&h.status, handleRunning, handleCancelled) {
// call synchronize so that the returning of Unregister cannot race
// with the calling of the errorHandler, if an error is already being processed.
h.worker.synchronize()
// already cancelled
return
}
failpoint.Inject("unregisterDelayPoint", func() {})
// call synchronize so that all function executions related to this handle will be
// linearized BEFORE Unregister.
h.worker.synchronize()
h.doCancel(cerrors.ErrWorkerPoolHandleCancelled.GenWithStackByArgs())
}
func (h *defaultEventHandle) GracefulUnregister(ctx context.Context, timeout time.Duration) error {
if !atomic.CompareAndSwapInt32(&h.status, handleRunning, handleCancelling) {
// already cancelling or cancelled
return nil
}
defer func() {
if !atomic.CompareAndSwapInt32(&h.status, handleCancelling, handleCancelled) {
// already cancelled
return
}
// call synchronize so that all function executions related to this handle will be
// linearized BEFORE Unregister.
h.worker.synchronize()
h.doCancel(cerrors.ErrWorkerPoolHandleCancelled.GenWithStackByArgs())
}()
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
doneCh := make(chan struct{})
select {
case <-ctx.Done():
return cerrors.ErrWorkerPoolGracefulUnregisterTimedOut.GenWithStackByArgs()
case h.worker.taskCh <- task{
handle: h,
doneCh: doneCh,
}:
}
select {
case <-ctx.Done():
return cerrors.ErrWorkerPoolGracefulUnregisterTimedOut.GenWithStackByArgs()
case <-doneCh:
}
return nil
}
// callers of doCancel need to check h.isCancelled first.
// DO NOT call doCancel multiple times on the same handle.
func (h *defaultEventHandle) doCancel(err error) {
h.worker.removeHandle(h)
if atomic.LoadInt32(&h.hasErrorHandler) == 1 {
h.errorHandler(err)
}
h.errCh <- err
close(h.errCh)
}
func (h *defaultEventHandle) ErrCh() <-chan error {
return h.errCh
}
func (h *defaultEventHandle) OnExit(f func(err error)) EventHandle {
atomic.StoreInt32(&h.hasErrorHandler, 0)
h.worker.synchronize()
h.errorHandler = f
atomic.StoreInt32(&h.hasErrorHandler, 1)
return h
}
func (h *defaultEventHandle) HashCode() int64 {
return h.id
}
func (h *defaultEventHandle) cancelWithErr(err error) {
if !atomic.CompareAndSwapInt32(&h.status, handleRunning, handleCancelled) {
// already cancelled
return
}
h.doCancel(err)
}
func (h *defaultEventHandle) durationSinceLastTimer() time.Duration {
return time.Since(h.lastTimer)
}
func (h *defaultEventHandle) doTimer(ctx context.Context) error {
if atomic.LoadInt32(&h.hasTimer) == 0 {
return nil
}
if h.durationSinceLastTimer() < h.timerInterval {
return nil
}
err := h.timerHandler(ctx)
if err != nil {
return errors.Trace(err)
}
h.lastTimer = time.Now()
return nil
}
type task struct {
handle *defaultEventHandle
f func(ctx context.Context) error
doneCh chan struct{} // only used in implementing GracefulUnregister
}
type worker struct {
taskCh chan task
handles map[*defaultEventHandle]struct{}
handleRWLock sync.RWMutex
// A message is passed to handleCancelCh when we need to wait for the
// current execution of handler to finish. Should be BLOCKING.
handleCancelCh chan struct{}
// must be accessed atomically
isRunning int32
// notifies exits of run()
stopNotifier notify.Notifier
slowSynchronizeThreshold time.Duration
slowSynchronizeLimiter *rate.Limiter
}
func newWorker() *worker {
return &worker{
taskCh: make(chan task, 128),
handles: make(map[*defaultEventHandle]struct{}),
handleCancelCh: make(chan struct{}), // this channel must be unbuffered, i.e. blocking
slowSynchronizeThreshold: 10 * time.Second,
slowSynchronizeLimiter: rate.NewLimiter(rate.Every(time.Second*5), 1),
}
}
func (w *worker) run(ctx context.Context) error {
ticker := time.NewTicker(workerPoolDefaultClockSourceInterval)
atomic.StoreInt32(&w.isRunning, 1)
defer func() {
ticker.Stop()
atomic.StoreInt32(&w.isRunning, 0)
w.stopNotifier.Notify()
}()
for {
select {
case <-ctx.Done():
return errors.Trace(ctx.Err())
case task := <-w.taskCh:
if atomic.LoadInt32(&task.handle.status) == handleCancelled {
// ignored cancelled handle
continue
}
if task.doneCh != nil {
close(task.doneCh)
if task.f != nil {
log.L().DPanic("unexpected message handler func in cancellation task", zap.Stack("stack"))
}
continue
}
err := task.f(ctx)
if err != nil {
task.handle.cancelWithErr(err)
}
case <-ticker.C:
var handleErrs []struct {
h *defaultEventHandle
e error
}
w.handleRWLock.RLock()
for handle := range w.handles {
if atomic.LoadInt32(&handle.status) == handleCancelled {
// ignored cancelled handle
continue
}
err := handle.doTimer(ctx)
if err != nil {
handleErrs = append(handleErrs, struct {
h *defaultEventHandle
e error
}{handle, err})
}
}
w.handleRWLock.RUnlock()
// cancelWithErr must be called out side of the loop above,
// to avoid deadlock.
for _, handleErr := range handleErrs {
handleErr.h.cancelWithErr(handleErr.e)
}
case <-w.handleCancelCh:
}
}
}
// synchronize waits for the worker to loop at least once, or to exit.
func (w *worker) synchronize() {
if atomic.LoadInt32(&w.isRunning) == 0 {
return
}
receiver, err := w.stopNotifier.NewReceiver(time.Millisecond * 100)
if err != nil {
if cerrors.ErrOperateOnClosedNotifier.Equal(errors.Cause(err)) {
return
}
log.Panic("unexpected error", zap.Error(err))
}
defer receiver.Stop()
startTime := time.Now()
for {
workerHasFinishedLoop := false
select {
case w.handleCancelCh <- struct{}{}:
workerHasFinishedLoop = true
case <-receiver.C:
}
if workerHasFinishedLoop || atomic.LoadInt32(&w.isRunning) == 0 {
break
}
if time.Since(startTime) > w.slowSynchronizeThreshold &&
w.slowSynchronizeLimiter.Allow() {
// likely the workerpool has deadlocked, or there is a bug
// in the event handlers.
logWarn("synchronize is taking too long, report a bug",
zap.Duration("duration", time.Since(startTime)),
zap.Stack("stacktrace"))
}
}
}
// A delegate to log.Warn. It exists only for testing.
var logWarn = log.Warn
func (w *worker) addHandle(handle *defaultEventHandle) {
w.handleRWLock.Lock()
defer w.handleRWLock.Unlock()
w.handles[handle] = struct{}{}
}
func (w *worker) removeHandle(handle *defaultEventHandle) {
w.handleRWLock.Lock()
defer w.handleRWLock.Unlock()
delete(w.handles, handle)
}