This repository has been archived by the owner on Feb 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
queueservice.go
440 lines (395 loc) · 14 KB
/
queueservice.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
package worker
import (
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/taskcluster/httpbackoff"
"github.com/taskcluster/taskcluster-client-go"
"github.com/taskcluster/taskcluster-worker/runtime"
"github.com/taskcluster/taskcluster-worker/runtime/atomics"
"github.com/taskcluster/taskcluster-worker/runtime/client"
)
type (
// queueMessagesList is the unmarshalled response from an Azure message queue request.
queueMessagesList struct {
XMLName xml.Name `xml:"QueueMessagesList"`
QueueMessages []queueMessage `xml:"QueueMessage"`
}
// queueMessage represents part of the message response from an
// Azure message queue request
queueMessage struct {
MessageID string `xml:"MessageId"`
PopReceipt string `xml:"PopReceipt"`
DequeueCount int `xml:"DequeueCount"`
MessageText string `xml:"MessageText"`
}
// messageQueue represents a queue containing a pair of signed
// delete and polling urls. A given worker type will have 1 or more messageQueues
// which should be polled in order for tasks.
messageQueue struct {
SignedDeleteURL string `json:"signedDeleteUrl"`
SignedPollURL string `json:"signedPollUrl"`
}
taskMessage struct {
TaskID string `json:"taskId"`
RunID int `json:"runId"`
signedDeleteURL string
}
// QueueService is an interface describing the methods responsible for claiming
// work from Azure queues.
QueueService interface {
Done()
Start() <-chan *taskClaim
Stop()
}
queueService struct {
mu sync.RWMutex
capacity int
interval int
tc chan *taskClaim
queues []messageQueue
expires tcclient.Time
expirationOffset int
client client.Queue
provisionerID string
workerType string
workerID string
workerGroup string
monitor runtime.Monitor
halt atomics.Bool
maxTasksToRun int
claimedTasks int
}
)
// Start will begin the task claiming loop and claim as many tasks as the worker
// capacity allows. Claimed tasks will be returned on a channel for consumers
// to run.
func (q *queueService) Start() <-chan *taskClaim {
q.tc = make(chan *taskClaim)
go func() {
for !q.halt.Get() {
claimSize, finished := q.claimSize()
if finished {
break
}
tasks := q.retrieveTasksFromQueue(claimSize)
q.claimTasks(tasks)
time.Sleep(time.Duration(q.interval) * time.Second)
}
close(q.tc)
}()
return q.tc
}
// claimSize returns the number of tasks that should be claimed, based on
// available capacity, and the number of tasks already claimed versus the
// maximum claim total. Additionally it returns a boolean indicating if
// the maximum total of claimed tasks is equal to the number of claimed
// tasks (which also implies size == 0).
func (q *queueService) claimSize() (size int, finished bool) {
q.mu.RLock()
defer q.mu.RUnlock()
if q.maxTasksToRun > 0 {
remaining := q.maxTasksToRun - q.claimedTasks
size = min(remaining, q.capacity)
finished = remaining == 0
return
}
size = q.capacity
return
}
// math.Min is for floats, let's avoid casting and float arithmetic...
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Stop will set the current capacity to 0 so no tasks are claimed.
func (q *queueService) Stop() {
q.halt.Set(true)
return
}
// Done is called each time a task is completed. Current capacity will be incremented
// each time Done is called.
func (q *queueService) Done() {
q.mu.Lock()
q.capacity++
q.mu.Unlock()
}
func (q *queueService) claimTasks(tasks []*taskMessage) {
var wg sync.WaitGroup
wg.Add(len(tasks))
for _, task := range tasks {
go func(task *taskMessage) {
defer wg.Done()
claim, err := q.claimTask(task)
if err != nil {
q.monitor.WithTags(map[string]string{
"taskID": task.TaskID,
"runID": fmt.Sprintf("%d", task.RunID),
"error": err.Error(),
}).Warn("Could not claim task")
return
}
q.mu.Lock()
q.capacity--
q.claimedTasks++
q.mu.Unlock()
q.tc <- claim
}(task)
}
wg.Wait()
return
}
func (q *queueService) claimTask(task *taskMessage) (*taskClaim, error) {
claim, err := claimTask(q.client, task.TaskID, task.RunID, q.workerID, q.workerGroup, q.monitor)
if err != nil {
switch err := err.(type) {
case *updateError:
if err.statusCode == 401 || err.statusCode == 403 || err.statusCode >= 500 {
// Do not delete the message if task could not be claimed because of server
// or authorization failures
return nil, errors.New("error claiming task: task was *not* deleted from Azure")
}
}
_ = q.deleteFromAzure(task.signedDeleteURL)
return nil, fmt.Errorf("Error when attempting to claim task %v. Error is non-recoverable so task was (hopefully) deleted from Azure. Cause: %v", task.TaskID, err)
}
_ = q.deleteFromAzure(task.signedDeleteURL)
return claim, nil
}
// deleteFromAzure will attempt to delete a task from the Azure queue and
// return an error in case of failure
func (q *queueService) deleteFromAzure(deleteURL string) error {
// Messages are deleted from the Azure queue with a DELETE request to the
// SignedDeleteURL from the Azure queue object returned from
// queue.pollTaskURLs.
// Also remark that the worker must delete messages if the queue.claimTask
// operations fails with a 4xx error. A 400 hundred range error implies
// that the task wasn't created, not scheduled or already claimed, in
// either case the worker should delete the message as we don't want
// another worker to receive message later.
q.monitor.Info("Deleting task from Azure queue")
httpCall := func() (*http.Response, error, error) {
req, err := http.NewRequest("DELETE", deleteURL, nil)
if err != nil {
return nil, nil, err
}
resp, err := http.DefaultClient.Do(req)
return resp, err, nil
}
_, _, err := httpbackoff.Retry(httpCall)
// Notice, that failure to delete messages from Azure queue is serious, as
// it wouldn't manifest itself in an immediate bug. Instead if messages
// repeatedly fails to be deleted, it would result in a lot of unnecessary
// calls to the queue and the Azure queue. The worker will likely continue
// to work, as the messages eventually disappears when their deadline is
// reached. However, the provisioner would over-provision aggressively as
// it would be unable to tell the number of pending tasks. And the worker
// would spend a lot of time attempting to claim faulty messages. For these
// reasons outlined above it's strongly advised that workers logs failures
// to delete messages from Azure queues.
if err != nil {
q.monitor.WithTags(map[string]string{
"error": err.Error(),
"url": deleteURL,
}).Warn("Not able to delete task from azure queue")
return err
}
q.monitor.Info("Successfully deleted task from azure queue")
return nil
}
// Retrieves the number of tasks requested from the Azure queues.
func (q *queueService) pollTaskURL(messageQueue *messageQueue, ntasks int) ([]*taskMessage, error) {
taskMessages := []*taskMessage{}
var r queueMessagesList
// To poll an Azure Queue the worker must do a `GET` request to the
// `SignedPollURL` from the object, representing the Azure queue. To
// receive multiple messages at once the parameter `&numofmessages=N`
// may be appended to `SignedPollURL`. The parameter `N` is the
// maximum number of messages desired, `N` can be up to 32.
n := int(math.Min(32, float64(ntasks)))
u := fmt.Sprintf("%s%s%d", messageQueue.SignedPollURL, "&numofmessages=", n)
resp, _, err := httpbackoff.Get(u)
if err != nil {
return nil, err
}
// When executing a `GET` request to `SignedPollURL` from an Azure queue object,
// the request will return an XML document on the form:
//
// ```xml
// <QueueMessagesList>
// <QueueMessage>
// <MessageId>...</MessageId>
// <InsertionTime>...</InsertionTime>
// <ExpirationTime>...</ExpirationTime>
// <PopReceipt>...</PopReceipt>
// <TimeNextVisible>...</TimeNextVisible>
// <DequeueCount>...</DequeueCount>
// <MessageText>...</MessageText>
// </QueueMessage>
// ...
// </QueueMessagesList>
// ```
// We unmarshal the response into go objects, using the go xml decoder.
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
if err := xml.Unmarshal(data, &r); err != nil {
//if err := xml.NewDecoder(resp.Body).Decode(&queueMessagesList); err != nil {
q.monitor.WithTags(map[string]string{
"body": string(data),
"error": err.Error(),
}).Debugf("Not able to xml decode the response from the Azure queue")
return nil, fmt.Errorf("Not able to xml decode the response from the Azure queue. Body: %s, Error: %s", resp.Body, err)
}
if len(r.QueueMessages) == 0 {
q.monitor.Debug("Zero tasks returned in Azure XML queueMessagesList")
return []*taskMessage{}, nil
}
// Utility method for replacing a placeholder within a uri with
// a string value which first must be uri encoded...
detokeniseURI := func(URI, placeholder, rawValue string) string {
return strings.Replace(URI, placeholder, strings.Replace(url.QueryEscape(rawValue), "+", "%20", -1), -1)
}
for _, qm := range r.QueueMessages {
// Before using the SignedDeleteURL the worker must replace the placeholder
// {{messageId}} with the contents of the <MessageId> tag. It is also
// necessary to replace the placeholder {{popReceipt}} with the URI encoded
// contents of the <PopReceipt> tag. Notice, that the worker must URI
// encode the contents of <PopReceipt> before substituting into the
// SignedDeleteURL. Otherwise, the worker will experience intermittent
// failures.
signedDeleteURL := detokeniseURI(
detokeniseURI(
messageQueue.SignedDeleteURL,
"{{messageId}}",
qm.MessageID,
),
"{{popReceipt}}",
qm.PopReceipt,
)
// Workers should read the value of the `<DequeueCount>` and log messages
// that alert the operator if a message has been dequeued a significant
// number of times, for example 15 or more.
if qm.DequeueCount >= 15 {
q.monitor.Warnf("Queue Message with message id %v has been dequeued %v times!", qm.MessageID, qm.DequeueCount)
err := q.deleteFromAzure(signedDeleteURL)
if err != nil {
q.monitor.Warnf("Not able to call Azure delete URL %v. %v", signedDeleteURL, err)
}
}
// To find the task referenced in a message the worker must base64
// decode and JSON parse the contents of the <MessageText> tag. This
// would return an object on the form: {taskId, runId}.
m, err := base64.StdEncoding.DecodeString(qm.MessageText)
if err != nil {
// try to delete from Azure, if it fails, nothing we can do about it
// not very serious - another worker will try to delete it
q.monitor.WithTag("messageText", qm.MessageText).Errorf("Not able to base64 decode the Message Text in Azure message response.")
q.monitor.WithTag("messageID", qm.MessageID).Info("Deleting from Azure queue as other workers will have the same problem.")
err2 := q.deleteFromAzure(signedDeleteURL)
if err2 != nil {
q.monitor.WithTags(map[string]string{
"messageID": qm.MessageID,
"url": signedDeleteURL,
"error": err2.Error(),
}).Warn("Not able to call Azure delete URL")
}
return nil, err2
}
// initialise fields of TaskRun not contained in json string m
tm := &taskMessage{
signedDeleteURL: signedDeleteURL,
}
// now populate remaining json fields of TaskMessage from json string m
err = json.Unmarshal(m, &tm)
if err != nil {
q.monitor.WithTags(map[string]string{
"error": err.Error(),
"message": string(m),
}).Warn("Not able to unmarshal json from base64 decoded MessageText")
err := q.deleteFromAzure(signedDeleteURL)
if err != nil {
q.monitor.WithTags(map[string]string{
"url": signedDeleteURL,
"error": err.Error(),
}).Warn("Not able to call Azure delete URL")
}
continue
}
taskMessages = append(taskMessages, tm)
}
return taskMessages, nil
}
// Refreshes a list of task queue urls. Each task queue contains a pair of signed urls
// used for polling and deleting messages.
func (q *queueService) refreshMessageQueueURLs() error {
// Attempt to wait until expiration gets closer before refreshing. No
// need to do it more frequently.
if !q.shouldRefreshQueueUrls() {
return nil
}
q.monitor.Debug("Refreshing Azure message queue urls")
signedURLs, err := q.client.PollTaskUrls(q.provisionerID, q.workerType)
if err != nil {
q.monitor.WithTag("error", err.Error()).Warn("Error retrieving message queue urls.")
return errors.New("error retrieving message queue urls")
}
messageQueues := []messageQueue{}
for _, pair := range signedURLs.Queues {
messageQueues = append(messageQueues, messageQueue(pair))
}
q.mu.Lock()
q.queues = messageQueues
q.expires = signedURLs.Expires
q.mu.Unlock()
q.monitor.Debugf("Refreshed %d Azure queue task urls", len(messageQueues))
return nil
}
func (q *queueService) retrieveTasksFromQueue(ntasks int) []*taskMessage {
_ = q.refreshMessageQueueURLs()
tasks := []*taskMessage{}
for _, queue := range q.queues {
// Continue polling the Azure queue until either enough messages have been retrieved
// or the queue has no more messages.
for {
// It hopefully would never be greater, but just incase, we would want to return
// and run what tasks we do have.
if len(tasks) >= ntasks {
return tasks
}
messages, err := q.pollTaskURL(&queue, ntasks-len(tasks))
if err != nil {
q.monitor.Warnf("Could not retrieve tasks from the Azure queue. %s", err)
break
}
if len(messages) == 0 {
break
}
tasks = append(tasks, messages...)
}
}
return tasks
}
// Evaluate if the current time is getting close to the url expiration as decided
// by the ExpirationOffset.
func (q *queueService) shouldRefreshQueueUrls() bool {
if len(q.queues) == 0 {
return true
}
// If the duration between Expiration and current time is less than the expiration
// off set then it's time to refresh the urls
if int(time.Until(time.Time(q.expires)).Seconds()) < q.expirationOffset {
return true
}
return false
}