-
Notifications
You must be signed in to change notification settings - Fork 53
/
queue.go
287 lines (236 loc) · 6.78 KB
/
queue.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
package main
import (
"log"
"sync"
"time"
"github.com/golang/protobuf/proto"
pduration "github.com/golang/protobuf/ptypes/duration"
tasks "google.golang.org/genproto/googleapis/cloud/tasks/v2"
)
// Queue holds all internals for a task queue
type Queue struct {
name string
state *tasks.Queue
fire chan *Task
work chan *Task
ts map[string]*Task
tsMux sync.Mutex
tokenBucket chan bool
maxDispatchesPerSecond float64
cancelTokenGenerator chan bool
cancelDispatcher chan bool
cancelWorkers chan bool
cancelled bool
paused bool
onTaskDone func(task *Task)
}
// NewQueue creates a new task queue
func NewQueue(name string, state *tasks.Queue, onTaskDone func(task *Task)) (*Queue, *tasks.Queue) {
setInitialQueueState(state)
queue := &Queue{
name: name,
state: state,
fire: make(chan *Task),
work: make(chan *Task),
ts: make(map[string]*Task),
onTaskDone: onTaskDone,
tokenBucket: make(chan bool, state.GetRateLimits().GetMaxBurstSize()),
maxDispatchesPerSecond: state.GetRateLimits().GetMaxDispatchesPerSecond(),
cancelTokenGenerator: make(chan bool, 1),
cancelDispatcher: make(chan bool, 1),
cancelWorkers: make(chan bool, 1),
}
// Fill the token bucket
for i := 0; i < int(state.GetRateLimits().GetMaxBurstSize()); i++ {
queue.tokenBucket <- true
}
return queue, state
}
func (queue *Queue) setTask(taskName string, task *Task) {
queue.tsMux.Lock()
defer queue.tsMux.Unlock()
queue.ts[taskName] = task
}
func (queue *Queue) removeTask(taskName string) {
queue.setTask(taskName, nil)
}
func setInitialQueueState(queueState *tasks.Queue) {
if queueState.GetRateLimits() == nil {
queueState.RateLimits = &tasks.RateLimits{}
}
if queueState.GetRateLimits().GetMaxDispatchesPerSecond() == 0 {
queueState.RateLimits.MaxDispatchesPerSecond = 500.0
}
if queueState.GetRateLimits().GetMaxBurstSize() == 0 {
queueState.RateLimits.MaxBurstSize = 100
}
if queueState.GetRateLimits().GetMaxConcurrentDispatches() == 0 {
queueState.RateLimits.MaxConcurrentDispatches = 1000
}
if queueState.GetRetryConfig() == nil {
queueState.RetryConfig = &tasks.RetryConfig{}
}
if queueState.GetRetryConfig().GetMaxAttempts() == 0 {
queueState.RetryConfig.MaxAttempts = 100
}
if queueState.GetRetryConfig().GetMaxDoublings() == 0 {
queueState.RetryConfig.MaxDoublings = 16
}
if queueState.GetRetryConfig().GetMinBackoff() == nil {
queueState.RetryConfig.MinBackoff = &pduration.Duration{
Nanos: 100000000,
}
}
if queueState.GetRetryConfig().GetMaxBackoff() == nil {
queueState.RetryConfig.MaxBackoff = &pduration.Duration{
Seconds: 3600,
}
}
queueState.State = tasks.Queue_RUNNING
}
func (queue *Queue) runWorkers() {
for i := 0; i < int(queue.state.GetRateLimits().GetMaxConcurrentDispatches()); i++ {
go queue.runWorker()
}
}
func (queue *Queue) runWorker() {
for {
select {
case task := <-queue.work:
task.Attempt()
case <-queue.cancelWorkers:
// Forward for next worker
queue.cancelWorkers <- true
return
}
}
}
func (queue *Queue) runTokenGenerator() {
period := time.Second / time.Duration(queue.maxDispatchesPerSecond)
// Use Timer with Reset() in place of time.Ticker as the latter was causing high CPU usage in Docker
t := time.NewTimer(period)
for {
select {
case <-t.C:
select {
case queue.tokenBucket <- true:
// Added token
t.Reset(period)
case <-queue.cancelTokenGenerator:
return
}
case <-queue.cancelTokenGenerator:
if !t.Stop() {
<-t.C
}
return
}
}
}
func (queue *Queue) runDispatcher() {
for {
select {
// Consume a token
case <-queue.tokenBucket:
select {
// Wait for task
case task := <-queue.fire:
// Pass on to workers
queue.work <- task
case <-queue.cancelDispatcher:
return
}
case <-queue.cancelDispatcher:
return
}
}
}
// Run starts the queue (workers, token generator and dispatcher)
func (queue *Queue) Run() {
go queue.runWorkers()
go queue.runTokenGenerator()
go queue.runDispatcher()
}
// NewTask creates a new task on the queue
func (queue *Queue) NewTask(newTaskState *tasks.Task) (*Task, *tasks.Task) {
task := NewTask(queue, newTaskState, func(task *Task) {
queue.removeTask(task.state.GetName())
queue.onTaskDone(task)
})
taskState := proto.Clone(task.state).(*tasks.Task)
queue.setTask(taskState.GetName(), task)
task.Schedule()
return task, taskState
}
// Delete stops, purges and removes the queue
func (queue *Queue) Delete() {
if !queue.cancelled {
queue.cancelled = true
log.Println("Stopping queue")
queue.cancelTokenGenerator <- true
queue.cancelDispatcher <- true
queue.cancelWorkers <- true
queue.Purge()
}
}
// Purge purges all tasks from the queue
// - Normally this is a fire-and-forget operation, but it returns a WaitGroup to allow HardReset to wait for completion
func (queue *Queue) Purge() *sync.WaitGroup {
waitGroup := sync.WaitGroup{}
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
queue.tsMux.Lock()
defer queue.tsMux.Unlock()
for _, task := range queue.ts {
// Avoid task firing
if task != nil {
task.Delete()
}
}
}()
return &waitGroup
}
// Goes beyond `Purge` behaviour to synchronously delete all tasks and their name handles
func (queue *Queue) HardReset(s *Server) {
waitGroup := queue.Purge()
waitGroup.Wait()
// This is still a bit awkward - we can't *guarantee* the task is fully deleted even after the WaitGroup because:
// - Purge() calls task.Delete()
// - task.Delete() writes to a buffered `cancel` channel
// - task.Schedule() reads from that buffered channel in a separate goroutine
// - When that goroutine sees the task is cancelled, it sets the task value to nil in the tasks map
//
// We need to be certain that we only remove the task from map *after* that completes, otherwise the task name will
// be reinserted with the nil value. At the moment the only easy way I can think of is to sleep for a very short
// period to allow the tasks' internal goroutines to fire first.
time.Sleep(10 * time.Millisecond)
queue.tsMux.Lock()
defer queue.tsMux.Unlock()
for taskName, task := range queue.ts {
if task != nil {
// The naive "sleep till it deletes" approach described above is too naive...
panic("Expected task to be deleted by now!")
}
delete(queue.ts, taskName)
s.hardDeleteTask(taskName)
}
}
// Pause pauses the queue
func (queue *Queue) Pause() {
if !queue.paused {
queue.paused = true
queue.state.State = tasks.Queue_PAUSED
queue.cancelDispatcher <- true
queue.cancelWorkers <- true
}
}
// Resume resumes a paused queue
func (queue *Queue) Resume() {
if queue.paused {
queue.paused = false
queue.state.State = tasks.Queue_RUNNING
go queue.runDispatcher()
go queue.runWorkers()
}
}