-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecutor.go
272 lines (239 loc) · 5.15 KB
/
executor.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
package executor
import (
"errors"
"runtime"
"sync"
"sync/atomic"
"time"
)
type ExecutorParams struct {
NumWorkers int
MaxJobQueueCapacity int
MaxJobQueueWaitTime time.Duration
ShutdownTimeout time.Duration
}
/*
DefaultExecutorParams generates a default param struct for
creating Executor.
NumWorkers: number of CPU report by go runtime library
MaxJobQueueCapacity: 1000
MaxJobQueueWaitTime: 30 seconds
ShutdownTimeout: 3 seconds
*/
func DefaultExecutorParams() ExecutorParams {
return ExecutorParams{
NumWorkers: runtime.NumCPU(),
MaxJobQueueCapacity: 1000,
MaxJobQueueWaitTime: 30 * time.Second,
ShutdownTimeout: 3 * time.Second,
}
}
func (p ExecutorParams) validate() error {
if p.NumWorkers <= 0 {
return errors.New("executor params: non positive NumWorkers")
}
if p.MaxJobQueueCapacity < 0 {
return errors.New("executor params: negative MaxJobQueueCapacity")
}
return nil
}
type executorJob struct {
runnable func()
ts time.Time
done func()
}
func (ej *executorJob) invoke() {
ej.runnable()
ej.done()
}
/*
worker internal states:
Unstarted
Idle: waiting for a job to execute
Running: executing a job
Stopped
*/
type worker struct {
done chan struct{}
jobChan chan *executorJob
executor *Executor
}
func newWorker(e *Executor) *worker {
return &worker{
done: make(chan struct{}),
jobChan: make(chan *executorJob),
executor: e,
}
}
func (w *worker) Run() {
for {
job := w.executor.tryGetJobAndRegister(w)
if job != nil {
job.invoke()
} else {
select {
case job := <-w.jobChan:
job.invoke()
case <-w.done:
return
}
}
}
}
func (w *worker) Stop() {
close(w.done)
}
func (w *worker) Take(j *executorJob) {
w.jobChan <- j
}
type Executor struct {
// parameters, immutable fields
numWorkers int
maxJobQueueCapacity int
maxJobQueueWaitTime time.Duration
shutdownTimeout time.Duration
// core objects
mu sync.Mutex
jobQueue []*executorJob
stopChan chan struct{}
workerWaitList chan *worker
stopped bool
workers []*worker
// stats
inflightJobs int32
}
func NewExecutor(params ExecutorParams) (*Executor, error) {
exec, err := newExecutor(params)
if err != nil {
return nil, err
}
for i := 0; i < params.NumWorkers; i++ {
w := newWorker(exec)
exec.workers[i] = w
go w.Run()
}
go exec.truncateLoop()
return exec, err
}
func newExecutor(params ExecutorParams) (*Executor, error) {
if err := params.validate(); err != nil {
return nil, err
}
return &Executor{
numWorkers: params.NumWorkers,
maxJobQueueCapacity: params.MaxJobQueueCapacity,
maxJobQueueWaitTime: params.MaxJobQueueWaitTime,
jobQueue: make([]*executorJob, 0),
stopChan: make(chan struct{}),
workerWaitList: make(chan *worker, params.NumWorkers),
workers: make([]*worker, params.NumWorkers),
inflightJobs: 0,
stopped: false,
shutdownTimeout: params.ShutdownTimeout,
}, nil
}
func (e *Executor) truncateLoop() {
ticker := time.NewTicker(e.maxJobQueueWaitTime)
for {
select {
case <-e.stopChan:
// truncate all
jobs := e.cleanJobQueue()
go e.dropJobs(jobs)
return
case <-ticker.C:
jobs := e.removeTimeoutJobsFromQueue()
go e.dropJobs(jobs)
}
}
}
func (e *Executor) removeTimeoutJobsFromQueue() []*executorJob {
e.mu.Lock()
defer e.mu.Unlock()
now := time.Now()
var i int
for i = 0; i < len(e.jobQueue); i++ {
if now.Sub(e.jobQueue[i].ts) < e.maxJobQueueWaitTime {
break
}
}
jobs := e.jobQueue[:i]
e.jobQueue = e.jobQueue[i:]
return jobs
}
func (e *Executor) cleanJobQueue() []*executorJob {
e.mu.Lock()
defer e.mu.Unlock()
jobs := e.jobQueue
e.jobQueue = nil
return jobs
}
func (e *Executor) dropJobs(jobs []*executorJob) {
for _, j := range jobs {
j.done()
}
}
func (e *Executor) tryGetJobAndRegister(w *worker) *executorJob {
e.mu.Lock()
defer e.mu.Unlock()
if e.stopped {
return nil
}
if len(e.jobQueue) > 0 {
head := e.jobQueue[0]
e.jobQueue = e.jobQueue[1:]
return head
}
e.workerWaitList <- w
return nil
}
func (e *Executor) pushLocked(job *executorJob) error {
if len(e.jobQueue) == e.maxJobQueueCapacity {
return errors.New("executor: queue over flow")
}
e.jobQueue = append(e.jobQueue, job)
return nil
}
func (e *Executor) Submit(runnable func()) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.stopped {
return errors.New("executor: submit a job to stopped executor")
}
atomic.AddInt32(&e.inflightJobs, 1)
job := &executorJob{
runnable: runnable,
ts: time.Now(),
done: func() { atomic.AddInt32(&e.inflightJobs, -1) },
}
select {
case w := <-e.workerWaitList:
w.Take(job)
default:
return e.pushLocked(job)
}
return nil
}
func (e *Executor) Stop() {
e.mu.Lock()
// stop new job submittion and workers acquiring job first
e.stopped = true
e.mu.Unlock()
close(e.stopChan)
for _, w := range e.workers {
w.Stop()
}
// Graceful shutdown
afterC := time.After(e.shutdownTimeout)
for {
inflightJobs := atomic.LoadInt32(&e.inflightJobs)
if inflightJobs == 0 {
break
}
select {
case <-afterC:
return
case <-time.After(100 * time.Millisecond):
}
}
}